Complete guide to the hybrid programming language
npm install -g cscript-language
# Via VS Code Command Palette
ext install VIBECO.cscript-language-support
# Or download VSIX
code --install-extension cscript-language-support-1.0.0.vsix
Create a file called hello.csc:
// Hello World in CScript
const message = "Hello, CScript!";
console.log(message);
// Use pipeline operators for clean data flow
const numbers = [1, 2, 3, 4, 5];
const result = numbers
|> filter(x => x % 2 === 0)
|> map(x => x * 2)
|> reduce((a, b) => a + b);
console.log(`Sum of doubled even numbers: ${result}`);
Transpile and run:
cscript hello.csc
Transform data with readable left-to-right flow:
// Instead of nested function calls
const result = reduce(map(filter(data, predicate), transform), accumulator);
// Use clean pipeline flow
const result = data
|> filter(predicate)
|> map(transform)
|> reduce(accumulator);
// Real-world example
const processedUsers = users
|> filter(user => user.isActive)
|> map(user => ({
...user,
fullName: `${user.firstName} ${user.lastName}`
}))
|> sortBy(user => user.createdAt)
|> take(10);
Powerful pattern matching that replaces verbose switch statements:
// Basic matching
const statusMessage = response.status match {
200 => "Success",
404 => "Not Found",
500 => "Server Error",
_ => "Unknown Status"
};
// Guard patterns with conditions
const category = value match {
x when x < 0 => "Negative",
x when x === 0 => "Zero",
x when x > 100 => "Large",
_ => "Normal"
};
// Tuple matching
const access = (user.role, user.isActive) match {
("admin", true) => "Full Access",
("user", true) => "Limited Access",
("guest", _) => "Read Only",
_ => "No Access"
};
SQL-like syntax for data manipulation:
// Basic queries
const activeUsers = from user in users
where user.isActive && user.age >= 18
select {
id: user.id,
name: user.name,
email: user.email
};
// Complex queries with joins
const userProjects = from user in users
join project in projects on user.id equals project.userId
where project.status === 'active'
select {
userName: user.name,
projectTitle: project.title,
deadline: project.deadline
}
orderby deadline ascending;
Custom operators and operator overloading:
// Operator overloading for classes
class Vector {
constructor(public x: number, public y: number) {}
operator +(other: Vector): Vector {
return new Vector(this.x + other.x, this.y + other.y);
}
operator *(scalar: number): Vector {
return new Vector(this.x * scalar, this.y * scalar);
}
}
const v1 = new Vector(1, 2);
const v2 = new Vector(3, 4);
const v3 = v1 + v2; // Vector addition
const v4 = v1 * 2; // Scalar multiplication
Function overloading and enhanced capabilities:
// Function overloading by parameter types
function process(value: string): string {
return value.toLowerCase().trim();
}
function process(value: number): number {
return Math.round(value * 100) / 100;
}
function process(value: Array): Array {
return value.filter(item => item != null);
}
// Usage automatically selects correct overload
const str = process(" HELLO WORLD "); // string version
const num = process(3.14159); // number version
const arr = process([1, null, 2, null]); // array version
Choose your preferred syntax style:
// C-style syntax with braces
function processOrders(orders) {
for (let order of orders) {
if (order.status === 'pending') {
order.status = 'processing';
sendNotification(order.customer);
}
}
return orders;
}
// Python-style syntax with indentation
function processOrders(orders):
for order in orders:
if order.status === 'pending':
order.status = 'processing'
sendNotification(order.customer)
return orders
import { transpile, TranspileOptions } from 'cscript-language';
interface TranspileOptions {
target?: 'es5' | 'es2015' | 'es2018' | 'es2020' | 'esnext';
module?: 'commonjs' | 'amd' | 'umd' | 'es6' | 'es2015' | 'esnext';
sourceMap?: boolean;
strict?: boolean;
declaration?: boolean;
outDir?: string;
features?: {
pipelineOperators?: boolean;
matchExpressions?: boolean;
linqQueries?: boolean;
operatorOverloading?: boolean;
smartFunctions?: boolean;
hybridSyntax?: boolean;
enhancedControlFlow?: boolean;
};
}
// Transpile CScript code to JavaScript
function transpile(source: string, options?: TranspileOptions): string;
// Transpile file
function transpileFile(inputPath: string, outputPath?: string, options?: TranspileOptions): void;
// Watch mode
function watch(inputPath: string, options?: TranspileOptions): void;
# Basic transpilation
cscript input.csc # Outputs input.js
cscript input.csc -o output.js # Custom output file
cscript src/ -o dist/ # Directory transpilation
# Options
cscript input.csc --target es2020 # Target ES version
cscript input.csc --module commonjs # Module format
cscript input.csc --source-map # Generate source maps
cscript input.csc --watch # Watch mode
# Configuration file
cscript --config csconfig.json # Use config file
cscript --init # Create default config
# Help and version
cscript --help # Show help
cscript --version # Show version
{
"compilerOptions": {
"target": "es2020",
"module": "es6",
"outDir": "./dist",
"sourceMap": true,
"strict": true,
"declaration": true,
"declarationDir": "./types"
},
"features": {
"pipelineOperators": true,
"matchExpressions": true,
"linqQueries": true,
"operatorOverloading": true,
"smartFunctions": true,
"hybridSyntax": true,
"enhancedControlFlow": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules/**/*",
"dist/**/*",
"**/*.test.csc"
],
"watchOptions": {
"watchFile": "useFsEvents",
"watchDirectory": "useFsEvents",
"followSymlinks": true,
"synchronousWatchDirectory": true
}
}
| Feature | Description | Default |
|---|---|---|
pipelineOperators |
Enable |> pipeline syntax |
true |
matchExpressions |
Enable pattern matching with match |
true |
linqQueries |
Enable SQL-like from/where/select |
true |
operatorOverloading |
Enable custom operator definitions | true |
smartFunctions |
Enable function overloading | true |
hybridSyntax |
Enable Python-style indentation | true |
enhancedControlFlow |
Enable advanced loop constructs | true |
Most JavaScript code works as-is in CScript:
// JavaScript - works in CScript
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
Gradually add types for better tooling:
// Add types for better IntelliSense
interface Item {
price: number;
quantity: number;
name: string;
}
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
Replace verbose patterns with CScript features:
// Before (JavaScript)
const processedData = data
.filter(item => item.active)
.map(item => transform(item))
.reduce((acc, item) => acc + item.value, 0);
// After (CScript)
const processedData = data
|> filter(item => item.active)
|> map(transform)
|> reduce((acc, item) => acc + item.value, 0);
csconfig.json configuration file.js files to .csc (optional, gradual migration)// Process sales data with pipeline operators
const salesReport = salesData
|> filter(sale => sale.date >= startDate && sale.date <= endDate)
|> map(sale => ({
...sale,
profit: sale.revenue - sale.cost,
margin: (sale.revenue - sale.cost) / sale.revenue
}))
|> groupBy(sale => sale.category)
|> mapValues(categoryData => ({
totalRevenue: categoryData.sum(s => s.revenue),
totalProfit: categoryData.sum(s => s.profit),
averageMargin: categoryData.average(s => s.margin),
salesCount: categoryData.length
}))
|> Object.entries
|> map(([category, stats]) => ({ category, ...stats }))
|> sortBy(item => item.totalRevenue, 'desc');
console.log('Sales Report:', salesReport);
class ApiClient {
constructor(private baseUrl: string, private apiKey: string) {}
async request(endpoint: string, options: RequestOptions = {}): Promise {
const url = `${this.baseUrl}${endpoint}`;
const config = {
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers
},
...options
};
try {
const response = await fetch(url, config);
return response.status match {
200 => await response.json(),
404 => throw new NotFoundError('Resource not found'),
401 => throw new AuthError('Unauthorized'),
500 => throw new ServerError('Internal server error'),
_ => throw new Error(`HTTP ${response.status}: ${response.statusText}`)
};
} catch (error) {
const handled = error match {
NetworkError => 'Network connection failed',
TimeoutError => 'Request timed out',
_ => error.message
};
throw new Error(`API request failed: ${handled}`);
}
}
}
For more information, visit the CScript GitHub repository or NPM package.