Skip to content
OandONEPublic

About

SharpThon (.spy) - A Python-like language with C# syntax that transpiles to C#. Write Python with braces, semicolons, and strong typing.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Repository files navigation

🐍⚡ SharpThon

A Python-like language that transpiles to C# — up to 16x faster than Python.
Benchmark based on a simple 10M loop test. Performance varies by workload.

License: MIT Alpha .NET 8.0 Sprache Cross Platform Architecture Speed


⚡ Performance

SharpThon is 16x faster than Python.

Language 10M Loop Iterations
Python 3,275 ms
SharpThon (C#) 196 ms

Same syntax, 16x the speed. The power of .NET, the simplicity of Python.


🤔 Why SharpThon?

Python offers simplicity. C# offers performance and the .NET ecosystem. SharpThon aims to combine both.

Write Python-like code with C# syntax. Transpile to clean C# and run anywhere .NET runs.

name = "OandONE"
age: int = 16

if age == 16:
    Write("Sweet sixteen!")

✨ Features

  • ✅ Python-like syntax — familiar, readable
  • ✅ C# target — transpiles to C# that can directly participate in the .NET ecosystem
  • ✅ Sprache Parser — clean C#, minimal Regex, no external tools
  • ✅ Optional type hints — x = 10 or x: int = 10
  • ✅ Constants & Readonly — const MAX = 3, readonly _host: str = "localhost"
  • ✅ Numeric types — int, long, float, double
  • ✅ str → string, Any → object — seamless C# mapping
  • ✅ Braces {} or Python-style indentation — use whichever reads better
  • ✅ Write() — similar to print() or Console.WriteLine()
  • ✅ if/elif/else — elif becomes C# else if
  • ✅ for (i in n) — becomes foreach + Enumerable.Range
  • ✅ while, ++/--
  • ✅ Functions — modifiers, type hints, parameters, and return types
  • ✅ Classes — fields, constructors, methods, access modifiers, and this
  • ✅ Comments — supports # and preserves inline // comments
  • ✅ Module imports — import other .spy files as modules
  • ✅ External libraries — require os, require json, require re, require sys, require random, require math, require time
  • ✅ using — import .NET namespaces
  • ✅ .NET namespace imports
  • ✅ C#/.NET interoperability
  • ✅ String interpolation — f"Hello {name}" → $"Hello {name}"
  • ✅ try/catch/finally — supports exception types and aliases
  • ✅ Async tasks — go and await go for simple asynchronous execution
  • ✅ Async functions — async def, await, Task / Task<T>, and top-level await
  • ✅ C-style for loops — for (i = 0; i < 10; i++)
  • ✅ Python-style error messages — compile and runtime errors mapped to .spy lines
  • ✅ Clear import errors — missing files and circular imports are reported clearly
  • ✅ Properties — get/set accessors with modifiers
  • ✅ Object instantiation — no new keyword needed, even inside larger expressions
  • ✅ Package imports — index.spy as entry point for folders
  • ✅ Async tasks — go {...} and await go {...} with block support (sync + async)
  • ✅ CI/CD — GitHub Actions for build and test
  • ✅ Inheritance — class : parent syntax
  • ✅ Lists — array literal syntax [1, 2, 3]
  • ✅ Dictionaries — Python-style {"key": value} syntax
  • ✅ Error context display — shows the exact source line with each error
  • ✅ Full Generics — List<T>, Dictionary<K, V>, nested generics
  • ✅ Python-like C# API names — Console.write_line() automatically maps to Console.WriteLine()
  • ✅ Python string/list methods — .upper(), .strip(), .startswith(), .append(), .sort() and friends map to their C# equivalents
  • ✅ LINQ & Lambda Expressions — Where, Select, OrderBy, standalone lambdas
  • ✅ Interfaces — interface and : implementation
  • ✅ Class hoisting — classes are moved to the end of generated code (Python-like)
  • ✅ Multi-module imports — import os, sys, math
  • ✅ Relative imports — import "../utils/math" and import "./utils/math"
  • ✅ Import aliases — import "./utils/math" as math
  • ✅ Quoted/path imports — supports import "utils/math", import "utils/math.spy", and dotted relative paths such as import ..utils.math
  • ✅ from imports — supports from "utils/math.spy" import add, aliases, and the same path forms as import
  • ✅ Python-style indentation blocks — if/elif/else, while, for, def, class, try and friends work without braces (braces remain fully supported)
  • ✅ for item in collection — iterates lists, arrays, strings, dictionaries (keys), and range(...)
  • ✅ Python operators — and, or, not, in, not in, is None, is not None
  • ✅ Default parameter values — def greet(name: str = "world")
  • ✅ Class field initializers — name = "Ali" and age: int = 16 inside classes
  • ✅ Public-by-default class fields — match the Python mental model; use private/protected explicitly when needed
  • ✅ Attribute syntax — [Serializable], [Obsolete("...")], and other C# attributes
  • ✅ Python constructors — def __init__(self, ...) and def ClassName(...)
  • ✅ self / cls — accepted in methods inside both Python-style and brace-style classes
  • ✅ Parent constructor calls — Animal(name) becomes : base(name)
  • ✅ Multi-line calls and collections — split arguments, lists, and dictionaries over several lines
  • ✅ Inline collection literals — len({"a": 1}), zip([1, 2], [3, 4])
  • ✅ raise and pass — Python-style exception raising and placeholder statements
  • ✅ Multi-argument Write — Write("name:", name, "age:", age)

🎯 Vision

Future Goals

  • Full C# / .NET interoperability
  • Advanced C# type support
  • External .NET library support
  • Self-hosting compiler

SharpThon aims to become a lightweight .NET development language that can directly interoperate with the existing C# and .NET ecosystem.

SharpThon does not need to understand or implement frameworks such as ASP.NET Core or Entity Framework Core directly. Instead, it aims to generate C# that can consume any compatible .NET library through normal using directives, types, methods, generics, and APIs.

using SomeDotNetLibrary

class UserService {
    public def GetUser(id: int) {
        return UserRepository.Find(id)
    }
}

Class Hoisting

Classes can be defined anywhere in the file. SharpThon automatically moves all class declarations to the end of the generated C# code — just like Python.

// Class is defined first
class Dog:
    def speak() -> str:
        return "Woof"

// But used here, before the class in source
my_dog = Dog()
Write(my_dog.speak())

This transpiles to valid C# with classes at the bottom. No need to worry about class ordering.


🔮 Future Ideas

py2spy

A long-term goal of SharpThon is py2spy — a tool that converts a subset of Python code into SharpThon syntax, helping developers migrate Python projects to the .NET ecosystem while keeping a familiar syntax.

Python:

for i in range(5):
    print(i)

↓

SharpThon:

for i in range(5):
    Write(i)

📦 Installation

git clone https://github.com/OandONE/SharpThon.git
cd SharpThon/sharpton_cs
dotnet build

SharpThon targets .NET 8 and runs on platforms supported by .NET, including Windows, Linux, and macOS.

Install as a .NET tool

dotnet tool install --global SharpThon.Cli
sharpton hello.spy

The compiler is also available as the SharpThon.Core NuGet package for embedding the transpiler in other tools.

Build the packages locally with:

dotnet pack sharpton_cs/Sharpton.Core -c Release
dotnet pack sharpton_cs/Sharpton.Cli -c Release

🚀 Quick Start

1. Create a .spy file

// hello.spy
name = "World"
Write("Hello " + name + "!")

2. Run with SharpThon

dotnet run --project Sharpton.Cli -- hello.spy

3. Output

Hello World!

To generate and inspect the C# without building/running it:

dotnet run --project Sharpton.Cli -- hello.spy --transpile-only

This is useful for editor integrations, quick syntax checks, and debugging the transpiler itself.


📋 Syntax Reference

Variables

name = "Ali"                    // type inferred
age: int = 16                   // explicit type
pi = 3.14                       // double
distance: double = 12.5         // double
population: long = 8000000000   // long
is_dev = true                   // bool
text: str = "Hello"             // str → string in C#
data: Any = 42                  // Any → object in C#

Python-like C# API Names

SharpThon automatically converts snake_case method names to PascalCase when calling C# methods. This lets you use Python-style naming with .NET libraries.

Console.write_line("Hello from SharpThon!")
Console.write_line_with_color("Red")

Transpiles to:

Console.WriteLine("Hello from SharpThon!");
Console.WriteLineWithColor("Red");

Common Python string/list methods are also recognized:

name = "  Ali  "
Write(name.strip().upper())      // .Trim().ToUpper()

items = [3, 1, 2]
items.append(4)                  // .Add(4)
items.sort()                     // .Sort()
Python C#
upper() ToUpper()
lower() ToLower()
strip() Trim()
lstrip() TrimStart()
rstrip() TrimEnd()
startswith() StartsWith()
endswith() EndsWith()
find() IndexOf()
rfind() LastIndexOf()
index() IndexOf()
split() Split()
replace() Replace()
append() Add()
extend() AddRange()
insert() Insert()
remove() Remove()
sort() Sort()
reverse() Reverse()
clear() Clear()

If you define a method with the same name in your own class, SharpThon leaves the call unchanged.

Constants & Readonly

SharpThon supports C#-style const and readonly modifiers.

const MAX_RETRY = 3
const APP_NAME = "SharpThon"
const PI: double = 3.14159

class Config {
    readonly _host: str = "localhost"
    public readonly Port: int = 8080
    public const API_URL = "https://api.example.com"
}

Output C#:

const int MAX_RETRY = 3;
const string APP_NAME = "SharpThon";
const double PI = 3.14159;

class Config {
    readonly string _host = "localhost";
    public readonly int Port = 8080;
    public const string API_URL = "https://api.example.com";
}
  • const works for local variables and class fields. The type is inferred from the value if not explicitly written.
  • readonly is for class fields only (it cannot be used inside functions).
  • You can combine public, private, protected with const or readonly.

Conditions

if (age > 18) {
    Write("Adult")
}
elif (age == 16) {
    Write("Sweet sixteen!")
}
else {
    Write("Young")
}

Python-Style Blocks (Indentation)

Braces are optional. Any block can use Python-style indentation instead, and both styles can be mixed in the same project:

def classify(score: int) -> str:
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    else:
        return "C"

for i in range(3):
    Write(i)

while count < 3:
    Write(count)
    count += 1

Indentation is significant inside an indentation block (spaces or tabs are accepted). Blocks end when the indentation returns to the level of their header. A line that starts a block uses a trailing colon instead of { ... }.

The C-style syntax keeps working exactly as before:

if (score >= 90) {
    return "A"
}
else if (score >= 80) {
    return "B"
}

else if is accepted as an alias for elif.

Python-Style Classes

class Person:
    name: str
    age: int = 16

    def __init__(self, name: str):
        self.name = name

    def greet(self) -> str:
        return "Hi " + self.name

p = Person("Ali")
Write(p.greet())
  • def __init__(...) and def ClassName(...) both declare a constructor.
  • self and cls are optional; when present in a method signature they are removed and self.x / cls.x map to this.x. This works in both Python-style and brace-style classes.
  • Fields declared without an access modifier are public, matching Python. Add private, protected, or public explicitly to override this.
  • A parent constructor can be called as the first statement of a subclass constructor; it is emitted as a C# : base(...) initializer:
class Dog(Animal):
    def __init__(self, name: str):
        Animal(name)
        self.name = name

Interfaces can use the same indentation style. Method bodies are treated as declarations and ignored:

interface IAnimal:
    def speak(self) -> str:
        pass
    def move(distance: int) -> None:
        pass

class Cat(IAnimal):
    def speak(self) -> str:
        return "Meow"

    def move(distance: int) -> None:
        Write(distance)

Python-Style Loops

for item in [10, 20, 30]:
    Write(item)

for i in range(5):
    Write(i)

# Dictionaries iterate their keys, like Python.
for key in {"a": 1, "b": 2}:
    Write(key)

for (i in 5) keeps its original meaning (0 through 4). Use range(n) when the count is stored in a variable.

Python Operators

if score > 0 and score < 100:
    Write("valid")

if not finished:
    Write("pending")

if "name" in data:
    Write("key exists")

if item not in items:
    Write("missing")

if value is None:
    Write("empty")

and, or, not, in, not in, is None, and is not None are translated to their C# equivalents. Membership works for lists, arrays, strings, and dictionary keys.

Loops

for (i in 5) {
    Write("Count: " + i)
}

items = [10, 20, 30]
for (item in items) {
    Write(item)
}

for (i in range(3)) {
    Write(i)
}

counter = 0
while (counter < 3) {
    Write("While: " + counter)
    counter++
}

Functions

SharpThon supports return types in both declaration and postfix form. The postfix form is normalized before parsing, so these forms are all supported:

def add() -> str {
    return "text"
}

def add() {
    return "text"
}

def add() {
    return "text"
} -> str

The postfix form is useful when the return type is decided after the function body is written.

public def add(a: int, b: int) -> int {
    return a + b
}

Write("5 + 3 = " + add(5, 3))

static def greet(name: str) {
    Write("Hello " + name + "!")
}

greet("Developer")

public def Area(radius: double) -> double {
    return 3.14159 * radius * radius
}

Default parameter values are supported:

def greet(name: str = "world") -> str {
    return "Hello " + name
}

def add(a: int = 1, b: int = 2) -> int:
    return a + b

Write(greet())
Write(add(10))

Multi-line calls are supported too:

result = add(
    10,
    20
)

Modules

Import other .spy files to use their functions and classes. The transpiler automatically compiles the imported file and adds it to the project.

main.spy:

import math_utils

result = math_utils.add(10, 20)
Write(f"Result: {result}")

math_utils.spy:

def add(x: int, y: int) -> int {
    return x + y
}

Relative Imports

Relative imports resolve from the directory of the file containing the import. Use a quoted path beginning with ./ or ../. The .spy extension is optional.

Project structure:

project/
├── main.spy
├── utils/
│   └── math.spy
└── features/
    └── stats.spy

main.spy:

import "./utils/math"

result = math.add(10, 20)
Write(result)

From a nested module, parent directories work as expected:

// features/stats.spy
import "../utils/math"

result = math.add(2, 3)

A relative import can also target a package directory; SharpThon loads its index.spy entry point automatically.

Relative imports are resolved per source file, so nested imports do not accidentally resolve against the entry file's directory.

Import Aliases

Use as to choose the name used to reference an imported module. This works with regular, quoted, extension-based, and relative imports.

import "./utils/math" as math
import "utils/math.spy" as math2

result = math.add(10, 20)

Aliases are useful when multiple modules have the same basename or when you want a clearer module name.

Quoted and Dotted Import Paths

SharpThon accepts several equivalent path forms for module imports. The .spy extension is optional.

import "utils/math"
import "utils/math.spy"
import ..utils.math
import "..utils.math"

The same path forms are accepted by from imports and can be combined with aliases:

from "../utils/math.spy" import add
from ..utils.math import add as sum
from "utils/math" import add as plus

Multiple imports can also be mixed on one line:

import "./utils/math" as math, os as operating_system

From Imports

Import specific functions or classes from a module without using the module prefix.

from TestImportModule import add

result = add(10, 20)
Write(result)

Multiple members are supported:

from TestImportModule import add, multiply

Write(add(10, 20))
Write(multiply(5, 5))

Relative modules work as well:

from "../utils/math" import add

result = add(10, 20)

A selected member can also be renamed with an alias:

from "../utils/math" import add as sum

result = sum(10, 20)

Package Entry File (index.spy)

When importing a folder as a package, SharpThon automatically looks for an index.spy file inside that folder and runs it as the entry point.

Structure:

my_package/
├── index.spy       ← entry point
├── other_file.spy
└── ...

Usage:

import my_package

SharpThon will automatically load my_package/index.spy.

If index.spy does not exist, an error is shown:

=== SharpThon Import Error ===

Package 'my_package' does not contain an index.spy file.

This is similar to index.js in Node.js or __init__.py in Python, but simpler and more explicit.

External Libraries (require)

SharpThon reserves import and from for .spy modules. Use require for built-in/external library compatibility layers.

require os
require json
require re
require sys
require random
require math
require time

Write(os.getcwd())
Write(math.sqrt(25))
Write(time.time())

The first built-in compatibility libraries are:

  • os — filesystem, environment, process, and os.path helpers
  • json — loads(), load(), dumps(), and dump()
  • re — matching, searching, compiled patterns, iteration, substitution, splitting, and escaping
  • sys — command-line arguments, runtime information, environment access, and process helpers
  • random — seeding, random values, integer ranges, sequence selection, shuffling, sampling, and common distributions
  • math — constants and common numeric, trigonometric, logarithmic, rounding, combinatoric, and comparison functions
  • time — wall-clock time, nanosecond time, monotonic/performance clocks, ctime(), localtime(), gmtime(), strftime(), and sleep()

The compatibility layer is implemented in SharpThonLibraries.cs, keeping library code separate from the main transpiler. The API surface is intentionally Python-shaped while using .NET 8 underneath; it is not a byte-for-byte implementation of the entire CPython standard library.

Aliases are also accepted:

require math as m
Write(m.sqrt(16))

using remains reserved for .NET namespaces, while import / from remain the SharpThon module system.

Using .NET Namespaces

Use using for standard .NET libraries, just like in C#.

using System
using System.Linq

↓

using System;
using System.Linq;

Classes

class User {
    public name: str
    private age: int

    def User(name: str, age: int) {
        this.name = name
        this.age = age
    }

    public def Greet() {
        Write(f"Hello {name}")
    }

    public def IsAdult() -> bool {
        return age >= 18
    }
}

Fields can be initialized directly, and the type is inferred when omitted:

class Config {
    host = "localhost"
    port: int = 8080
    tags = ["dev", "local"]

    public const VERSION = "1.0"
}

Fields declared without an access modifier are public, so config.host is accessible outside the class. Use private or protected when you want C#-style encapsulation.

C# attributes are passed through:

[Serializable]
class User {
    [Obsolete("Use NewName instead")]
    public def OldName() {
        return "legacy"
    }
}

Python-style classes are also supported; see Python-Style Classes.

Properties

SharpThon supports properties with C#-style accessors. Use get and set blocks to control access to private fields.

class UserSettings {
    private name: str = "Ali"
    private age: int = 0
    private _password: str = ""

    // Read-only property
    Name -> str {
        return name
    }

    // Public property with getter and setter
    public Age -> int {
        get {
            return age
        }
        set (value) {
            age = value
        }
    }

    // Write-only property
    protected Password -> str {
        set (value) {
            _password = value
        }
    }

    // Static read-only property
    static Config -> str {
        return "default"
    }
}

Usage:

settings = UserSettings()
settings.Age = 42
Write(settings.Name)
Write(UserSettings.Config)

Properties support:

  • ✅ get / set accessors
  • ✅ public, private, protected modifiers
  • ✅ static properties
  • ✅ Read-only (get only) and write-only (set only) properties

Inheritance

SharpThon supports class inheritance. Use : to inherit from a parent class.

class Animal {
    public name: str

    def Animal(name: str) {
        this.name = name
    }

    public def Speak() {
        Write("...")
    }
}

class Dog : Animal {
    def Dog(name: str) {
        // Call parent constructor
        Animal(name)
    }

    public def Speak() {
        Write(name + " says woof!")
    }
}

dog = Dog("Rex")
dog.Speak()

The transpiler converts this to C# class inheritance using : syntax. A parent constructor call in the first line of a subclass constructor becomes a C# base initializer:

public Dog(string name) : base(name) {
    ...
}

Object Instantiation

Objects are created without the new keyword. This keeps the syntax closer to Python.

user = User("Ali", 16)
settings = UserSettings()
Write(User("Reza", 17).Greet())

↓

var user = new User("Ali", 16);
var settings = new UserSettings();
Console.WriteLine(new User("Reza", 17).Greet());

The new keyword is added automatically by the transpiler, including when a class is constructed inside a larger expression.

String Interpolation

Use Python-style f-strings for string interpolation.

name = "Ali"
message = f"Hello {name}"

Write(message)

↓

var name = "Ali";
var message = $"Hello {name}";

Console.WriteLine(message);

Exception Handling

try {
    x = 0
    y = 1 / x
}
catch (Exception as ex) {
    Write(ex.Message)
}
finally {
    Write("Done")
}

Async Functions

SharpThon supports real Task-based async functions:

async def compute(value: int) -> int:
    await Task.Delay(10)
    return value * 2

class Worker:
    async def compute(self, value: int) -> int:
        await Task.Delay(1)
        return value + 1

async def run():
    result = await compute(21)
    Write(result)

    worker = Worker()
    Write(await worker.compute(41))

await run()
  • async def becomes an async Task / async Task<T> method.
  • await works as a statement, in assignments, conditions, and call arguments.
  • Top-level await is supported; when imports are present, the generated main() becomes async automatically.
  • Async class methods work with self/cls.
  • go { ... } blocks use async lambdas, so await inside them is valid.
  • await go remains a blocking helper for synchronous callers. Inside async def, prefer await async_function().

Async generators, async lambdas, async for, and async with are not implemented yet.

Async Tasks

Use go to run an operation in the background without waiting for it to complete.

go do_something()

This transpiles to:

Task.Run(() => do_something());

Use await go when the task should be completed before continuing:

await go do_something()

This transpiles to:

Task.Run(() => do_something()).GetAwaiter().GetResult();

SharpThon functions are synchronous, so await go blocks the current function. It works both at the top level and inside functions. Full async/await functions are still on the roadmap.

Block support:

go {
    Write("Hello")
    Write("World")
}

await go {
    data = fetch_data()
    process(data)
}

Error Handling (Python-style Traceback)

SharpThon provides clean, readable error messages similar to Python tracebacks. Both compile-time and runtime errors are mapped back to the original .spy file.

When an error occurs, SharpThon displays:

  • 📁 Your .spy source file (not the generated .cs file)
  • 📍 Line number where the error happened
  • 💬 A clear error description
  • 🏷️ The C# error type (for advanced users)
  • 📝 The actual source code line where the error occurred

Compile-time error example:

=== SharpThon Error ===

File: ../test_error.spy
Line: 6

The name 'unknownVariable' does not exist in the current context
C# Error: CS0103

=======================

Runtime error example (division by zero):

// divide.spy
def main() {
    x = 10
    y = 0
    z = x / y   // division by zero
    Write(z)
}
main()

Output:

=== SharpThon Runtime Error ===

File: ../divide.spy
Line: 4

System.DivideByZeroException: Attempted to divide by zero.

===============================

This makes debugging much easier, especially for developers coming from Python who are used to simple, direct error messages.

Error Context Display

SharpThon now shows the actual source code line along with the error, not just the line number.

Example:

File: ../_test_error.spy
Line: 8

  8 |         "name": "Ali"

} expected
C# Error: CS1513

This makes debugging much easier — you can see exactly which line caused the error without opening the file.

C-style For Loops

for (i = 0; i < 5; i++) {
    Write(i)
}

↓

for (int i = 0; i < 5; i++) {
    Console.WriteLine(i);
}

Lists

numbers = [1, 2, 3]
names = ["Ali", "Reza"]
mixed = [1, "two", true]

Dictionaries

scores = {"Ali": 90, "Reza": 85}
config = {"host": "localhost", "port": 8080}

Access values:

Write(scores["Ali"])
config["port"] = 9090

Generics

SharpThon supports full generics with C#-style type parameters:

// Lists
numbers: List<int> = [1, 2, 3]
names: List<string> = ["Ali", "Mamad"]

// Dictionaries
ages: Dictionary<string, int> = {
    "ali": 16,
    "mamad": 20
}

// Nested generics
matrix: List<List<int>> = [
    [1, 2],
    [3, 4]
]

// Complex types
nested: Dictionary<string, List<int>> = {
    "numbers": [10, 20, 30]
}

Generic types map directly to C#:

  • List<T> → List<T>
  • Dictionary<K, V> → Dictionary<K, V>
  • Nested generics work as expected

LINQ & Lambda Expressions

SharpThon supports LINQ and lambda expressions with C#-style syntax.

using System.Linq

numbers = [5, 12, 8, 3, 9, 15, 2, 7]

// Filter with lambda
even_numbers = numbers.Where(x => x % 2 == 0)

// Sort with lambda
sorted = numbers.OrderByDescending(x => x)

// Map with lambda
squares = numbers.Select(x => x * x)

// Standalone lambda with explicit type
add: Func<int, int, int> = (a, b) => a + b

// Standalone lambda with dynamic
mul = (x, y) => x * y

This provides full functional programming support with LINQ.

Interfaces

SharpThon supports interfaces. Define a contract that classes must implement using interface and :.

interface IAnimal {
    def speak() -> str
    def move(distance: int) -> None
}

class Dog : IAnimal {
    def speak() -> str {
        return "Woof"
    }

    def move(distance: int) -> None {
        Write(distance)
    }
}

my_var = Dog()
my_var.speak()
my_var.move(1)

The transpiler converts this to C# interface and class : interface syntax.

CI/CD

Every push to GitHub automatically runs build and tests via GitHub Actions.

The workflow file is located at .github/workflows/dotnet.yml.

🔄 How It Works

SharpThon (.spy)
       ↓
 Sprache Parser
       ↓
 C# (.cs)
       ↓
 .NET Build
       ↓
 Run

The transpiler is written in C# using Sprache — a clean parser combinator library.

Minimal Regex, no external tools, no Java — just pure C# and .NET.

A Python prototype is also available in python_transpiler/.


📁 Project Structure

SharpThon/
├── .github/workflows
│   └── dotnet.yaml         # CD/DI
├── python_transpiler/      # Python prototype (MVP)
│   ├── transpiler.py
│   ├── indent_converter.py
│   └── runner.py
├── sharpton_cs/            # C# transpiler (current)
│   ├── Sharpton.Core/      # Core library
│   │   ├── Transpiler.cs
│   │   ├── Parser.cs       # Sprache parser
│   │   ├── SharpThonBuiltins.cs
│   │   ├── SharpThonLibraries.cs # Require Liberaries
│   │   ├── TranspileResult.cs
│   │   └── Sharpton.Core.csproj
│   ├── Sharpton.Cli/       # CLI tool
│   │   ├── Program.cs
│   │   └── Sharpton.Cli.csproj
│   ├── SharpThon.LSP/       # LSP
│   │   ├── Program.cs
│   │   ├── SharpThonLanguageServer.cs
│   │   └── SharpThon.LSP.csproj
│   ├── SharpThon.Tests/       # Unit Tests
│   │   ├── CircularImportTests.cs
│   │   ├── ImportErrorTests.cs
│   │   ├── PackageImportsTests.cs
│   │   ├── VariablesTests.cs
│   │   ├── CliTestSupport.cs
│   │   ├── ImportsTests.cs
│   │   ├── FeatureTests.cs
│   │   └── SharpThon.Tests.csproj
│   └── Sharpton.sln
├── tests/      # All Tests
│   ├── main.spy
│   └── ...
├── test.spy                # Demo file
└── README.md

🗺️ Roadmap

Feature Status
Python MVP ✅ Complete
C# Transpiler (Regex) ✅ Complete
Sprache Parser ✅ Complete
Functions with modifiers ✅ Complete
str → string, Any type ✅ Complete
long and double types ✅ Complete
Imports (import x.y) ✅ Complete
Classes (fields, constructors, methods, this) ✅ Complete
String interpolation (f-strings) ✅ Complete
try/catch/finally ✅ Complete
Async tasks (go / await go) ✅ Complete
C-style for loops ✅ Complete
Unit tests ✅ Complete
Clear import errors (missing/circular) ✅ Complete
Properties ✅ Complete
Async tasks (go {...} / await go {...}) ✅ Complete
CI/CD ✅ Complete
Inheritance ✅ Complete
Dictionaries & List Support ✅ Complete
Generics ✅ Complete
Constants & Readonly ✅ Complete
Python-like names for C# APIs ✅ Complete
Python string/list method aliases ✅ Complete
LINQ / Lambda expressions ✅ Complete
Interfaces ✅ Complete
Multi-module import (import a, b, c) ✅ Complete
External libraries (require) ✅ Complete
Built-in Types (None, str, list, dict, tuple, enumerate, ...) ✅ Complete
VS Code Extension (LSP) 🚧 In Progress
Relative imports ("../utils/math") ✅ Complete
Import aliases (import x as y) ✅ Complete
from imports (from x import y) ✅ Complete
Python-style indentation blocks ✅ Complete
for over collections / range(...) ✅ Complete
Python operators (and, or, not, in) ✅ Complete
Default parameter values ✅ Complete
__init__ / self / cls ✅ Complete
Parent constructor calls (: base(...)) ✅ Complete
raise / pass ✅ Complete
Multi-argument Write ✅ Complete
Inline collection literals ✅ Complete
Attribute syntax ✅ Complete
Class field initializer ✅ Complete
General member access ✅ Complete
Multi-line expressions/calls ✅ Complete
C# interop syntax coverage 🚧 Partial
Nullability / null handling 🚧 Partial
Better compiler error recovery ❌
Semantic analyzer / symbol table ❌
Class/member-aware parsing ❌
Attribute/member metadata preservation ✅ Complete
Conditional imports ❌
Lazy imports (inside functions) ❌
Quoted imports with extension ✅ Complete
Module caching ✅ Complete
Better circular import reporting ✅ Complete
Official documentation (website, PDF) ❌
Python UX libraries via require (os, json, re, sys, random, math, time) ✅ Complete
Full async / await support ✅ Complete
Async generators / async for / async with ❌
Self-hosting ❌
NuGet package ✅ Complete

📄 License

MIT © OandONE


🙏 Acknowledgments

Inspired by Python (simplicity) and C# (power).

Built by a developer who wanted Python's readability with C#'s performance.

About

SharpThon (.spy) - A Python-like language with C# syntax that transpiles to C#. Write Python with braces, semicolons, and strong typing.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages