Commit 4115df74 authored by Roman Alifanov's avatar Roman Alifanov

Initial commit

parents
# ContenT Language Specification
## Overview
ContenT (.ct) - DSL язык, компилируемый в оптимизированный Bash.
Гибрид Python + Go + Vala синтаксиса.
---
## Синтаксис
### Комментарии
```
# однострочный комментарий
```
### Переменные
```
name = "Alice"
count = 42
active = true
data = nil
```
Экранирование фигурных скобок в строках: `"\{"`
### Строковая интерполяция
```
msg = "Hello, {name}!"
```
### Структуры данных
```
# Массив
items = ["a", "b", "c"]
# Ассоциативный массив (dict/map)
config = {"host": "localhost", "port": 8080}
```
### Функции
```
func greet (name) {
print ("Hello, {name}!")
}
func greet (name, greeting = "Hello") {
print ("{greeting}, {name}!")
}
# Variadic
func sum (numbers...) {
total = 0
foreach n in numbers {
total += n
}
return total
}
```
Перегрузка функций эмулируется через проверку количества аргументов.
### Классы
```
class Logger {
level = "INFO"
prefix = ""
construct (level = "INFO") {
this.level = level
}
func log (msg) {
print ("[{this.level}] {this.prefix}{msg}")
}
}
```
### Наследование
```
class FileLogger : Logger {
path = "/var/log/app.log"
construct (path, level = "INFO") {
base (level)
this.path = path
}
func log (msg) {
fs.append (this.path, "[{this.level}] {msg}\n")
}
}
```
### Создание объектов
```
logger = Logger ("DEBUG")
logger.log ("Starting app")
```
### Операции с полями объектов
Поля объектов поддерживают составные операторы присваивания:
```
class Counter {
value = 0
name = ""
func increment (n = 1) {
this.value += n # арифметика
}
func decrement (n = 1) {
this.value -= n
}
func appendName (suffix) {
this.name ..= suffix # конкатенация строк
}
}
```
Поддерживаемые операторы: `=`, `+=`, `-=`, `*=`, `/=`, `..=`
### Pipe-оператор
```
# Shell-like — соединение команд
result = shell.exec ("cmd1") | shell.exec ("cmd2")
# Функциональный — цепочка функций
result = value | func1 | func2
```
См. полное описание в разделе stdlib → Pipe-оператор.
### Декораторы
Декораторы работают как на функциях, так и на методах классов.
**Доступные декораторы:**
- `@retry(attempts, delay)` — повторные попытки при ошибке
- `@log` — логирование вызовов (выводит в stderr)
- `@cache(ttl)` — кеширование результатов на ttl секунд
- `@awk` — компиляция в AWK (см. ниже)
```
# На функциях
@retry (attempts = 3, delay = 1)
func fetchData (url) {
return http.get (url)
}
@log
func processUser (data) {
# ...
}
@cache (ttl = 60)
func getConfig () {
return fs.read ("/etc/app.conf")
}
```
```
# На методах классов
class ApiClient {
baseUrl = ""
construct (url) {
this.baseUrl = url
}
@retry (attempts = 3, delay = 2)
func fetch (endpoint) {
return http.get (this.baseUrl .. endpoint)
}
@cache (ttl = 300)
func getStatus () {
return http.get (this.baseUrl .. "/status")
}
@log
func post (endpoint, data) {
return http.post (this.baseUrl .. endpoint, data)
}
}
```
### @awk — высокопроизводительные функции
Декоратор `@awk` компилирует функцию в AWK вместо Bash. Даёт ускорение **до 2000x** на строковых и числовых операциях.
```
@awk
func countWords (text) {
count = 0
n = text.split (" ")
for i in range (1, n + 1) {
count += 1
}
return count
}
@awk
func sumNumbers (text) {
total = 0
n = text.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
```
**Поддерживаемый синтаксис в @awk:**
- Переменные, присваивания (`=`, `+=`, `-=`, `*=`, `/=`, `%=`)
- Циклы: `for i in range()`, `foreach`, `while`
- Условия: `if/else if/else`
- Операторы: `+`, `-`, `*`, `/`, `%`, `^`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `&&`, `||`
- Конкатенация строк: `..`
- Вложенные функции (AWK helper functions)
- `break`, `continue`, `return`
**Доступные методы в @awk:**
- Строки: `text.len ()`, `text.upper ()`, `text.lower ()`, `text.trim ()`, `text.substr ()`, `text.index ()`, `text.contains ()`, `text.split ()`, `text.replace ()`, `text.starts ()`, `text.ends ()`, `text.charAt ()`
- Массивы: `arr.len ()`, `arr.get ()`, `arr.set ()`, `arr.push ()`, `arr.pop ()`, `arr.shift ()`, `arr.has ()`, `arr.del ()`
- Словари: `dict.get ()`, `dict.set ()`, `dict.has ()`, `dict.del ()`, `dict.keys ()`
- Математика: `math.sin ()`, `math.cos ()`, `math.sqrt ()`, `math.log ()`, `math.exp ()`, `math.int ()`, `math.rand ()`, `math.atan2 ()`
- Вывод: `print ()`, `printf ()`, `sprintf ()`
**Ограничения AWK:**
- Массивы в AWK ассоциативные — `pop ()`, `shift ()`, `join ()`, `slice ()` имеют ограниченную поддержку
- `ord ()` / `chr ()` недоступны (только в gawk)
- Нет доступа к `this` в методах классов
**Обработка файлов с __input__:**
```
@awk
func processFile (filename) {
total = 0
foreach line in __input__ {
total += line.len ()
}
return total
}
```
Использует mawk (предпочтительно) или gawk для максимальной скорости.
**@awk на методах классов:**
`@awk` методы не имеют доступа к `this` — передавайте данные через параметры.
```
class Calculator {
@awk
func fastSum (numbers) {
total = 0
n = numbers.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
}
calc = Calculator ()
result = calc.fastSum ("1 2 3 4 5") # 15
```
### Лямбды
```
# Один аргумент
filterFn = x => x > 10
# Несколько аргументов
addFn = (a, b) => a + b
# Многострочная
processFn = item => {
print (item)
return item
}
# Вызов
result = filterFn (15) # true
sum = addFn (3, 4) # 7
```
### Циклы
```
# foreach - итерация по коллекции
foreach item in items {
process (item)
}
foreach i, item in items {
print ("{i}: {item}")
}
# Для dict - key, value
foreach key, value in config {
print ("{key} = {value}")
}
# for - итерация по range
for i in range (10) {
print (i)
}
for i in range (0, 100, 5) {
print (i)
}
# while
while running {
tick ()
}
```
### Условия
```
if count > 10 {
print ("Many")
} else if count > 0 {
print ("Some")
} else {
print ("None")
}
```
### When (Pattern Matching)
```
when value {
1 {
print ("one")
}
2, 3 {
print ("two or three")
}
4..10 {
print ("four to ten")
}
else {
print ("other")
}
}
```
Поддерживается:
- Одиночные значения: `1`, `"hello"`
- Множественные значения: `2, 3, 4`
- Диапазоны: `4..10` (от 4 до 10 включительно)
- `else` — ветка по умолчанию
Работает в обычных функциях и в `@awk` функциях.
### Try / Except / Finally / Throw
```
func parseConfig (path) {
try {
data = fs.read (path)
return json.parse (data)
} except FileNotFound e {
print ("Not found: {e}")
return {}
} except ParseError e {
throw Error ("Invalid config: {e}")
} finally {
print ("Done")
}
}
```
### Defer
```
func processData () {
resource = acquireResource ()
defer releaseResource (resource)
# работа с ресурсом...
# releaseResource вызовется автоматически при выходе
}
```
### Import
```
import "std/http"
import "std/json"
import "Logger"
import "MyLib.sh"
```
---
## Стандартная библиотека (stdlib)
Встроена автоматически.
### print ()
```
print ("Hello, {name}!")
print (data)
```
### http
```
response = http.get ("https://api.example.com/data")
response = http.post (url, {"key": "value"})
response = http.put (url, data)
response = http.delete (url)
```
Использует `curl -sS --fail --show-error`.
### fs
```
data = fs.read (path)
fs.write (path, content)
fs.append (path, content)
exists = fs.exists (path)
fs.remove (path)
fs.mkdir (path)
files = fs.list (path)
```
### json
```
obj = json.parse (string)
string = json.stringify (obj)
```
### logger
```
logger.info ("message")
logger.warn ("message")
logger.error ("message")
logger.debug ("message")
```
### str (строковые методы)
Методы вызываются непосредственно на строковых переменных:
```
text = "Hello, World!"
# Базовые
len = text.len () # длина строки
upper = text.upper () # HELLO, WORLD!
lower = text.lower () # hello, world!
trimmed = text.trim () # убрать пробелы по краям
# Поиск и проверка
has = text.contains ("World") # true
starts = text.starts ("Hello") # true
ends = text.ends ("!") # true
idx = text.index ("World") # 7
# Работа с подстроками
sub = text.substr (0, 5) # Hello
char = text.charAt (0) # H
# Преобразование
replaced = text.replace ("World", "ContenT")
parts = text.split (", ") # массив ["Hello", "World!"]
# Символы (глобальные функции)
code = ord ("A") # 65
char = chr (65) # "A"
```
### arr (методы массивов)
Методы вызываются непосредственно на массивах:
```
items = ["a", "b", "c"]
# Размер
len = items.len () # 3
# Добавление/удаление
items.push ("d") # ["a", "b", "c", "d"]
items.pop () # удалить последний
first = items.shift () # удалить и вернуть первый
# Доступ
item = items.get (0) # "a"
items.set (1, "x") # items[1] = "x"
# Преобразование
joined = items.join (", ") # "a, b, c"
slice = items.slice (0, 2) # ["a", "b"]
```
### regex
```
matched = regex.match (text, pattern)
extracted = regex.extract (text, pattern)
```
### args (аргументы командной строки)
```
count = args.count ()
arg = args.get (0)
```
### shell (выполнение команд)
```
shell.exec ("ls -la")
output = shell.capture ("whoami")
shell.source ("config.sh")
```
### Pipe-оператор (`|`)
Оператор `|` поддерживает два режима работы:
**Shell-like pipe** — соединение shell-команд через stdout:
```
# Нативный bash pipe - без subshell overhead
files = shell.exec ("ls -la") | shell.exec ("grep txt")
# Генерирует: files=$(ls -la | grep txt)
# Цепочки из 3+ команд
count = shell.exec ("cat file.txt") | shell.exec ("grep error") | shell.exec ("wc -l")
# Генерирует: count=$(cat file.txt | grep error | wc -l)
```
**Функциональный pipe** — передача результата как первого аргумента:
```
func double (x) {
return x * 2
}
func add_ten (x) {
return x + 10
}
# 5 | double | add_ten эквивалентно add_ten(double(5))
result = 5 | double | add_ten # 20
# С дополнительными аргументами
func multiply (x, factor) {
return x * factor
}
result = 10 | multiply (3) # multiply(10, 3) = 30
```
**Приоритет:** Pipe имеет самый низкий приоритет среди бинарных операторов (ниже `||`).
```
# a || b | c парсится как (a || b) | c
```
### time
```
now = time.now () # Unix timestamp (секунды)
ms = time.ms () # Миллисекунды
```
### random
```
n = random () # 0-32767
n = random_range (1, 100) # 1-100
```
### math
```
sum = math.add (a, b)
diff = math.sub (a, b)
prod = math.mul (a, b)
quot = math.div (a, b)
rem = math.mod (a, b)
minimum = math.min (a, b)
maximum = math.max (a, b)
absolute = math.abs (n)
```
### dict (методы словарей)
Методы вызываются непосредственно на словарях:
```
config = {"host": "localhost", "port": 8080}
# Доступ
host = config.get ("host") # "localhost"
config.set ("debug", true) # добавить ключ
# Проверка
exists = config.has ("host") # true
# Удаление
config.del ("debug") # удалить ключ
# Получить все ключи
keys = config.keys () # ["host", "port"]
```
### Утилиты
```
exit (code)
is_number (value)
is_empty (value)
ngrep (pattern, text) # grep с номерами строк
```
---
## CLI
### build
```bash
content build main.ct # -> main.sh
content build main.ct -o app.sh # -> app.sh
content build utils.ct main.ct -o app.sh # Multi-file (Vala-style)
```
### Многофайловая компиляция
Как в Vala — передайте несколько .ct файлов компилятору:
```bash
content build lib.ct utils.ct main.ct -o app.sh
content run lib.ct main.ct
content run lib.ct main.ct -- arg1 arg2 # с аргументами
```
**Авто-поиск файлов:**
```bash
content build . -o app.sh # Все .ct в текущей директории
content run . # Скомпилировать и запустить все .ct
```
`main.ct` автоматически ставится последним (точка входа).
Все файлы компилируются вместе. Функции и классы из одного файла доступны в других без явного импорта.
### run
```bash
content run main.ct
content run lib.ct main.ct
content run lib.ct main.ct -- arg1 arg2
```
Компилирует во временный файл, запускает, удаляет (даже при ошибке).
### build-lib
```bash
content --build-lib MyLib.ct # -> MyLib.sh
```
### lint
```bash
content build main.ct --lint # запускает ShellCheck
```
---
## Пользовательские библиотеки
### Сборка
```bash
content --build-lib MyLib.ct
```
Генерирует `MyLib.sh` с bash кодом и метаданными.
### Импорт
```
import "MyLib.sh"
import "Logger" # ищет в глобальных путях
```
### Глобальные пути
```
/usr/lib/content/
~/.content/libs/
```
---
## Оптимизации Bash
Компилятор автоматически:
- Минимизирует fork
- Избегает subshell где возможно
- Использует bash builtins
- Использует [[ ]] вместо [ ]
- Использует массивы
- Кеширует вычисления
- Инлайнит простые методы
---
## Ошибки компиляции
```
Error: Unknown variable 'user'
--> main.ct:2:10
Error: Missing closing brace
--> main.ct:15:1
```
Показывает все ошибки сразу.
---
## Архитектура компилятора
```
┌─────────────────┐
│ Source .ct │
└────────┬────────┘
┌────────▼────────┐
│ Lexer │
│ (Tokenizer) │
└────────┬────────┘
┌────────▼────────┐
│ Parser │
│ (AST Gen) │
└────────┬────────┘
┌────────▼────────┐
│ Code Gen │
│ (Bash / AWK) │
└────────┬────────┘
┌────────▼────────┐
│ Output .sh │
└─────────────────┘
```
## Bootstrap vs Full Compiler
### Bootstrap (Python)
- Минимальный компилятор на Python
- Используется один раз для сборки full compiler
- После успешной сборки не нужен
### Full Compiler (ContenT)
- Self-hosted, написан на ContenT
- Production-ready
- Все оптимизации
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
# ContenT
**ContenT** is a DSL compiler that transforms `.ct` files into optimized Bash scripts. The language syntax is a hybrid of Python, Go, and Vala.
[Русская версия](README_ru.md)
## Features
- **Clean syntax** — Python-like readability with Go/Vala influences
- **Classes & inheritance** — OOP with constructors and method calls
- **Lambdas**`x => x * 2`, `(a, b) => a + b`, multiline blocks
- **Decorators**`@retry`, `@log`, `@cache`, `@awk`
- **Pipe operator** — shell-like `|` for command chaining and functional composition
- **Error handling**`try/except/finally/throw/defer`
- **String interpolation**`"Hello, {name}!"`
- **@awk functions** — compile to AWK for ~300x speedup on string/numeric operations
- **Optimized output** - no unnecessary subshells, inlined methods
## Installation
```bash
git clone https://gitlab.eterfund.ru/ximperlinux/ContenT.git
cd content
```
Requires Python 3.8+ (bootstrap compiler).
## Quick Start
```bash
# Compile .ct to .sh
python3 content build main.ct
# Compile and run
python3 content run main.ct
# Compile with linting (ShellCheck)
python3 content build main.ct --lint
```
## Syntax Overview
### Variables & Strings
```
name = "World"
count = 42
message = "Hello, {name}!" # interpolation
```
### Functions
```
func greet (name, greeting = "Hello") {
print ("{greeting}, {name}!")
}
func sum (numbers...) { # variadic
total = 0
foreach n in numbers {
total += n
}
return total
}
```
### Classes
```
class Logger {
level = "INFO"
construct (level = "INFO") {
this.level = level
}
func log (msg) {
print ("[{this.level}] {msg}")
}
}
logger = Logger ("DEBUG")
logger.log ("Starting...")
```
### Pipe Operator
```
# Shell-like pipe — native bash pipes
files = shell.exec ("ls -la") | shell.exec ("grep txt") | shell.exec ("wc -l")
# Functional pipe — chain function calls
result = 5 | double | add_ten # = add_ten(double(5))
```
### Decorators
```
@retry (attempts = 3, delay = 1)
func fetch_data (url) {
return http.get (url)
}
@awk
func fast_sum (text) {
total = 0
n = text.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
```
### Control Flow
```
if count > 10 {
print ("Many")
} else if count > 0 {
print ("Some")
} else {
print ("None")
}
foreach item in items {
process (item)
}
for i in range (0, 10) {
print (i)
}
when value {
1 { print ("one") }
2, 3 { print ("two or three") }
4..10 { print ("four to ten") }
else { print ("other") }
}
```
### Error Handling
```
try {
data = fs.read (path)
return json.parse (data)
} except FileNotFound e {
print ("Not found: {e}")
return {}
} finally {
cleanup ()
}
```
## Standard Library
| Module | Functions |
|--------|-----------|
| **I/O** | `print()`, `exit()` |
| **HTTP** | `http.get/post/put/delete` |
| **Filesystem** | `fs.read/write/append/exists/remove/mkdir/list` |
| **JSON** | `json.parse/stringify` |
| **Strings** | `.len()`, `.upper()`, `.lower()`, `.trim()`, `.contains()`, `.replace()`, `.split()`, `.substr()` |
| **Arrays** | `.push()`, `.pop()`, `.shift()`, `.len()`, `.get()`, `.set()`, `.join()`, `.slice()` |
| **Dicts** | `.get()`, `.set()`, `.has()`, `.del()`, `.keys()` |
| **Regex** | `regex.match/extract` |
| **Shell** | `shell.exec/capture/source` |
| **Math** | `math.add/sub/mul/div/mod/min/max/abs` |
| **Time** | `time.now/ms` |
| **Random** | `random()`, `random_range()` |
| **Args** | `args.count/get` |
| **Logger** | `logger.info/warn/error/debug` |
## CLI Commands
```bash
# Build
content build main.ct # -> main.sh
content build main.ct -o app.sh # custom output
content build lib.ct main.ct -o app.sh # multi-file
content build . -o app.sh # all .ct in directory
# Run
content run main.ct
content run main.ct -- arg1 arg2 # with arguments
# Build library
content --build-lib MyLib.ct # -> MyLib.sh
# Lint
content build main.ct --lint # run ShellCheck
```
## @awk — High-Performance Functions
The `@awk` decorator compiles functions to AWK instead of Bash, providing **100-1000x speedup** on numeric and string operations.
### Benchmark Results
Heavy string benchmark (`examples/bench_heavy_*.ct`):
| Version | Time | Speedup |
|---------|------|---------|
| Bash | 57.8s | 1x |
| AWK | 0.09s | **~640x** |
Test includes: string concatenation, pattern search, CSV generation, word splitting (5000-10000 iterations each).
### Usage
```
# Same syntax — just add @awk
@awk
func fast_sum (n) {
total = 0
for i in range (1, n + 1) {
total += i
}
return total
}
# String processing
@awk
func count_words (text) {
n = text.split (" ")
return n
}
# Works on class methods too
class Calculator {
@awk
func compute (data) {
# fast computation
}
}
```
### Supported in @awk
- Variables, assignments (`=`, `+=`, `-=`, `*=`, `/=`, `%=`)
- Loops: `for i in range()`, `foreach`, `while`
- Conditions: `if/else if/else`, `when`
- Operators: `+`, `-`, `*`, `/`, `%`, `^`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `&&`, `||`
- String methods: `.len()`, `.upper()`, `.lower()`, `.trim()`, `.split()`, `.substr()`, `.contains()`, `.replace()`
- Array methods: `.len()`, `.get()`, `.set()`, `.push()`, `.pop()`
- Math: `math.sin()`, `math.cos()`, `math.sqrt()`, `math.log()`, `math.exp()`
- `break`, `continue`, `return`
### Limitations
- No access to `this` in class methods — pass data via parameters
- Arrays are associative (AWK limitation)
- No `ord()`/`chr()` (gawk-only)
Uses `mawk` (preferred) or `gawk` for maximum speed.
## Documentation
- [Language Specification](LANGUAGE_SPEC.md)
## Project Structure
```
bootstrap/ # Bootstrap compiler (Python)
├── main.py # CLI entry point
├── lexer.py # Tokenizer
├── parser.py # AST generation
├── codegen.py # Bash code generator
├── awk_codegen.py # AWK generator for @awk
└── stdlib.py # Standard library
examples/ # Example .ct programs
```
## License
[AGPL-3.0](LICENSE)
# ContenT
**ContenT** — DSL-компилятор, преобразующий `.ct` файлы в оптимизированные Bash-скрипты. Синтаксис языка — гибрид Python, Go и Vala.
[English version](README.md)
## Возможности
- **Чистый синтаксис** — читаемость Python с влиянием Go/Vala
- **Классы и наследование** — ООП с конструкторами и вызовами методов
- **Лямбды**`x => x * 2`, `(a, b) => a + b`, многострочные блоки
- **Декораторы**`@retry`, `@log`, `@cache`, `@awk`
- **Pipe-оператор** — shell-like `|` для цепочек команд и функциональной композиции
- **Обработка ошибок**`try/except/finally/throw/defer`
- **Строковая интерполяция**`"Привет, {name}!"`
- **@awk функции** — компиляция в AWK для ускорения ~300x на строковых/числовых операциях
- **Оптимизированный вывод** — без лишних subshell, инлайнинг методов
## Установка
```bash
git clone https://gitlab.eterfund.ru/ximperlinux/ContenT.git
cd content
```
Требуется Python 3.8+ (bootstrap-компилятор).
## Быстрый старт
```bash
# Компиляция .ct в .sh
python3 content build main.ct
# Компиляция и запуск
python3 content run main.ct
# Компиляция с линтингом (ShellCheck)
python3 content build main.ct --lint
```
## Обзор синтаксиса
### Переменные и строки
```
name = "Мир"
count = 42
message = "Привет, {name}!" # интерполяция
```
### Функции
```
func greet (name, greeting = "Привет") {
print ("{greeting}, {name}!")
}
func sum (numbers...) { # variadic
total = 0
foreach n in numbers {
total += n
}
return total
}
```
### Классы
```
class Logger {
level = "INFO"
construct (level = "INFO") {
this.level = level
}
func log (msg) {
print ("[{this.level}] {msg}")
}
}
logger = Logger ("DEBUG")
logger.log ("Запуск...")
```
### Pipe-оператор
```
# Shell-like pipe — нативные bash-пайпы
files = shell.exec ("ls -la") | shell.exec ("grep txt") | shell.exec ("wc -l")
# Функциональный pipe — цепочка вызовов функций
result = 5 | double | add_ten # = add_ten(double(5))
```
### Декораторы
```
@retry (attempts = 3, delay = 1)
func fetch_data (url) {
return http.get (url)
}
@awk
func fast_sum (text) {
total = 0
n = text.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
```
### Управление потоком
```
if count > 10 {
print ("Много")
} else if count > 0 {
print ("Немного")
} else {
print ("Ничего")
}
foreach item in items {
process (item)
}
for i in range (0, 10) {
print (i)
}
when value {
1 { print ("один") }
2, 3 { print ("два или три") }
4..10 { print ("от четырёх до десяти") }
else { print ("другое") }
}
```
### Обработка ошибок
```
try {
data = fs.read (path)
return json.parse (data)
} except FileNotFound e {
print ("Не найдено: {e}")
return {}
} finally {
cleanup ()
}
```
## Стандартная библиотека
| Модуль | Функции |
|--------|---------|
| **Ввод/вывод** | `print()`, `exit()` |
| **HTTP** | `http.get/post/put/delete` |
| **Файловая система** | `fs.read/write/append/exists/remove/mkdir/list` |
| **JSON** | `json.parse/stringify` |
| **Строки** | `.len()`, `.upper()`, `.lower()`, `.trim()`, `.contains()`, `.replace()`, `.split()`, `.substr()` |
| **Массивы** | `.push()`, `.pop()`, `.shift()`, `.len()`, `.get()`, `.set()`, `.join()`, `.slice()` |
| **Словари** | `.get()`, `.set()`, `.has()`, `.del()`, `.keys()` |
| **Regex** | `regex.match/extract` |
| **Shell** | `shell.exec/capture/source` |
| **Математика** | `math.add/sub/mul/div/mod/min/max/abs` |
| **Время** | `time.now/ms` |
| **Случайные числа** | `random()`, `random_range()` |
| **Аргументы** | `args.count/get` |
| **Логгер** | `logger.info/warn/error/debug` |
## Команды CLI
```bash
# Сборка
content build main.ct # -> main.sh
content build main.ct -o app.sh # свой выходной файл
content build lib.ct main.ct -o app.sh # несколько файлов
content build . -o app.sh # все .ct в директории
# Запуск
content run main.ct
content run main.ct -- arg1 arg2 # с аргументами
# Сборка библиотеки
content --build-lib MyLib.ct # -> MyLib.sh
# Линтинг
content build main.ct --lint # запуск ShellCheck
```
## @awk — Высокопроизводительные функции
Декоратор `@awk` компилирует функции в AWK вместо Bash, обеспечивая **ускорение в 100-1000 раз** на числовых и строковых операциях.
### Результаты бенчмарка
Тяжёлый строковый бенчмарк (`examples/bench_heavy_*.ct`):
| Версия | Время | Ускорение |
|--------|-------|-----------|
| Bash | 57.8с | 1x |
| AWK | 0.09с | **~640x** |
Тест включает: конкатенацию строк, поиск паттернов, генерацию CSV, разбиение слов (5000-10000 итераций каждый).
### Использование
```
# Тот же синтаксис — просто добавьте @awk
@awk
func fast_sum (n) {
total = 0
for i in range (1, n + 1) {
total += i
}
return total
}
# Обработка строк
@awk
func count_words (text) {
n = text.split (" ")
return n
}
# Работает и на методах классов
class Calculator {
@awk
func compute (data) {
# быстрые вычисления
}
}
```
### Поддерживается в @awk
- Переменные, присваивания (`=`, `+=`, `-=`, `*=`, `/=`, `%=`)
- Циклы: `for i in range()`, `foreach`, `while`
- Условия: `if/else if/else`, `when`
- Операторы: `+`, `-`, `*`, `/`, `%`, `^`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `&&`, `||`
- Методы строк: `.len()`, `.upper()`, `.lower()`, `.trim()`, `.split()`, `.substr()`, `.contains()`, `.replace()`
- Методы массивов: `.len()`, `.get()`, `.set()`, `.push()`, `.pop()`
- Математика: `math.sin()`, `math.cos()`, `math.sqrt()`, `math.log()`, `math.exp()`
- `break`, `continue`, `return`
### Ограничения
- Нет доступа к `this` в методах классов — передавайте данные через параметры
- Массивы ассоциативные (ограничение AWK)
- Нет `ord()`/`chr()` (только в gawk)
Использует `mawk` (предпочтительно) или `gawk` для максимальной скорости.
## Документация
- [Спецификация языка](LANGUAGE_SPEC.md)
## Структура проекта
```
bootstrap/ # Bootstrap-компилятор (Python)
├── main.py # CLI точка входа
├── lexer.py # Токенизатор
├── parser.py # Генерация AST
├── codegen.py # Генератор Bash-кода
├── awk_codegen.py # AWK-генератор для @awk
└── stdlib.py # Стандартная библиотека
examples/ # Примеры .ct программ
```
## Лицензия
[AGPL-3.0](LICENSE)
__version__ = "0.1.0"
from dataclasses import dataclass, field
from typing import List, Optional, Any, Union
@dataclass
class SourceLocation:
line: int
column: int
filename: str = "<stdin>"
@dataclass
class ASTNode:
pass
@dataclass
class Expression (ASTNode):
pass
@dataclass
class IntegerLiteral (Expression):
value: int = 0
location: Optional[SourceLocation] = None
@dataclass
class FloatLiteral (Expression):
value: float = 0.0
location: Optional[SourceLocation] = None
@dataclass
class StringLiteral (Expression):
value: str = ""
has_interpolation: bool = False
location: Optional[SourceLocation] = None
@dataclass
class BoolLiteral (Expression):
value: bool = False
location: Optional[SourceLocation] = None
@dataclass
class NilLiteral (Expression):
location: Optional[SourceLocation] = None
@dataclass
class Identifier (Expression):
name: str = ""
location: Optional[SourceLocation] = None
@dataclass
class ArrayLiteral (Expression):
elements: List[Expression] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class DictLiteral (Expression):
pairs: List[tuple] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class BinaryOp (Expression):
left: Optional[Expression] = None
operator: str = ""
right: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class UnaryOp (Expression):
operator: str = ""
operand: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class CallExpr (Expression):
callee: Optional[Expression] = None
arguments: List[Expression] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class MemberAccess (Expression):
object: Optional[Expression] = None
member: str = ""
location: Optional[SourceLocation] = None
@dataclass
class IndexAccess (Expression):
object: Optional[Expression] = None
index: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class Lambda (Expression):
params: List[str] = field (default_factory=list)
body: Union['Block', Expression, None] = None
location: Optional[SourceLocation] = None
@dataclass
class ThisExpr (Expression):
location: Optional[SourceLocation] = None
@dataclass
class BaseCall (Expression):
arguments: List[Expression] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class NewExpr (Expression):
class_name: str = ""
arguments: List[Expression] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class Statement (ASTNode):
pass
@dataclass
class Block (Statement):
statements: List[Statement] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class ExpressionStmt (Statement):
expression: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class Assignment (Statement):
target: Optional[Expression] = None
operator: str = "="
value: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class ReturnStmt (Statement):
value: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class BreakStmt (Statement):
location: Optional[SourceLocation] = None
@dataclass
class ContinueStmt (Statement):
location: Optional[SourceLocation] = None
@dataclass
class IfStmt (Statement):
condition: Optional[Expression] = None
then_branch: Optional[Block] = None
elif_branches: List[tuple] = field (default_factory=list)
else_branch: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class WhileStmt (Statement):
condition: Optional[Expression] = None
body: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class ForStmt (Statement):
variable: str = ""
iterable: Optional[Expression] = None
body: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class ForeachStmt (Statement):
variables: List[str] = field (default_factory=list)
iterable: Optional[Expression] = None
body: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class TryStmt (Statement):
try_block: Optional[Block] = None
except_clauses: List[tuple] = field (default_factory=list)
finally_block: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class ThrowStmt (Statement):
expression: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class DeferStmt (Statement):
expression: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class ImportStmt (Statement):
path: str = ""
location: Optional[SourceLocation] = None
@dataclass
class RangePattern (Expression):
"""Range pattern for when branches: 1..10"""
start: Optional[Expression] = None
end: Optional[Expression] = None
location: Optional[SourceLocation] = None
@dataclass
class WhenBranch:
"""Single branch of a when statement"""
patterns: List[Expression] = field (default_factory=list) # values, ranges, or 'else'
is_else: bool = False
body: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class WhenStmt (Statement):
"""When statement (pattern matching)"""
value: Optional[Expression] = None
branches: List[WhenBranch] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class Declaration (ASTNode):
pass
@dataclass
class Parameter:
name: str = ""
default: Optional[Expression] = None
is_variadic: bool = False
@dataclass
class Decorator:
name: str = ""
arguments: List[tuple] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class FunctionDecl (Declaration):
name: str = ""
params: List[Parameter] = field (default_factory=list)
body: Optional[Block] = None
decorators: List[Decorator] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class ClassDecl (Declaration):
name: str = ""
parent: Optional[str] = None
fields: List[tuple] = field (default_factory=list)
constructor: Optional['ConstructorDecl'] = None
methods: List[FunctionDecl] = field (default_factory=list)
location: Optional[SourceLocation] = None
@dataclass
class ConstructorDecl (Declaration):
params: List[Parameter] = field (default_factory=list)
body: Optional[Block] = None
location: Optional[SourceLocation] = None
@dataclass
class Program (ASTNode):
statements: List[Union[Statement, Declaration]] = field (default_factory=list)
location: Optional[SourceLocation] = None
from typing import List
from .ast_nodes import (
FunctionDecl, Assignment, ReturnStmt, IfStmt, WhileStmt,
ForStmt, ForeachStmt, ExpressionStmt, BreakStmt, ContinueStmt,
WhenStmt, RangePattern,
Block, Identifier, IntegerLiteral, FloatLiteral, StringLiteral,
BoolLiteral, NilLiteral, ArrayLiteral, DictLiteral, BinaryOp,
UnaryOp, CallExpr, IndexAccess, MemberAccess
)
AWK_MATH_FUNCS = {
"sin": lambda a: f"sin({a[0]})",
"cos": lambda a: f"cos({a[0]})",
"sqrt": lambda a: f"sqrt({a[0]})",
"log": lambda a: f"log({a[0]})",
"exp": lambda a: f"exp({a[0]})",
"int": lambda a: f"int({a[0]})",
"rand": lambda a: "rand()",
"atan2": lambda a: f"atan2({a[0]}, {a[1]})",
}
AWK_BUILTIN_FUNCS = {
"print": lambda a: f"print {', '.join(a)}" if a else "print",
"printf": lambda a: f"printf {', '.join(a)}",
"sprintf": lambda a: f"sprintf({', '.join(a)})",
"length": lambda a: f"length({a[0]})" if a else "length()",
"substr": lambda a: f"substr({', '.join(a)})",
"split": lambda a: f"split({', '.join(a)})",
"sub": lambda a: f"sub({', '.join(a)})",
"gsub": lambda a: f"gsub({', '.join(a)})",
"match": lambda a: f"match({', '.join(a)})",
"tolower": lambda a: f"tolower({a[0]})" if a else "",
"toupper": lambda a: f"toupper({a[0]})" if a else "",
"int": lambda a: f"int({a[0]})" if a else "",
}
class AwkCodegenMixin:
"""Mixin class for AWK code generation.
This mixin provides methods for compiling @awk decorated functions
to AWK instead of Bash, giving ~2000x performance boost on
string/numeric operations.
"""
def _awk_scan_types (self, stmts: list) -> dict:
"""Scan statements and determine variable types from assignments."""
var_types = {} # var_name -> "array" | "dict" | "string"
for stmt in stmts:
if isinstance (stmt, Assignment):
if isinstance (stmt.target, Identifier):
var_name = stmt.target.name
if isinstance (stmt.value, ArrayLiteral):
var_types[var_name] = "array"
elif isinstance (stmt.value, DictLiteral):
var_types[var_name] = "dict"
elif isinstance (stmt.value, StringLiteral):
var_types[var_name] = "string"
elif isinstance (stmt, IfStmt):
var_types.update (self._awk_scan_types (stmt.then_branch.statements))
for _, elif_block in stmt.elif_branches:
var_types.update (self._awk_scan_types (elif_block.statements))
if stmt.else_branch and isinstance (stmt.else_branch, Block):
var_types.update (self._awk_scan_types (stmt.else_branch.statements))
elif isinstance (stmt, (WhileStmt, ForStmt)):
var_types.update (self._awk_scan_types (stmt.body.statements))
elif isinstance (stmt, ForeachStmt):
var_types.update (self._awk_scan_types (stmt.body.statements))
elif isinstance (stmt, FunctionDecl):
var_types.update (self._awk_scan_types (stmt.body.statements))
elif isinstance (stmt, Block):
var_types.update (self._awk_scan_types (stmt.statements))
return var_types
def _awk_escape (self, s: str) -> str:
"""Escape string for embedding in bash single quotes."""
return s.replace ("'", "'\"'\"'")
def _awk_make_emitter (self):
"""Create AWK code emitter with indentation tracking."""
lines = []
indent = [0]
def emit (line): lines.append (" " * indent[0] + line)
def inc (): indent[0] += 1
def dec (): indent[0] -= 1
return lines, emit, inc, dec
def generate_awk_function (self, func: FunctionDecl):
"""Generate a function that runs as inline AWK instead of Bash."""
name = func.name
self.emit (f"{name} () {{")
self.indent_level += 1
nested_funcs = []
main_stmts = []
for stmt in func.body.statements:
if isinstance (stmt, FunctionDecl):
nested_funcs.append (stmt)
else:
main_stmts.append (stmt)
self._awk_var_types = self._awk_scan_types (func.body.statements)
input_foreach = None
input_idx = -1
for idx, stmt in enumerate (main_stmts):
if isinstance (stmt, ForeachStmt):
if isinstance (stmt.iterable, Identifier) and stmt.iterable.name == "__input__":
input_foreach = stmt
input_idx = idx
break
if input_foreach:
params_v = [f'-v {p.name}="${{{i + 2}}}"' for i, p in enumerate (func.params[1:])]
else:
params_v = [f'-v {p.name}="${{{i + 1}}}"' for i, p in enumerate (func.params)]
params_str = " ".join (params_v)
awk_cmd = f'"$__ct_awk_cmd" {params_str}'.strip () if params_str else '"$__ct_awk_cmd"'
if input_foreach:
before_stmts = main_stmts[:input_idx]
after_stmts = main_stmts[input_idx + 1:]
begin_lines, begin_emit, begin_inc, begin_dec = self._awk_make_emitter ()
for stmt in before_stmts:
self._awk_stmt (stmt, begin_emit, begin_inc, begin_dec)
line_lines, line_emit, line_inc, line_dec = self._awk_make_emitter ()
if len (input_foreach.variables) > 1:
line_emit (f"{input_foreach.variables[0]} = NR")
line_emit (f"{input_foreach.variables[1]} = $0")
else:
line_emit (f"{input_foreach.variables[0]} = $0")
for stmt in input_foreach.body.statements:
self._awk_stmt (stmt, line_emit, line_inc, line_dec)
end_lines, end_emit, end_inc, end_dec = self._awk_make_emitter ()
for stmt in after_stmts:
self._awk_stmt (stmt, end_emit, end_inc, end_dec)
self.emit (f"__CT_RET=$({awk_cmd} '")
for nf in nested_funcs:
self._awk_helper_func (nf)
if begin_lines:
self.emit ("BEGIN {")
for line in begin_lines:
self.emit (f" {self._awk_escape (line)}")
self.emit ("}")
self.emit ("{")
for line in line_lines:
self.emit (f" {self._awk_escape (line)}")
self.emit ("}")
if end_lines:
self.emit ("END {")
for line in end_lines:
self.emit (f" {self._awk_escape (line)}")
self.emit ("}")
self.emit ("' \"$1\")")
else:
awk_lines, awk_emit, awk_inc, awk_dec = self._awk_make_emitter ()
for stmt in main_stmts:
self._awk_stmt (stmt, awk_emit, awk_inc, awk_dec)
self.emit (f"__CT_RET=$({awk_cmd} '")
for nf in nested_funcs:
self._awk_helper_func (nf)
self.emit ("BEGIN {")
for line in awk_lines:
self.emit (f" {self._awk_escape (line)}")
self.emit ("}')")
self.emit ('echo "$__CT_RET"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _awk_helper_func (self, func: FunctionDecl):
"""Generate AWK helper function definition."""
params = ", ".join (p.name for p in func.params)
self.emit (f"function {func.name}({params}) {{")
lines, emit, inc, dec = self._awk_make_emitter ()
for stmt in func.body.statements:
self._awk_stmt (stmt, emit, inc, dec, in_func=True)
for line in lines:
self.emit (f" {self._awk_escape (line)}")
self.emit ("}")
def _awk_stmt (self, stmt, emit, inc, dec, in_func=False):
"""Generate AWK statement."""
if isinstance (stmt, FunctionDecl):
return
if isinstance (stmt, Assignment):
target = self._awk_target (stmt.target)
if isinstance (stmt.value, (ArrayLiteral, DictLiteral)):
var_types = getattr (self, '_awk_var_types', {})
if isinstance (stmt.target, Identifier):
if isinstance (stmt.value, ArrayLiteral):
var_types[stmt.target.name] = "array"
else:
var_types[stmt.target.name] = "dict"
self._awk_var_types = var_types
emit (f"delete {target}")
return
value = self._awk_expr (stmt.value)
op = stmt.operator
if op == "=":
emit (f"{target} = {value}")
elif op == "+=":
emit (f"{target} += {value}")
elif op == "-=":
emit (f"{target} -= {value}")
elif op == "*=":
emit (f"{target} *= {value}")
elif op == "/=":
emit (f"{target} /= {value}")
elif op == "%=":
emit (f"{target} %= {value}")
elif op == "..=":
emit (f"{target} = {target} {value}")
else:
emit (f"{target} = {value}")
elif isinstance (stmt, ReturnStmt):
if in_func:
if stmt.value:
emit (f"return {self._awk_expr (stmt.value)}")
else:
emit ("return")
else:
if stmt.value:
emit (f"print {self._awk_expr (stmt.value)}")
emit ("exit")
elif isinstance (stmt, IfStmt):
cond = self._awk_cond (stmt.condition)
emit (f"if ({cond}) {{")
inc ()
for s in stmt.then_branch.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
for elif_cond, elif_block in stmt.elif_branches:
emit (f"}} else if ({self._awk_cond (elif_cond)}) {{")
inc ()
for s in elif_block.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
if stmt.else_branch:
emit ("} else {")
inc ()
if isinstance (stmt.else_branch, Block):
for s in stmt.else_branch.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
else:
self._awk_stmt (stmt.else_branch, emit, inc, dec, in_func)
dec ()
emit ("}")
elif isinstance (stmt, WhileStmt):
emit (f"while ({self._awk_cond (stmt.condition)}) {{")
inc ()
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
elif isinstance (stmt, ForStmt):
var = stmt.variable
if isinstance (stmt.iterable, CallExpr) and isinstance (stmt.iterable.callee, Identifier):
if stmt.iterable.callee.name == "range":
args = stmt.iterable.arguments
if len (args) == 1:
start, end, step = "0", self._awk_expr (args[0]), "1"
elif len (args) == 2:
start, end, step = self._awk_expr (args[0]), self._awk_expr (args[1]), "1"
else:
start = self._awk_expr (args[0])
end = self._awk_expr (args[1])
step = self._awk_expr (args[2])
emit (f"for ({var} = {start}; {var} < {end}; {var} += {step}) {{")
inc ()
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
return
arr = self._awk_expr (stmt.iterable)
emit (f"for ({var} in {arr}) {{")
inc ()
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
elif isinstance (stmt, ForeachStmt):
var = stmt.variables[0]
iterable = stmt.iterable
if isinstance (iterable, CallExpr) and isinstance (iterable.callee, MemberAccess):
if (isinstance (iterable.callee.object, Identifier) and
iterable.callee.member == "split" and
len (iterable.arguments) >= 1):
text_var = iterable.callee.object.name
delim = self._awk_expr (iterable.arguments[0])
emit (f"__n = split({text_var}, __arr, {delim})")
emit ("for (__i = 1; __i <= __n; __i++) {")
inc ()
emit (f"{var} = __arr[__i]")
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
return
arr = self._awk_expr (iterable)
if len (stmt.variables) > 1:
key_var = stmt.variables[0]
val_var = stmt.variables[1]
emit (f"for ({key_var} in {arr}) {{")
inc ()
emit (f"{val_var} = {arr}[{key_var}]")
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
else:
emit (f"for ({var} in {arr}) {{")
inc ()
for s in stmt.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
elif isinstance (stmt, ExpressionStmt):
expr = self._awk_expr (stmt.expression)
if expr:
emit (expr)
elif isinstance (stmt, BreakStmt):
emit ("break")
elif isinstance (stmt, ContinueStmt):
emit ("continue")
elif isinstance (stmt, WhenStmt):
val = self._awk_expr (stmt.value)
emit (f"__when_val = {val}")
first = True
for branch in stmt.branches:
if branch.is_else:
emit ("} else {")
else:
conditions = []
for p in branch.patterns:
if isinstance (p, RangePattern):
start = self._awk_expr (p.start)
end = self._awk_expr (p.end)
conditions.append (f"(__when_val >= {start} && __when_val <= {end})")
else:
pval = self._awk_expr (p)
conditions.append (f"__when_val == {pval}")
cond_str = " || ".join (conditions)
if first:
emit (f"if ({cond_str}) {{")
first = False
else:
emit (f"}} else if ({cond_str}) {{")
inc ()
for s in branch.body.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
dec ()
emit ("}")
elif isinstance (stmt, Block):
for s in stmt.statements:
self._awk_stmt (s, emit, inc, dec, in_func)
def _awk_target (self, expr) -> str:
"""Generate AWK assignment target."""
if isinstance (expr, Identifier):
return expr.name
if isinstance (expr, IndexAccess):
obj = self._awk_expr (expr.object)
idx = self._awk_expr (expr.index)
return f"{obj}[{idx}]"
if isinstance (expr, MemberAccess):
obj = self._awk_expr (expr.object)
return f'{obj}["{expr.member}"]'
return self._awk_expr (expr)
def _awk_expr (self, expr) -> str:
"""Generate AWK expression."""
if expr is None:
return ""
if isinstance (expr, IntegerLiteral):
return str (expr.value)
if isinstance (expr, FloatLiteral):
return str (expr.value)
if isinstance (expr, StringLiteral):
value = expr.value
value = value.replace ('\\', '\\\\')
value = value.replace ('\n', '\\n')
value = value.replace ('\t', '\\t')
value = value.replace ('"', '\\"')
value = value.replace ("'", "\\047")
return f'"{value}"'
if isinstance (expr, BoolLiteral):
return "1" if expr.value else "0"
if isinstance (expr, NilLiteral):
return '""'
if isinstance (expr, Identifier):
return expr.name
if isinstance (expr, ArrayLiteral):
return '""'
if isinstance (expr, DictLiteral):
return '""'
if isinstance (expr, BinaryOp):
left = self._awk_expr (expr.left)
right = self._awk_expr (expr.right)
op = expr.operator
if op == "..":
return f"({left} {right})"
if op in ("==", "!=", "<", ">", "<=", ">=", "&&", "||", "+", "-", "*", "/", "%", "^"):
return f"({left} {op} {right})"
return f"({left} {op} {right})"
if isinstance (expr, UnaryOp):
operand = self._awk_expr (expr.operand)
if expr.operator == "!":
return f"(!{operand})"
if expr.operator == "-":
return f"(-{operand})"
if expr.operator == "++":
return f"(++{operand})"
if expr.operator == "--":
return f"(--{operand})"
return operand
if isinstance (expr, CallExpr):
if isinstance (expr.callee, MemberAccess) and isinstance (expr.callee.object, Identifier):
ns = expr.callee.object.name
method = expr.callee.member
args = expr.arguments
if ns == "math" and method in AWK_MATH_FUNCS:
awk_args = [self._awk_expr(a) for a in args]
return AWK_MATH_FUNCS[method](awk_args)
var_types = getattr (self, '_awk_var_types', {})
var_type = var_types.get (ns, "string")
if var_type == "array":
if method == "len":
return f"length({ns})"
if method == "push" and len (args) >= 1:
val = self._awk_expr (args[0])
return f"{ns}[length({ns}) + 1] = {val}"
if method == "pop":
return f"delete {ns}[length({ns})]"
if method == "shift":
return f"delete {ns}[1]"
if method == "get" and len (args) >= 1:
idx = self._awk_expr (args[0])
return f"{ns}[{idx}]"
if method == "set" and len (args) >= 2:
idx = self._awk_expr (args[0])
val = self._awk_expr (args[1])
return f"{ns}[{idx}] = {val}"
if method == "has" and len (args) >= 1:
key = self._awk_expr (args[0])
return f"({key} in {ns})"
if method == "del" and len (args) >= 1:
key = self._awk_expr (args[0])
return f"delete {ns}[{key}]"
elif var_type == "dict":
if method == "get" and len (args) >= 1:
key = self._awk_expr (args[0])
return f"{ns}[{key}]"
if method == "set" and len (args) >= 2:
key = self._awk_expr (args[0])
val = self._awk_expr (args[1])
return f"{ns}[{key}] = {val}"
if method == "has" and len (args) >= 1:
key = self._awk_expr (args[0])
return f"({key} in {ns})"
if method == "del" and len (args) >= 1:
key = self._awk_expr (args[0])
return f"delete {ns}[{key}]"
if method == "keys":
return f"{ns}"
else:
if method == "len":
return f"length({ns})"
if method == "upper":
return f"toupper({ns})"
if method == "lower":
return f"tolower({ns})"
if method == "contains" and len (args) >= 1:
needle = self._awk_expr (args[0])
return f"(index({ns}, {needle}) > 0)"
if method == "index" and len (args) >= 1:
needle = self._awk_expr (args[0])
return f"(index({ns}, {needle}) - 1)"
if method == "substr" and len (args) >= 2:
start = self._awk_expr (args[0])
length = self._awk_expr (args[1])
return f"substr({ns}, {start} + 1, {length})"
if method == "charAt" and len (args) >= 1:
pos = self._awk_expr (args[0])
return f"substr({ns}, {pos} + 1, 1)"
if method == "trim":
return f"(gsub(/^[ \\t]+|[ \\t]+$/, \"\", {ns}) ? {ns} : {ns})"
if method == "replace" and len (args) >= 2:
old = self._awk_expr (args[0])
new = self._awk_expr (args[1])
return f"(gsub({old}, {new}, {ns}) ? {ns} : {ns})"
if method == "split" and len (args) >= 1:
delim = self._awk_expr (args[0])
return f"split({ns}, __split_arr, {delim})"
if method == "starts" and len (args) >= 1:
prefix = self._awk_expr (args[0])
return f"(substr({ns}, 1, length({prefix})) == {prefix})"
if method == "ends" and len (args) >= 1:
suffix = self._awk_expr (args[0])
return f"(substr({ns}, length({ns}) - length({suffix}) + 1) == {suffix})"
if isinstance (expr.callee, Identifier):
func_name = expr.callee.name
args = [self._awk_expr(a) for a in expr.arguments]
if func_name in AWK_BUILTIN_FUNCS:
return AWK_BUILTIN_FUNCS[func_name](args)
return f"{func_name}({', '.join(args)})"
return ""
if isinstance (expr, IndexAccess):
obj = self._awk_expr (expr.object)
idx = self._awk_expr (expr.index)
return f"{obj}[{idx}]"
if isinstance (expr, MemberAccess):
obj = self._awk_expr (expr.object)
return f'{obj}["{expr.member}"]'
return ""
def _awk_cond (self, expr) -> str:
"""Generate AWK condition without outer parens."""
result = self._awk_expr (expr)
if result.startswith ('(') and result.endswith (')'):
return result[1:-1]
return result
from .ast_nodes import *
class ClassMixin:
"""Mixin for class and method generation."""
def generate_class(self, cls: ClassDecl):
self.current_class = cls.name
self.current_class_fields = set(field_name for field_name, _ in cls.fields)
for field_name, default_value in cls.fields:
if isinstance(default_value, ArrayLiteral):
self.class_field_types[(cls.name, field_name)] = "array"
elif isinstance(default_value, DictLiteral):
self.class_field_types[(cls.name, field_name)] = "dict"
else:
self.class_field_types[(cls.name, field_name)] = "scalar"
for method in cls.methods:
self._check_inlineable_method(cls, method)
self._generate_class_constructor(cls)
if cls.constructor:
self._generate_construct_method(cls)
for method in cls.methods:
has_awk = any(dec.name == "awk" for dec in method.decorators)
if has_awk:
self._generate_awk_method(cls, method)
elif method.decorators:
self._generate_decorated_method(cls, method)
else:
self._generate_plain_method(cls, method)
if cls.parent and cls.parent in self.classes:
parent_cls = self.classes[cls.parent]
own_method_names = {m.name for m in cls.methods}
for parent_method in parent_cls.methods:
if parent_method.name not in own_method_names:
self._generate_inherited_method(cls, parent_cls, parent_method)
self.current_class = None
self.current_class_fields = set()
def _generate_class_constructor(self, cls: ClassDecl):
"""Generate class factory function."""
self.emit(f"{cls.name} () {{")
self.indent_level += 1
self.emit('__ct_last_instance="__ct_inst_$RANDOM$RANDOM"')
self.emit(f'__ct_obj_class["$__ct_last_instance"]="{cls.name}"')
for field_name, default_value in cls.fields:
if isinstance(default_value, ArrayLiteral):
elements = [self.generate_expr(e) for e in default_value.elements]
if elements:
arr_content = " ".join([f'"{e}"' for e in elements])
self.emit(f'declare -ga "${{__ct_last_instance}}_{field_name}=({arr_content})"')
else:
self.emit(f'declare -ga "${{__ct_last_instance}}_{field_name}=()"')
elif isinstance(default_value, DictLiteral):
self.emit(f'declare -gA "${{__ct_last_instance}}_{field_name}=()"')
self.emit(f'__CT_OBJ["$__ct_last_instance.{field_name}"]="${{__ct_last_instance}}_{field_name}"')
elif default_value:
val = self.generate_expr(default_value)
self.emit(f'__CT_OBJ["$__ct_last_instance.{field_name}"]="{val}"')
else:
self.emit(f'__CT_OBJ["$__ct_last_instance.{field_name}"]=""')
if cls.parent:
self.emit(f'# Inherit from {cls.parent}')
if cls.constructor:
self.emit("# Call constructor")
params_list = " ".join([f'"${{{i + 1}}}"' for i in range(len(cls.constructor.params))])
self.emit(f'__ct_class_{cls.name}_construct "$__ct_last_instance" {params_list}')
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_construct_method(self, cls: ClassDecl):
"""Generate construct method."""
self.emit(f"__ct_class_{cls.name}_construct () {{")
self.indent_level += 1
self.emit('local this="$1"')
self.emit('shift')
self.in_class_method = True
old_in_function = self.in_function
old_local_vars = self.local_vars.copy()
self.in_function = True
self.local_vars = set()
for i, param in enumerate(cls.constructor.params):
if param.default is not None:
default_val = self.generate_expr(param.default)
self.emit(f'local {param.name}="${{{i + 1}:-{default_val}}}"')
else:
self.emit(f'local {param.name}="${{{i + 1}}}"')
self.local_vars.add(param.name)
for stmt in cls.constructor.body.statements:
self.generate_statement(stmt)
self.in_class_method = False
self.in_function = old_in_function
self.local_vars = old_local_vars
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_plain_method(self, cls: ClassDecl, method: FunctionDecl):
"""Generate a plain class method."""
self.emit(f"__ct_class_{cls.name}_{method.name} () {{")
self.indent_level += 1
self.emit('local this="$1"')
self.emit('shift')
self.in_class_method = True
old_in_function = self.in_function
old_local_vars = self.local_vars.copy()
self.in_function = True
self.local_vars = set()
for i, param in enumerate(method.params):
if param.is_variadic:
self.emit(f'local -a {param.name}=("${{@:{i + 1}}}")')
else:
if param.default is not None:
default_val = self.generate_expr(param.default)
self.emit(f'local {param.name}="${{{i + 1}:-{default_val}}}"')
else:
self.emit(f'local {param.name}="${{{i + 1}}}"')
self.local_vars.add(param.name)
for stmt in method.body.statements:
self.generate_statement(stmt)
self.in_class_method = False
self.in_function = old_in_function
self.local_vars = old_local_vars
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_inherited_method(self, child_cls: ClassDecl, parent_cls: ClassDecl, method: FunctionDecl):
"""Generate proxy method for inherited method."""
self.emit(f"__ct_class_{child_cls.name}_{method.name} () {{")
self.indent_level += 1
self.emit(f'__ct_class_{parent_cls.name}_{method.name} "$@"')
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_decorated_method(self, cls: ClassDecl, method: FunctionDecl):
"""Generate a class method with decorators."""
base_name = f"__ct_class_{cls.name}_{method.name}"
original_name = f"{base_name}_orig"
self.emit(f"{original_name} () {{")
self.indent_level += 1
self.emit('local this="$1"')
self.emit('shift')
self.in_class_method = True
old_in_function = self.in_function
old_local_vars = self.local_vars.copy()
self.in_function = True
self.local_vars = set()
for i, param in enumerate(method.params):
if param.is_variadic:
self.emit(f'local -a {param.name}=("${{@:{i + 1}}}")')
else:
if param.default is not None:
default_val = self.generate_expr(param.default)
self.emit(f'local {param.name}="${{{i + 1}:-{default_val}}}"')
else:
self.emit(f'local {param.name}="${{{i + 1}}}"')
self.local_vars.add(param.name)
for stmt in method.body.statements:
self.generate_statement(stmt)
self.in_class_method = False
self.in_function = old_in_function
self.local_vars = old_local_vars
self.indent_level -= 1
self.emit("}")
self.emit()
current_name = original_name
for i, decorator in enumerate(reversed(method.decorators)):
wrapper_name = f"{base_name}_d{i}"
self.generate_method_decorator_wrapper(decorator, current_name, wrapper_name, method.params)
current_name = wrapper_name
self.emit(f"{base_name} () {{")
self.indent_level += 1
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(method.params) + 1)])
self.emit(f'{current_name} {params_str}')
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_awk_method(self, cls: ClassDecl, method: FunctionDecl):
"""Generate @awk method for class."""
awk_func_name = f"__ct_class_{cls.name}_{method.name}_awk"
method_name = f"__ct_class_{cls.name}_{method.name}"
temp_func = FunctionDecl(
name=awk_func_name,
params=method.params,
body=method.body,
decorators=[],
location=method.location
)
self.generate_awk_function(temp_func)
self.emit(f"# @awk method - 'this' is ignored, calls AWK function")
self.emit(f"{method_name} () {{")
self.indent_level += 1
self.emit('shift # ignore this')
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(method.params))])
self.emit(f'{awk_func_name} {params_str}')
self.indent_level -= 1
self.emit("}")
self.emit()
def _check_inlineable_method(self, cls: ClassDecl, method: FunctionDecl):
"""Check if method can be inlined."""
if method.params:
return
if len(method.body.statements) != 1:
return
stmt = method.body.statements[0]
if not isinstance(stmt, ReturnStmt) or not stmt.value:
return
value = stmt.value
if isinstance(value, MemberAccess) and isinstance(value.object, ThisExpr):
field = value.member
field_names = [f for f, _ in cls.fields]
if field in field_names:
self.inlineable_methods[(cls.name, method.name)] = f'${{__CT_OBJ["$this.{field}"]}}'
return
if isinstance(value, CallExpr) and isinstance(value.callee, MemberAccess):
if isinstance(value.callee.object, Identifier) and value.callee.object.name == "str":
if value.callee.member == "charAt" and len(value.arguments) == 2:
arg0, arg1 = value.arguments
if isinstance(arg0, MemberAccess) and isinstance(arg0.object, ThisExpr):
if isinstance(arg1, MemberAccess) and isinstance(arg1.object, ThisExpr):
self.inlineable_methods[(cls.name, method.name)] = \
f'${{__CT_OBJ["$this.{arg0.member}"]:${{__CT_OBJ["$this.{arg1.member}"]}}:1}}'
def generate_function(self, func: FunctionDecl):
for dec in func.decorators:
if dec.name == "awk":
self.generate_awk_function(func)
return
if func.decorators:
self.generate_decorated_function(func)
return
name = func.name
if self.current_class:
name = f"__ct_class_{self.current_class}_{func.name}"
self.emit(f"{name} () {{")
self.indent_level += 1
for i, param in enumerate(func.params):
if param.is_variadic:
self.emit(f'local -a {param.name}=("${{@:{i + 1}}}")')
else:
if param.default is not None:
default_val = self.generate_expr(param.default)
self.emit(f'local {param.name}="${{{i + 1}:-{default_val}}}"')
else:
self.emit(f'local {param.name}="${{{i + 1}}}"')
old_deferred = self.deferred_calls
self.deferred_calls = []
old_in_function = self.in_function
self.in_function = True
old_local_vars = self.local_vars
self.local_vars = set()
for param in func.params:
self.local_vars.add(param.name)
for stmt in func.body.statements:
self.generate_statement(stmt)
if self.deferred_calls:
self.emit("# Deferred calls")
for call in reversed(self.deferred_calls):
self.emit(call)
self.deferred_calls = old_deferred
self.in_function = old_in_function
self.local_vars = old_local_vars
self.indent_level -= 1
self.emit("}")
self.emit()
def generate_decorated_function(self, func: FunctionDecl) -> str:
original_name = f"__ct_orig_{func.name}"
temp_func = FunctionDecl(
name=original_name,
params=func.params,
body=func.body,
decorators=[],
location=func.location
)
self.generate_function(temp_func)
current_name = original_name
for i, decorator in enumerate(reversed(func.decorators)):
wrapper_name = f"__ct_decorated_{func.name}_{i}"
self.generate_decorator_wrapper(decorator, current_name, wrapper_name, func.params)
current_name = wrapper_name
self.emit(f"{func.name} () {{")
self.indent_level += 1
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(func.params))])
self.emit(f'{current_name} {params_str}')
self.indent_level -= 1
self.emit("}")
self.emit()
return current_name
from typing import List, Dict, Optional, Set
from .ast_nodes import *
from .errors import ErrorCollector
from .stdlib import StdlibMixin
from .awk_codegen import AwkCodegenMixin
from .expr_codegen import ExprMixin
from .stmt_codegen import StmtMixin
from .class_codegen import ClassMixin
from .decorator_codegen import DecoratorMixin
from .dispatch_codegen import DispatchMixin
from .cse_codegen import CseMixin
class CodeGenerator(StdlibMixin, AwkCodegenMixin, ExprMixin, StmtMixin,
ClassMixin, DecoratorMixin, DispatchMixin, CseMixin):
"""
Main code generator class.
Combines mixins:
- StdlibMixin: stdlib function generation
- AwkCodegenMixin: @awk decorator compilation
- ExprMixin: expression generation
- StmtMixin: statement generation
- ClassMixin: class and method generation
- DecoratorMixin: decorator wrapper generation
- DispatchMixin: method dispatch and assignments
- CseMixin: common subexpression elimination
"""
def __init__(self):
self.output: List[str] = []
self.indent_level = 0
self.errors = ErrorCollector()
self.current_class: Optional[str] = None
self.current_class_fields: Set[str] = set()
self.in_class_method = False
self.in_function = False
self.classes: Dict[str, ClassDecl] = {}
self.functions: Dict[str, FunctionDecl] = {}
self.inlineable_methods: Dict[tuple, str] = {}
self.array_vars: Set[str] = set()
self.dict_vars: Set[str] = set()
self.class_field_types: Dict[tuple, str] = {}
self.local_vars: Set[str] = set()
self.global_vars: Set[str] = {
'L_SRC', 'L_POS', 'L_LEN', 'L_LINE', 'L_COL', 'L_FILE',
'T_TYPES', 'T_VALUES', 'T_LINES', 'T_COUNT',
'P_POS', 'P_STACK',
'A_TYPES', 'A_V1', 'A_V2', 'A_V3', 'A_V4', 'A_V5', 'A_V6', 'A_COUNT',
'G_OUT', 'G_INDENT', 'G_IN_FUNC', 'G_IN_CLASS', 'G_CUR_CLASS',
'G_DEFERRED', 'G_CLASSES', 'G_FUNCS', 'G_ARRAY_VARS', 'G_LOCAL_VARS', 'G_GLOBAL_VARS',
'G_TEMP_CTR', 'G_LAMBDA_CTR',
'G_CSE_KEYS', 'G_CSE_VALS', 'G_CSE_REGEN', 'G_CSE_CALLS',
'G_AWK_LINES', 'G_AWK_INDENT',
'__CT_RET',
}
self.lambda_counter = 0
self.temp_counter = 0
self.deferred_calls: List[str] = []
def indent(self) -> str:
return " " * self.indent_level
def emit(self, line: str = ""):
if line:
self.output.append(f"{self.indent()}{line}")
else:
self.output.append("")
def emit_raw(self, line: str):
self.output.append(line)
def emit_var_assign(self, var_name: str, value: str, is_array: bool = False):
"""Emit variable assignment with proper local declaration."""
if '.' in var_name or '[' in var_name:
self.emit(f'{var_name}="{value}"')
return
if self.in_function and var_name not in self.local_vars and var_name not in self.global_vars:
self.local_vars.add(var_name)
if is_array:
self.emit(f'local -a {var_name}=("{value}")')
else:
self.emit(f'local {var_name}="{value}"')
else:
self.emit(f'{var_name}="{value}"')
def new_temp(self) -> str:
self.temp_counter += 1
return f"__ct_tmp_{self.temp_counter}"
def new_lambda_name(self) -> str:
self.lambda_counter += 1
return f"__ct_lambda_{self.lambda_counter}"
def generate(self, program: Program) -> str:
"""Generate code for a single program."""
return self.generate_multi([program])
def generate_multi(self, programs: list) -> str:
"""Generate code for multiple programs (multi-file compilation)."""
self.emit_raw("#!/usr/bin/env bash")
self.emit_raw("# Generated by ContenT compiler")
self.emit_raw("set -euo pipefail")
self.emit()
self.emit_stdlib()
for program in programs:
for stmt in program.statements:
if isinstance(stmt, ClassDecl):
self.classes[stmt.name] = stmt
elif isinstance(stmt, FunctionDecl):
self.functions[stmt.name] = stmt
elif isinstance(stmt, Assignment):
if isinstance(stmt.target, Identifier):
self.global_vars.add(stmt.target.name)
for program in programs:
for stmt in program.statements:
self.generate_statement(stmt)
return "\n".join(self.output)
from .ast_nodes import *
class CseMixin:
"""Mixin for CSE optimization."""
def collect_method_calls(self, expr: Expression, calls: list):
"""Collect this.method() calls from an expression."""
if isinstance(expr, CallExpr):
if isinstance(expr.callee, MemberAccess) and isinstance(expr.callee.object, ThisExpr):
calls.append(expr)
for arg in expr.arguments:
self.collect_method_calls(arg, calls)
elif isinstance(expr, BinaryOp):
self.collect_method_calls(expr.left, calls)
self.collect_method_calls(expr.right, calls)
elif isinstance(expr, UnaryOp):
self.collect_method_calls(expr.operand, calls)
elif isinstance(expr, MemberAccess):
self.collect_method_calls(expr.object, calls)
def collect_all_calls(self, expr: Expression, calls: list):
"""Collect ALL function calls from an expression."""
if isinstance(expr, CallExpr):
calls.append(expr)
for arg in expr.arguments:
self.collect_all_calls(arg, calls)
elif isinstance(expr, BinaryOp):
self.collect_all_calls(expr.left, calls)
self.collect_all_calls(expr.right, calls)
elif isinstance(expr, UnaryOp):
self.collect_all_calls(expr.operand, calls)
elif isinstance(expr, MemberAccess):
self.collect_all_calls(expr.object, calls)
def precompute_condition_calls(self, condition: Expression) -> tuple:
"""Pre-compute method calls in condition."""
calls = []
self.collect_method_calls(condition, calls)
seen = {}
mapping = {}
regen_code = []
for call in calls:
method = call.callee.member
args = [self.generate_expr(arg) for arg in call.arguments]
args_str = " ".join([f'"{a}"' for a in args])
key = f"this.{method}({args_str})"
if key not in seen:
temp = self.new_temp()
call_line = f'__ct_class_{self.current_class}_{method} "$this" {args_str} >/dev/null'
assign_line = f'{temp}="$__CT_RET"'
self.emit(call_line)
self.emit(assign_line)
seen[key] = temp
regen_code.append((call_line, assign_line))
mapping[id(call)] = seen[key]
return mapping, regen_code
def precompute_all_calls(self, condition: Expression) -> tuple:
"""Pre-compute all function calls in condition."""
calls = []
self.collect_all_calls(condition, calls)
seen = {}
mapping = {}
regen_code = []
for call in calls:
if isinstance(call.callee, MemberAccess):
if isinstance(call.callee.object, ThisExpr):
method = call.callee.member
args = [self.generate_expr(arg) for arg in call.arguments]
args_str = " ".join([f'"{a}"' for a in args])
key = f"this.{method}({args_str})"
if key not in seen:
temp = self.new_temp()
call_line = f'__ct_class_{self.current_class}_{method} "$this" {args_str} >/dev/null'
assign_line = f'{temp}="$__CT_RET"'
self.emit(call_line)
self.emit(assign_line)
seen[key] = temp
regen_code.append((call_line, assign_line))
mapping[id(call)] = seen[key]
elif isinstance(call.callee.object, Identifier):
obj_name = call.callee.object.name
method = call.callee.member
args = [self.generate_expr(arg) for arg in call.arguments]
args_str = " ".join([f'"{a}"' for a in args])
key = f"{obj_name}.{method}({args_str})"
if key not in seen:
temp = self.new_temp()
call_expr = self.generate_expr(call)
if call_expr.startswith('$'):
call_line = f'{temp}="{call_expr}"'
else:
call_line = f'{temp}="$({call_expr})"'
self.emit(call_line)
seen[key] = temp
regen_code.append((call_line, ""))
mapping[id(call)] = seen[key]
elif isinstance(call.callee, Identifier):
func_name = call.callee.name
args = [self.generate_expr(arg) for arg in call.arguments]
args_str = " ".join([f'"{a}"' for a in args])
key = f"{func_name}({args_str})"
if key not in seen:
temp = self.new_temp()
call_line = f'{func_name} {args_str} >/dev/null'
assign_line = f'{temp}="$__CT_RET"'
self.emit(call_line)
self.emit(assign_line)
seen[key] = temp
regen_code.append((call_line, assign_line))
mapping[id(call)] = seen[key]
return mapping, regen_code
def generate_condition_with_precompute(self, expr: Expression, mapping: dict) -> str:
"""Generate condition using pre-computed values."""
if isinstance(expr, BinaryOp):
left = self.generate_expr_with_precompute(expr.left, mapping)
right = self.generate_expr_with_precompute(expr.right, mapping)
op = expr.operator
if op == "==":
return f'[[ "{left}" == "{right}" ]]'
elif op == "!=":
return f'[[ "{left}" != "{right}" ]]'
elif op == "<":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" < "{right}" ]]'
return f'[[ {left} -lt {right} ]]'
elif op == ">":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" > "{right}" ]]'
return f'[[ {left} -gt {right} ]]'
elif op == "<=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" > "{right}" ]]'
return f'[[ {left} -le {right} ]]'
elif op == ">=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" < "{right}" ]]'
return f'[[ {left} -ge {right} ]]'
elif op == "&&":
l = self.generate_condition_with_precompute(expr.left, mapping)
r = self.generate_condition_with_precompute(expr.right, mapping)
return f'{{ {l} && {r}; }}'
elif op == "||":
l = self.generate_condition_with_precompute(expr.left, mapping)
r = self.generate_condition_with_precompute(expr.right, mapping)
return f'{{ {l} || {r}; }}'
if isinstance(expr, UnaryOp) and expr.operator == "!":
inner = self.generate_condition_with_precompute(expr.operand, mapping)
return f'! {inner}'
if isinstance(expr, Identifier):
return f'[[ "${expr.name}" == "true" ]]'
if isinstance(expr, BoolLiteral):
return "true" if expr.value else "false"
return self.generate_condition(expr)
def generate_expr_with_precompute(self, expr: Expression, mapping: dict) -> str:
"""Generate expression using pre-computed values."""
if isinstance(expr, CallExpr) and id(expr) in mapping:
return f'${mapping[id(expr)]}'
if isinstance(expr, MemberAccess):
if isinstance(expr.object, CallExpr) and id(expr.object) in mapping:
temp = mapping[id(expr.object)]
return f'${{__CT_OBJ["${temp}.{expr.member}"]}}'
return self.generate_expr(expr)
return self.generate_expr(expr)
from typing import List
from .ast_nodes import *
class DecoratorMixin:
"""Mixin for decorator wrapper generation."""
def generate_decorator_wrapper(self, decorator: Decorator, wrapped_name: str,
wrapper_name: str, params: List[Parameter]):
"""Generate decorator wrapper for standalone function."""
if decorator.name == "retry":
self._generate_retry_wrapper(decorator, wrapped_name, wrapper_name, params, is_method=False)
elif decorator.name == "log":
self._generate_log_wrapper(wrapped_name, wrapper_name, params, is_method=False)
elif decorator.name == "cache":
self._generate_cache_wrapper(decorator, wrapped_name, wrapper_name, params, is_method=False)
else:
self._generate_passthrough_wrapper(wrapped_name, wrapper_name, params, is_method=False)
def generate_method_decorator_wrapper(self, decorator: Decorator, wrapped_name: str,
wrapper_name: str, params: List[Parameter]):
"""Generate decorator wrapper for class method."""
if decorator.name == "retry":
self._generate_retry_wrapper(decorator, wrapped_name, wrapper_name, params, is_method=True)
elif decorator.name == "log":
self._generate_log_wrapper(wrapped_name, wrapper_name, params, is_method=True)
elif decorator.name == "cache":
self._generate_cache_wrapper(decorator, wrapped_name, wrapper_name, params, is_method=True)
else:
self._generate_passthrough_wrapper(wrapped_name, wrapper_name, params, is_method=True)
self.current_class = None
self.current_class_fields = set()
def _generate_retry_wrapper(self, decorator: Decorator, wrapped_name: str,
wrapper_name: str, params: List[Parameter], is_method: bool):
attempts = 3
delay = 1
for arg_name, arg_val in decorator.arguments:
if arg_name == "attempts":
attempts = self.generate_expr(arg_val)
elif arg_name == "delay":
delay = self.generate_expr(arg_val)
self.emit(f"{wrapper_name} () {{")
self.indent_level += 1
if is_method:
self.emit('local this="$1"')
self.emit('shift')
self.emit(f"local __attempts={attempts}")
self.emit(f"local __delay={delay}")
self.emit("local __i")
self.emit("for __i in $(seq 1 $__attempts); do")
self.indent_level += 1
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(params))])
if is_method:
self.emit(f'if {wrapped_name} "$this" {params_str}; then')
else:
self.emit(f'if {wrapped_name} {params_str}; then')
self.indent_level += 1
self.emit("return 0")
self.indent_level -= 1
self.emit("fi")
self.emit('sleep "$__delay"')
self.indent_level -= 1
self.emit("done")
self.emit("return 1")
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_log_wrapper(self, wrapped_name: str, wrapper_name: str,
params: List[Parameter], is_method: bool):
self.emit(f"{wrapper_name} () {{")
self.indent_level += 1
if is_method:
self.emit('local this="$1"')
self.emit('shift')
self.emit(f'echo "[LOG] Calling {wrapped_name}" >&2')
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(params))])
if is_method:
self.emit(f'{wrapped_name} "$this" {params_str}')
else:
self.emit(f'{wrapped_name} {params_str}')
self.emit('local __ret=$?')
self.emit(f'echo "[LOG] {wrapped_name} returned $__ret" >&2')
self.emit('return $__ret')
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_cache_wrapper(self, decorator: Decorator, wrapped_name: str,
wrapper_name: str, params: List[Parameter], is_method: bool):
ttl = 60
for arg_name, arg_val in decorator.arguments:
if arg_name == "ttl":
ttl = self.generate_expr(arg_val)
self.emit(f"declare -gA __ct_cache_{wrapper_name}=()")
self.emit(f"declare -g __ct_cache_time_{wrapper_name}=0")
self.emit()
self.emit(f"{wrapper_name} () {{")
self.indent_level += 1
if is_method:
self.emit('local this="$1"')
self.emit('shift')
self.emit(f'local __key="$this:$*"')
else:
self.emit(f'local __key="$*"')
self.emit(f'local __now=$(date +%s)')
self.emit(f'local __cache_age=$((__now - __ct_cache_time_{wrapper_name}))')
self.emit(f'if [[ $__cache_age -lt {ttl} ]] && [[ -n "${{__ct_cache_{wrapper_name}[$__key]:-}}" ]]; then')
self.indent_level += 1
self.emit(f'__CT_RET="${{__ct_cache_{wrapper_name}[$__key]}}"')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
self.indent_level -= 1
self.emit("fi")
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(params))])
if is_method:
self.emit(f'local __result=$({wrapped_name} "$this" {params_str})')
else:
self.emit(f'local __result=$({wrapped_name} {params_str})')
self.emit(f'__CT_RET="$__result"')
self.emit(f'__ct_cache_{wrapper_name}["$__key"]="$__result"')
self.emit(f'__ct_cache_time_{wrapper_name}=$__now')
self.emit('echo "$__result"')
self.indent_level -= 1
self.emit("}")
self.emit()
def _generate_passthrough_wrapper(self, wrapped_name: str, wrapper_name: str,
params: List[Parameter], is_method: bool):
self.emit(f"{wrapper_name} () {{")
self.indent_level += 1
if is_method:
self.emit('local this="$1"')
self.emit('shift')
params_str = " ".join([f'"${{{i + 1}}}"' for i in range(len(params))])
if is_method:
self.emit(f'{wrapped_name} "$this" {params_str}')
else:
self.emit(f'{wrapped_name} {params_str}')
self.indent_level -= 1
self.emit("}")
self.emit()
from .ast_nodes import *
ARR_METHODS = {
"len": "__ct_arr_len", "push": "__ct_arr_push", "pop": "__ct_arr_pop",
"shift": "__ct_arr_shift", "join": "__ct_arr_join", "get": "__ct_arr_get",
"set": "__ct_arr_set", "slice": "__ct_arr_slice",
}
DICT_METHODS = {
"get": "__ct_dict_get", "set": "__ct_dict_set", "has": "__ct_dict_has",
"del": "__ct_dict_del", "keys": "__ct_dict_keys",
}
STR_METHODS = {
"len": "__ct_str_len", "upper": "__ct_str_upper", "lower": "__ct_str_lower",
"trim": "__ct_str_trim", "contains": "__ct_str_contains", "starts": "__ct_str_starts",
"ends": "__ct_str_ends", "index": "__ct_str_index", "replace": "__ct_str_replace",
"substr": "__ct_str_substr", "split": "__ct_str_split", "charAt": "__ct_str_char_at",
}
BUILTIN_NAMESPACES = {"fs", "http", "json", "logger", "regex", "args", "shell", "time", "math"}
BUILTIN_FUNCS = {"print", "exit", "len", "range", "ngrep", "is_number", "is_empty", "chr", "ord"}
class DispatchMixin:
"""Mixin for method dispatch and assignment."""
def generate_assignment(self, stmt: Assignment):
if isinstance(stmt.target, MemberAccess):
if isinstance(stmt.target.object, ThisExpr):
self._generate_this_field_assignment(stmt)
return
target = self.generate_lvalue(stmt.target)
if isinstance(stmt.value, BinaryOp) and stmt.value.operator == "|":
self._generate_pipe_assignment(stmt, target)
return
if isinstance(stmt.value, Lambda):
self.generate_lambda_as_function(stmt.value, target)
return
if isinstance(stmt.value, NewExpr):
args = [self.generate_expr(arg) for arg in stmt.value.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{stmt.value.class_name} {args_str}')
self.emit_var_assign(target, '$__ct_last_instance')
return
if isinstance(stmt.value, CallExpr) and isinstance(stmt.value.callee, Identifier):
callee_name = stmt.value.callee.name
if callee_name in self.classes:
args = [self.generate_expr(arg) for arg in stmt.value.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{callee_name} {args_str}')
self.emit_var_assign(target, '$__ct_last_instance')
return
if isinstance(stmt.value, CallExpr) and isinstance(stmt.value.callee, MemberAccess):
if self._generate_method_call_assignment(stmt, target):
return
if isinstance(stmt.value, CallExpr) and isinstance(stmt.value.callee, Identifier):
func_name = stmt.value.callee.name
if func_name not in BUILTIN_FUNCS and func_name not in self.classes:
args = [self.generate_expr(arg) for arg in stmt.value.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{func_name} {args_str} >/dev/null')
self.emit_var_assign(target, '$__CT_RET')
return
if isinstance(stmt.value, ArrayLiteral):
self._generate_array_assignment(stmt, target)
return
if isinstance(stmt.value, DictLiteral):
self._generate_dict_assignment(stmt, target)
return
if isinstance(stmt.value, Identifier):
src_name = stmt.value.name
if src_name in self.array_vars:
self.emit(f'{target}=("${{{src_name}[@]}}")')
self.array_vars.add(target)
return
if isinstance(stmt.value, BinaryOp) and stmt.value.operator in ("==", "!=", "<", ">", "<=", ">=", "&&", "||"):
cond = self.generate_condition(stmt.value)
if self.in_function and target not in self.local_vars and target not in self.global_vars and '.' not in target and '[' not in target:
self.local_vars.add(target)
self.emit(f'local {target}')
self.emit(f'if {cond}; then {target}="true"; else {target}="false"; fi')
return
value = self.generate_expr(stmt.value)
if stmt.operator == "=":
self.emit_var_assign(target, value)
elif stmt.operator == "+=":
self.emit('{}=$((${{{}}} + {}))'.format(target, target, value))
elif stmt.operator == "-=":
self.emit('{}=$((${{{}}} - {}))'.format(target, target, value))
elif stmt.operator == "*=":
self.emit('{}=$((${{{}}} * {}))'.format(target, target, value))
elif stmt.operator == "/=":
self.emit('{}=$((${{{}}} / {}))'.format(target, target, value))
def _generate_this_field_assignment(self, stmt: Assignment):
"""Generate this.field = value assignment."""
field = stmt.target.member
value = self.generate_expr(stmt.value)
if stmt.operator == "=":
self.emit(f'__CT_OBJ["$this.{field}"]="{value}"')
elif stmt.operator == "+=":
self.emit(f'__CT_OBJ["$this.{field}"]="$(( ${{__CT_OBJ["$this.{field}"]}} + {value} ))"')
elif stmt.operator == "-=":
self.emit(f'__CT_OBJ["$this.{field}"]="$(( ${{__CT_OBJ["$this.{field}"]}} - {value} ))"')
elif stmt.operator == "*=":
self.emit(f'__CT_OBJ["$this.{field}"]="$(( ${{__CT_OBJ["$this.{field}"]}} * {value} ))"')
elif stmt.operator == "/=":
self.emit(f'__CT_OBJ["$this.{field}"]="$(( ${{__CT_OBJ["$this.{field}"]}} / {value} ))"')
elif stmt.operator == "..=":
self.emit(f'__CT_OBJ["$this.{field}"]="${{__CT_OBJ["$this.{field}"]}}{value}"')
else:
self.emit(f'__CT_OBJ["$this.{field}"]="{value}"')
def _generate_method_call_assignment(self, stmt: Assignment, target: str) -> bool:
"""Generate method call assignment. Returns True if handled."""
callee = stmt.value.callee
args = [self.generate_expr(arg) for arg in stmt.value.arguments]
if isinstance(callee.object, ThisExpr) and self.current_class:
method = callee.member
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_class_{self.current_class}_{method} "$this" {args_str} >/dev/null')
self.emit_var_assign(target, '$__CT_RET')
return True
if isinstance(callee.object, Identifier):
obj_name = callee.object.name
method = callee.member
if obj_name in BUILTIN_NAMESPACES:
return False
args_str = " ".join([f'"{a}"' for a in args])
if obj_name in self.array_vars and method in ARR_METHODS:
func_name = ARR_METHODS[method]
if method == "push" and len(args) == 1:
self.emit(f'{obj_name}+=("{args[0]}")')
else:
self.emit(f'{func_name} "{obj_name}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit_var_assign(target, '$__CT_RET')
return True
if obj_name in self.dict_vars and method in DICT_METHODS:
func_name = DICT_METHODS[method]
self.emit(f'{func_name} "{obj_name}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit_var_assign(target, '$__CT_RET')
return True
if method in STR_METHODS:
obj = self.generate_expr(callee.object)
func_name = STR_METHODS[method]
self.emit(f'{func_name} "{obj}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit_var_assign(target, '$__CT_RET')
return True
obj = self.generate_expr(callee.object)
self.emit(f'__ct_call_method "{obj}" "{method}" {args_str} >/dev/null')
self.emit_var_assign(target, '$__CT_RET')
return True
return False
def _generate_array_assignment(self, stmt: Assignment, target: str):
"""Generate array literal assignment."""
elements = [self.generate_expr(e) for e in stmt.value.elements]
arr_content = " ".join([f'"{e}"' for e in elements]) if elements else ""
if self.in_function and target not in self.local_vars and target not in self.global_vars:
self.local_vars.add(target)
if arr_content:
self.emit(f'local -a {target}=({arr_content})')
else:
self.emit(f'local -a {target}=()')
elif self.in_function and target in self.global_vars:
if arr_content:
self.emit(f'{target}=({arr_content})')
else:
self.emit(f'{target}=()')
else:
if arr_content:
self.emit(f'declare -ga {target}=({arr_content})')
else:
self.emit(f'declare -ga {target}=()')
self.array_vars.add(target)
def _generate_dict_assignment(self, stmt: Assignment, target: str):
"""Generate dict literal assignment."""
pairs = []
for k, v in stmt.value.pairs:
key = self.generate_expr(k)
val = self.generate_expr(v)
pairs.append(f'[{key}]="{val}"')
dict_content = " ".join(pairs) if pairs else ""
if self.in_function and target not in self.local_vars and target not in self.global_vars:
self.local_vars.add(target)
if dict_content:
self.emit(f'local -A {target}=({dict_content})')
else:
self.emit(f'local -A {target}=()')
else:
if dict_content:
self.emit(f'declare -gA {target}=({dict_content})')
else:
self.emit(f'declare -gA {target}=()')
self.dict_vars.add(target)
def _generate_pipe_assignment(self, stmt: Assignment, target: str):
"""Generate pipe expression assignment."""
elements = self._collect_pipe_chain(stmt.value)
if all(self._is_shell_exec(e) for e in elements):
commands = [self._extract_shell_command(e) for e in elements]
pipe_cmd = " | ".join(commands)
self.emit_var_assign(target, f'$({pipe_cmd})')
return
self._generate_functional_pipe_assignment(elements, target)
def _generate_functional_pipe_assignment(self, elements: list, target: str):
"""Generate functional pipe with proper variable handling."""
if not elements:
return
first = elements[0]
if isinstance(first, CallExpr):
if self._is_shell_exec(first):
cmd = self._extract_shell_command(first)
current_var = self.new_temp()
self.emit_var_assign(current_var, f'$({cmd})')
else:
call_code = self.generate_call_statement(first)
self.emit(f'{call_code} >/dev/null')
current_var = self.new_temp()
self.emit_var_assign(current_var, '$__CT_RET')
elif isinstance(first, Identifier):
current_var = first.name
else:
current_var = self.new_temp()
self.emit_var_assign(current_var, self.generate_expr(first))
for elem in elements[1:]:
if isinstance(elem, CallExpr):
if self._is_shell_exec(elem):
cmd = self._extract_shell_command(elem)
new_var = self.new_temp()
self.emit_var_assign(new_var, f'$(echo "${{{current_var}}}" | {cmd})')
current_var = new_var
else:
func_name = self._get_call_func_name(elem)
args = [self.generate_expr(a) for a in elem.arguments]
args_str = " ".join([f'"{a}"' for a in args])
if args_str:
self.emit(f'{func_name} "${{{current_var}}}" {args_str} >/dev/null')
else:
self.emit(f'{func_name} "${{{current_var}}}" >/dev/null')
new_var = self.new_temp()
self.emit_var_assign(new_var, '$__CT_RET')
current_var = new_var
elif isinstance(elem, Identifier):
self.emit(f'{elem.name} "${{{current_var}}}" >/dev/null')
new_var = self.new_temp()
self.emit_var_assign(new_var, '$__CT_RET')
current_var = new_var
self.emit_var_assign(target, f'${{{current_var}}}')
def _get_call_func_name(self, call_expr: CallExpr) -> str:
"""Get function name from call expression."""
if isinstance(call_expr.callee, Identifier):
return call_expr.callee.name
elif isinstance(call_expr.callee, MemberAccess):
if isinstance(call_expr.callee.object, Identifier):
return f'{call_expr.callee.object.name}.{call_expr.callee.member}'
return "unknown"
def generate_expression_stmt(self, stmt: ExpressionStmt):
expr = stmt.expression
if isinstance(expr, BaseCall):
if self.current_class:
parent_cls = self.classes.get(self.current_class)
if parent_cls and parent_cls.parent:
args = [self.generate_expr(a) for a in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_class_{parent_cls.parent}_construct "$this" {args_str}')
return
args = [self.generate_expr(a) for a in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'# base({args_str})')
return
if isinstance(expr, CallExpr):
if isinstance(expr.callee, MemberAccess):
if self._handle_field_method_call(expr):
return
if isinstance(expr.callee.object, Identifier):
if self._handle_var_method_call(expr):
return
call_code = self.generate_call_statement(expr)
if isinstance(expr.callee, MemberAccess):
obj = expr.callee.object
if isinstance(obj, Identifier):
if obj.name not in BUILTIN_NAMESPACES:
call_code = f'{call_code} >/dev/null'
elif isinstance(obj, ThisExpr):
call_code = f'{call_code} >/dev/null'
self.emit(call_code)
else:
result = self.generate_expr(expr)
if result:
self.emit(result)
def _handle_field_method_call(self, expr: CallExpr) -> bool:
"""Handle this.field.method() or var.field.method(). Returns True if handled."""
callee = expr.callee
args = [self.generate_expr(arg) for arg in expr.arguments]
if isinstance(callee.object, MemberAccess) and isinstance(callee.object.object, ThisExpr):
field_name = callee.object.member
method = callee.member
return self._emit_field_method(f"${{this}}_{field_name}", method, args)
if isinstance(callee.object, MemberAccess) and isinstance(callee.object.object, Identifier):
var_name = callee.object.object.name
field_name = callee.object.member
is_array_field = any(
self.class_field_types.get((cls, field_name)) == "array"
for cls in self.classes
)
is_dict_field = any(
self.class_field_types.get((cls, field_name)) == "dict"
for cls in self.classes
)
if is_array_field or is_dict_field:
return self._emit_field_method(f"${{{var_name}}}_{field_name}", expr.callee.member, args)
return False
def _emit_field_method(self, field_ref: str, method: str, args: list) -> bool:
"""Emit field method call."""
if method == "push":
self.emit(f'local -n __ct_tmp_arr="{field_ref}"')
for arg in args:
self.emit(f'__ct_tmp_arr+=("{arg}")')
return True
elif method == "pop":
self.emit(f'local -n __ct_tmp_arr="{field_ref}"')
self.emit("unset '__ct_tmp_arr[-1]'")
return True
elif method == "set" and len(args) >= 2:
self.emit(f'local -n __ct_tmp_arr="{field_ref}"')
self.emit(f'__ct_tmp_arr[{args[0]}]="{args[1]}"')
return True
elif method == "del" and len(args) >= 1:
self.emit(f'local -n __ct_tmp_arr="{field_ref}"')
self.emit(f"unset '__ct_tmp_arr[{args[0]}]'")
return True
elif method in ("len", "shift", "join", "get", "slice"):
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_arr_{method} "{field_ref}" {args_str} >/dev/null'.strip())
return True
elif method in ("has", "keys"):
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_dict_{method} "{field_ref}" {args_str} >/dev/null'.strip())
return True
return False
def _handle_var_method_call(self, expr: CallExpr) -> bool:
"""Handle var.method() calls. Returns True if handled."""
var_name = expr.callee.object.name
method = expr.callee.member
args = [self.generate_expr(arg) for arg in expr.arguments]
if var_name in self.array_vars:
if method == "push":
for arg in args:
self.emit(f'{var_name}+=("{arg}")')
return True
elif method == "pop":
self.emit(f"unset '{var_name}[-1]'")
return True
elif method == "set" and len(args) >= 2:
self.emit(f'{var_name}[{args[0]}]="{args[1]}"')
return True
elif method in ("len", "shift", "join", "get", "slice"):
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_arr_{method} "{var_name}" {args_str} >/dev/null'.strip())
return True
if var_name in self.dict_vars:
if method == "set" and len(args) >= 2:
self.emit(f'{var_name}[{args[0]}]="{args[1]}"')
return True
elif method == "del" and len(args) >= 1:
self.emit(f"unset '{var_name}[{args[0]}]'")
return True
elif method in ("get", "has", "keys"):
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_dict_{method} "{var_name}" {args_str} >/dev/null'.strip())
return True
return False
def generate_call_statement(self, expr: CallExpr) -> str:
callee = expr.callee
args = [self.generate_expr(arg) for arg in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
if isinstance(callee, Identifier):
return self._generate_builtin_call(callee.name, args, args_str)
if isinstance(callee, MemberAccess):
return self._generate_member_call(callee, args, args_str)
return ""
def _generate_builtin_call(self, name: str, args: list, args_str: str) -> str:
"""Generate builtin function call."""
if name == "print":
return f'__ct_print "{args[0]}"' if args else '__ct_print ""'
elif name == "range":
return f'__ct_range {args_str}'
elif name == "ngrep":
return f'__ct_ngrep {args_str}'
elif name == "exit":
return f'__ct_exit {args_str}'
elif name == "len":
return f'__ct_str_len {args_str}'
elif name == "is_number":
return f'__ct_is_number {args_str}'
elif name == "is_empty":
return f'__ct_is_empty {args_str}'
elif name == "chr":
return f'__ct_str_chr {args_str}'
elif name == "ord":
return f'__ct_str_ord {args_str}'
else:
return f'{name} {args_str}'
def _generate_member_call(self, callee: MemberAccess, args: list, args_str: str) -> str:
"""Generate member access call."""
obj = self.generate_expr(callee.object)
method = callee.member
if isinstance(callee.object, ThisExpr) and self.current_class:
key = (self.current_class, method)
if key in self.inlineable_methods and not args_str.strip():
return f'__CT_RET={self.inlineable_methods[key]}'
return f'__ct_class_{self.current_class}_{method} "$this" {args_str}'
if isinstance(callee.object, Identifier):
result = self._generate_stdlib_call(callee.object.name, method, args, args_str)
if result:
return result
if isinstance(callee.object, MemberAccess) and isinstance(callee.object.object, ThisExpr):
result = self._generate_this_field_call(callee, args_str)
if result:
return result
if isinstance(callee.object, MemberAccess) and isinstance(callee.object.object, Identifier):
result = self._generate_var_field_call(callee, args_str)
if result:
return result
var_name = callee.object.name if isinstance(callee.object, Identifier) else None
if var_name and var_name in self.array_vars and method in ARR_METHODS:
if method == "push" and len(args) == 1:
return f'{var_name}+=("{args[0]}")'
return f'{ARR_METHODS[method]} "{var_name}" {args_str}'.strip()
if var_name and var_name in self.dict_vars and method in DICT_METHODS:
return f'{DICT_METHODS[method]} "{var_name}" {args_str}'.strip()
if method in STR_METHODS:
return f'{STR_METHODS[method]} "{obj}" {args_str}'.strip()
return f'__ct_call_method "{obj}" "{method}" {args_str}'
def _generate_stdlib_call(self, obj_name: str, method: str, args: list, args_str: str) -> str:
"""Generate stdlib call. Returns None if not stdlib."""
if obj_name == "http":
return f'__ct_http_{method} {args_str}'
elif obj_name == "fs":
return f'__ct_fs_{method} {args_str}'
elif obj_name == "json":
return f'__ct_json_{method} {args_str}'
elif obj_name == "logger" and method in ("info", "warn", "error", "debug"):
return f'__ct_logger_{method} {args_str}'
elif obj_name == "regex":
return f'__ct_regex_{method} {args_str}'
elif obj_name == "args":
if method == "count":
return '__ct_args_count'
elif method == "get":
return f'__ct_args_get {args_str}'
elif obj_name == "shell":
if method == "exec":
return args[0] if args else ""
elif method == "capture":
return f'$({args[0]})' if args else ""
elif method == "source":
return f'source "{args[0]}"' if args else ""
return None
def _generate_this_field_call(self, callee: MemberAccess, args_str: str) -> str:
"""Generate this.field.method() call."""
field_name = callee.object.member
method = callee.member
if method in ARR_METHODS:
arr_name = f'"${{this}}_{field_name}"'
return f'{ARR_METHODS[method]} {arr_name} {args_str}'.strip()
if method in DICT_METHODS:
dict_ref = f'"${{__CT_OBJ[\\"$this.{field_name}\\"]}}"'
return f'{DICT_METHODS[method]} {dict_ref} {args_str}'.strip()
return None
def _generate_var_field_call(self, callee: MemberAccess, args_str: str) -> str:
"""Generate var.field.method() call."""
var_name = callee.object.object.name
field_name = callee.object.member
method = callee.member
is_array_field = any(
self.class_field_types.get((cls, field_name)) == "array"
for cls in self.classes
)
is_dict_field = any(
self.class_field_types.get((cls, field_name)) == "dict"
for cls in self.classes
)
if is_array_field and method in ARR_METHODS:
return f'{ARR_METHODS[method]} "${{{var_name}}}_{field_name}" {args_str}'.strip()
if is_dict_field and method in DICT_METHODS:
return f'{DICT_METHODS[method]} "${{{var_name}}}_{field_name}" {args_str}'.strip()
return None
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class CompileError:
message: str
filename: str
line: int
column: int
hint: Optional[str] = None
def __str__ (self):
result = f"Error: {self.message}\n --> {self.filename}:{self.line}:{self.column}"
if self.hint:
result += f"\n Hint: {self.hint}"
return result
class ErrorCollector:
def __init__ (self):
self.errors: List[CompileError] = []
def add (self, error: CompileError):
self.errors.append (error)
def add_error (self, message: str, filename: str, line: int, column: int, hint: str = None):
self.errors.append (CompileError (
message=message,
filename=filename,
line=line,
column=column,
hint=hint
))
def has_errors (self) -> bool:
return len (self.errors) > 0
def print_errors (self):
for error in self.errors:
print (str (error))
print ()
def clear (self):
self.errors = []
import re
from .ast_nodes import *
class ExprMixin:
"""Mixin for expression generation."""
def generate_expr(self, expr: Expression) -> str:
if isinstance(expr, IntegerLiteral):
return str(expr.value)
if isinstance(expr, FloatLiteral):
return str(expr.value)
if isinstance(expr, StringLiteral):
return self._generate_string_literal(expr)
if isinstance(expr, BoolLiteral):
return "true" if expr.value else "false"
if isinstance(expr, NilLiteral):
return ""
if isinstance(expr, Identifier):
return f"${{{expr.name}}}"
if isinstance(expr, ThisExpr):
return "$this"
if isinstance(expr, ArrayLiteral):
elements = [self.generate_expr(e) for e in expr.elements]
return "(" + " ".join([f'"{e}"' for e in elements]) + ")"
if isinstance(expr, DictLiteral):
pairs = []
for k, v in expr.pairs:
key = self.generate_expr(k)
val = self.generate_expr(v)
pairs.append(f'[{key}]="{val}"')
return "(" + " ".join(pairs) + ")"
if isinstance(expr, BinaryOp):
return self._generate_binary_op(expr)
if isinstance(expr, UnaryOp):
return self._generate_unary_op(expr)
if isinstance(expr, CallExpr):
return self._generate_call_expr(expr)
if isinstance(expr, MemberAccess):
return self._generate_member_access(expr)
if isinstance(expr, IndexAccess):
return self._generate_index_access(expr)
if isinstance(expr, Lambda):
return self.generate_lambda(expr)
if isinstance(expr, NewExpr):
args = [self.generate_expr(a) for a in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
return f'$({expr.class_name} {args_str}; echo "$__ct_last_instance")'
if isinstance(expr, BaseCall):
args = [self.generate_expr(a) for a in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
return f'# base({args_str})'
return ""
def _generate_string_literal(self, expr: StringLiteral) -> str:
"""Handle string interpolation."""
value = expr.value
value = value.replace('\\', '\\\\')
value = value.replace('"', '\\"')
value = value.replace('`', '\\`')
def escape_dollar(match):
pos = match.start()
rest = value[pos + 1:]
if not rest.startswith('{'):
return '\\$'
if rest.startswith('{{'):
return '\\$'
if rest.startswith('{__CT_') or rest.startswith('{['):
return '\\$'
brace_content = rest[1:]
close_pos = brace_content.find('}')
if close_pos == -1:
return '\\$'
return '$'
value = re.sub(r'\$', escape_dollar, value)
def replace_dollar_brace(match):
content = match.group(1)
if content.startswith('__CT_') or '[' in content:
return match.group(0)
if '.' in content:
parts = content.split('.', 1)
if parts[0] == 'this':
return f'\\$${{__CT_OBJ["$this.{parts[1]}"]}}'
else:
return f'\\$${{__CT_OBJ["${parts[0]}.{parts[1]}"]}}'
return f'\\$${{{content}}}'
def replace_interpolation(match):
content = match.group(1)
if '[' in content or content.startswith('__'):
return match.group(0)
if '(' in content:
return self._handle_interpolation_call(content)
if '.' in content:
parts = content.split('.', 1)
if parts[0] == 'this':
return f'${{__CT_OBJ["$this.{parts[1]}"]}}'
else:
return f'${{__CT_OBJ["${parts[0]}.{parts[1]}"]}}'
return f'${{{content}}}'
value = value.replace('\x00DOLLAR\x00{', '\x01ESCAPED_DOLLAR_BRACE\x01')
value = value.replace('\x00DOLLAR\x00', '\\$')
value = value.replace('\x00LBRACE\x00', '\x01ESCAPED_LBRACE\x01')
value = value.replace('\x00RBRACE\x00', '\x01ESCAPED_RBRACE\x01')
value = re.sub(r'\$\{(?!\{)([^}]+)\}', replace_dollar_brace, value)
value = re.sub(r'(?<!\$)\{([^}\[]+)\}', replace_interpolation, value)
value = value.replace('\x01ESCAPED_DOLLAR_BRACE\x01', '\\${')
value = value.replace('\x01ESCAPED_LBRACE\x01', '{')
value = value.replace('\x01ESCAPED_RBRACE\x01', '}')
return value
def _handle_interpolation_call(self, content: str) -> str:
"""Handle function/method calls in string interpolation."""
if '.' in content and not content.startswith('('):
dot_idx = content.find('.')
paren_idx = content.find('(')
if dot_idx < paren_idx:
parts = content.split('.', 1)
obj = parts[0]
rest = parts[1]
method_paren_idx = rest.find('(')
method = rest[:method_paren_idx].strip()
args_csv = rest[method_paren_idx + 1:-1]
args_list = self._parse_args_with_parens(args_csv) if args_csv else []
args_bash = ' '.join([self._convert_arg_to_bash(a) for a in args_list])
if obj == 'str':
return f'$(__ct_str_{method} {args_bash})'
elif obj == 'arr':
return f'$(__ct_arr_{method} {args_bash})'
elif obj == 'args':
if method == 'count':
return '$(__ct_args_count)'
elif method == 'get':
return f'$(__ct_args_get {args_bash})'
return f'$(__ct_call_method "${{{obj}}}" "{method}" {args_bash})'
paren_idx = content.find('(')
func_name = content[:paren_idx].strip()
args_part = content[paren_idx + 1:-1].strip()
if args_part:
args_list = self._parse_args_with_parens(args_part)
args_bash = ' '.join([self._convert_arg_to_bash(a) for a in args_list])
return f'$({func_name} {args_bash})'
else:
return f'$({func_name})'
def _parse_args_with_parens(self, args_str: str) -> list:
"""Parse comma-separated args, respecting nested parentheses."""
args = []
current = ""
depth = 0
for ch in args_str:
if ch == '(':
depth += 1
current += ch
elif ch == ')':
depth -= 1
current += ch
elif ch == ',' and depth == 0:
args.append(current.strip())
current = ""
else:
current += ch
if current.strip():
args.append(current.strip())
return args
def _convert_arg_to_bash(self, arg: str) -> str:
"""Convert a single argument to bash syntax."""
arg = arg.strip()
if not arg:
return '""'
if '(' in arg and arg.endswith(')'):
paren_idx = arg.find('(')
func_name = arg[:paren_idx].strip()
inner_args = arg[paren_idx + 1:-1].strip()
if inner_args:
inner_list = self._parse_args_with_parens(inner_args)
inner_bash = ' '.join([self._convert_arg_to_bash(a) for a in inner_list])
return f'$({func_name} {inner_bash})'
else:
return f'$({func_name})'
if arg.isdigit() or (arg.startswith('-') and arg[1:].isdigit()):
return f'"{arg}"'
if arg.startswith('"') and arg.endswith('"'):
return arg
return f'"${{{arg}}}"'
def _generate_binary_op(self, expr: BinaryOp) -> str:
left = self.generate_expr(expr.left)
right = self.generate_expr(expr.right)
op = expr.operator
if op == "+":
return f"$(({left} + {right}))"
elif op == "..":
return f"{left}{right}"
elif op in ("-", "*", "/", "%"):
return f"$(({left} {op} {right}))"
elif op == "==":
return f'[[ "{left}" == "{right}" ]]'
elif op == "!=":
return f'[[ "{left}" != "{right}" ]]'
elif op == "<":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" < "{right}" ]]'
return f'[[ {left} -lt {right} ]]'
elif op == ">":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" > "{right}" ]]'
return f'[[ {left} -gt {right} ]]'
elif op == "<=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" > "{right}" ]]'
return f'[[ {left} -le {right} ]]'
elif op == ">=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" < "{right}" ]]'
return f'[[ {left} -ge {right} ]]'
elif op == "&&":
return f'{left} && {right}'
elif op == "||":
return f'{left} || {right}'
elif op == "|":
return self._generate_pipe_expr(expr)
return f"$(({left} {op} {right}))"
def _generate_unary_op(self, expr: UnaryOp) -> str:
operand = self.generate_expr(expr.operand)
if expr.operator == "!":
return f'! {operand}'
elif expr.operator == "-":
return f'$((-{operand}))'
return operand
def _generate_call_expr(self, expr: CallExpr) -> str:
if isinstance(expr.callee, Identifier) and expr.callee.name == "len":
if len(expr.arguments) == 1:
arg = expr.arguments[0]
if isinstance(arg, MemberAccess) and isinstance(arg.object, ThisExpr):
return f'${{#__CT_OBJ["$this.{arg.member}"]}}'
if isinstance(expr.callee, MemberAccess):
if isinstance(expr.callee.object, Identifier) and expr.callee.object.name == "str":
result = self._inline_str_method(expr)
if result:
return result
if isinstance(expr.callee.object, Identifier) and expr.callee.object.name == "arr":
result = self._inline_arr_method(expr)
if result:
return result
if isinstance(expr.callee.object, ThisExpr) and self.current_class:
method = expr.callee.member
key = (self.current_class, method)
if key in self.inlineable_methods and len(expr.arguments) == 0:
return self.inlineable_methods[key]
if isinstance(expr.callee.object, Identifier) and expr.callee.object.name == "shell":
if expr.callee.member == "capture":
return self.generate_call_statement(expr)
return f"$({self.generate_call_statement(expr)})"
def _inline_str_method(self, expr: CallExpr) -> str:
"""Inline common str methods."""
method = expr.callee.member
if method == "len" and len(expr.arguments) == 1:
arg = expr.arguments[0]
if isinstance(arg, MemberAccess) and isinstance(arg.object, ThisExpr):
return f'${{#__CT_OBJ["$this.{arg.member}"]}}'
if isinstance(arg, Identifier):
return f'${{#{arg.name}}}'
if method == "charAt" and len(expr.arguments) == 2:
arg0, arg1 = expr.arguments
if isinstance(arg0, MemberAccess) and isinstance(arg0.object, ThisExpr):
pos = self.generate_expr(arg1)
return f'${{__CT_OBJ["$this.{arg0.member}"]:{pos}:1}}'
str_val = self.generate_expr(arg0)
if str_val.startswith('${') and str_val.endswith('}'):
str_val = str_val[2:-1]
elif str_val.startswith('$') and not str_val.startswith('$('):
str_val = str_val[1:]
pos = self.generate_expr(arg1)
return f'${{{str_val}:{pos}:1}}'
return None
def _inline_arr_method(self, expr: CallExpr) -> str:
"""Inline common arr methods."""
method = expr.callee.member
if method == "get" and len(expr.arguments) == 2:
arr_arg = expr.arguments[0]
idx_arg = expr.arguments[1]
if isinstance(arr_arg, Identifier):
arr_name = arr_arg.name
idx = self.generate_expr(idx_arg)
return f'${{{arr_name}[{idx}]}}'
if method == "len" and len(expr.arguments) == 1:
arr_arg = expr.arguments[0]
if isinstance(arr_arg, Identifier):
return f'${{#{arr_arg.name}[@]}}'
return None
def _generate_member_access(self, expr: MemberAccess) -> str:
if isinstance(expr.object, ThisExpr):
return f'${{__CT_OBJ["$this.{expr.member}"]}}'
obj = self.generate_expr(expr.object)
if obj.startswith('${') and obj.endswith('}'):
obj = '$' + obj[2:-1]
return f'${{__CT_OBJ["{obj}.{expr.member}"]}}'
def _generate_index_access(self, expr: IndexAccess) -> str:
obj = self.generate_expr(expr.object)
idx = self.generate_expr(expr.index)
if obj.startswith('${') and obj.endswith('}'):
obj = obj[2:-1]
elif obj.startswith('$'):
obj = obj[1:]
return f'${{{obj}[{idx}]}}'
def is_string_comparison(self, left_expr: Expression, right_expr: Expression) -> bool:
"""Check if this is a string comparison (vs numeric)."""
if isinstance(left_expr, StringLiteral) and len(left_expr.value) == 1:
return True
if isinstance(right_expr, StringLiteral) and len(right_expr.value) == 1:
return True
if isinstance(left_expr, StringLiteral):
try:
float(left_expr.value)
except ValueError:
return True
if isinstance(right_expr, StringLiteral):
try:
float(right_expr.value)
except ValueError:
return True
return False
def generate_condition(self, expr: Expression) -> str:
if isinstance(expr, BinaryOp):
return self._generate_binary_condition(expr)
if isinstance(expr, UnaryOp) and expr.operator == "!":
inner = self.generate_condition(expr.operand)
return f'! {inner}'
if isinstance(expr, Identifier):
return f'[[ "${expr.name}" == "true" ]]'
if isinstance(expr, BoolLiteral):
return "true" if expr.value else "false"
if isinstance(expr, CallExpr):
return self._generate_call_condition(expr)
result = self.generate_expr(expr)
return f'[[ -n "{result}" ]]'
def _generate_binary_condition(self, expr: BinaryOp) -> str:
left = self.generate_expr(expr.left)
right = self.generate_expr(expr.right)
op = expr.operator
if op == "==":
return f'[[ "{left}" == "{right}" ]]'
elif op == "!=":
return f'[[ "{left}" != "{right}" ]]'
elif op == "<":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" < "{right}" ]]'
return f'[[ {left} -lt {right} ]]'
elif op == ">":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ "{left}" > "{right}" ]]'
return f'[[ {left} -gt {right} ]]'
elif op == "<=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" > "{right}" ]]'
return f'[[ {left} -le {right} ]]'
elif op == ">=":
if self.is_string_comparison(expr.left, expr.right):
return f'[[ ! "{left}" < "{right}" ]]'
return f'[[ {left} -ge {right} ]]'
elif op == "&&":
l = self.generate_condition(expr.left)
r = self.generate_condition(expr.right)
return f'{{ {l} && {r}; }}'
elif op == "||":
l = self.generate_condition(expr.left)
r = self.generate_condition(expr.right)
return f'{{ {l} || {r}; }}'
return f'[[ "{left}" == "{right}" ]]'
def _generate_call_condition(self, expr: CallExpr) -> str:
"""Generate condition for function calls."""
if isinstance(expr.callee, MemberAccess):
if isinstance(expr.callee.object, Identifier):
obj_name = expr.callee.object.name
method = expr.callee.member
if obj_name == "str":
if method == "contains" and len(expr.arguments) == 2:
haystack = self.generate_expr(expr.arguments[0])
needle = self.generate_expr(expr.arguments[1])
return f'[[ "{haystack}" == *"{needle}"* ]]'
elif method == "starts" and len(expr.arguments) == 2:
s = self.generate_expr(expr.arguments[0])
prefix = self.generate_expr(expr.arguments[1])
return f'[[ "{s}" == "{prefix}"* ]]'
elif method == "ends" and len(expr.arguments) == 2:
s = self.generate_expr(expr.arguments[0])
suffix = self.generate_expr(expr.arguments[1])
return f'[[ "{s}" == *"{suffix}" ]]'
if obj_name == "fs" and method == "exists" and len(expr.arguments) == 1:
path = self.generate_expr(expr.arguments[0])
return f'[[ -e "{path}" ]]'
if obj_name == "regex" and method == "match" and len(expr.arguments) == 2:
s = self.generate_expr(expr.arguments[0])
pattern = self.generate_expr(expr.arguments[1])
return f'[[ "{s}" =~ {pattern} ]]'
if isinstance(expr.callee, Identifier):
if expr.callee.name == "is_number" and len(expr.arguments) == 1:
val = self.generate_expr(expr.arguments[0])
return f'[[ "{val}" =~ ^-?[0-9]+$ ]]'
elif expr.callee.name == "is_empty" and len(expr.arguments) == 1:
val = self.generate_expr(expr.arguments[0])
return f'[[ -z "{val}" ]]'
result = self.generate_expr(expr)
return f'[[ "{result}" == "true" ]]'
def generate_lambda(self, expr: Lambda) -> str:
"""Generate lambda and return its name."""
name = self.new_lambda_name()
self.generate_lambda_as_function(expr, name)
return name
def generate_lambda_as_function(self, expr: Lambda, name: str):
"""Generate lambda as a named function."""
self.emit(f"{name} () {{")
self.indent_level += 1
for i, param in enumerate(expr.params):
self.emit(f'local {param}="${{{i + 1}}}"')
if isinstance(expr.body, Block):
for stmt in expr.body.statements:
self.generate_statement(stmt)
else:
result = self.generate_expr(expr.body)
self.emit(f'echo "{result}"')
self.indent_level -= 1
self.emit("}")
self.emit()
def generate_lvalue(self, expr: Expression) -> str:
"""Generate left-hand side of assignment (without $ prefix)."""
if isinstance(expr, Identifier):
return expr.name
elif isinstance(expr, MemberAccess):
if isinstance(expr.object, ThisExpr):
return f'"${{this}}_{expr.member}"'
obj = self.generate_lvalue(expr.object)
return f'{obj}_{expr.member}'
elif isinstance(expr, IndexAccess):
obj = self.generate_lvalue(expr.object)
idx = self.generate_expr(expr.index)
return f'{obj}[{idx}]'
return self.generate_expr(expr)
def _generate_pipe_expr(self, expr: BinaryOp) -> str:
"""Generate pipe expression as inline expression."""
elements = self._collect_pipe_chain(expr)
if all(self._is_shell_exec(e) for e in elements):
commands = [self._extract_shell_command(e) for e in elements]
return f'$({" | ".join(commands)})'
return self._generate_functional_pipe_inline(elements)
def _collect_pipe_chain(self, expr: Expression) -> list:
"""Collect all elements in a pipe chain from left to right."""
if isinstance(expr, BinaryOp) and expr.operator == "|":
return self._collect_pipe_chain(expr.left) + self._collect_pipe_chain(expr.right)
return [expr]
def _is_shell_exec(self, expr: Expression) -> bool:
"""Check if expression is shell.exec() or shell.capture()."""
if isinstance(expr, CallExpr) and isinstance(expr.callee, MemberAccess):
if isinstance(expr.callee.object, Identifier):
return (expr.callee.object.name == "shell" and
expr.callee.member in ("exec", "capture"))
return False
def _extract_shell_command(self, expr: Expression) -> str:
"""Extract shell command string from shell.exec()/shell.capture() call."""
if isinstance(expr, CallExpr) and expr.arguments:
arg = expr.arguments[0]
if isinstance(arg, StringLiteral):
return arg.value
return self.generate_expr(arg)
return ""
def _generate_functional_pipe_inline(self, elements: list) -> str:
"""Generate functional pipe as nested function calls."""
if len(elements) == 0:
return ""
if len(elements) == 1:
return self.generate_expr(elements[0])
result = self.generate_expr(elements[0])
for elem in elements[1:]:
if isinstance(elem, CallExpr):
result = self._wrap_pipe_call(elem, result)
elif isinstance(elem, Identifier):
result = f'$({elem.name} "{result}")'
else:
func = self.generate_expr(elem)
result = f'$({func} "{result}")'
return result
def _wrap_pipe_call(self, call_expr: CallExpr, prev_result: str) -> str:
"""Wrap a function call to receive piped result as first argument."""
if isinstance(call_expr.callee, Identifier):
func_name = call_expr.callee.name
args = [self.generate_expr(a) for a in call_expr.arguments]
all_args = [f'"{prev_result}"'] + [f'"{a}"' for a in args]
return f'$({func_name} {" ".join(all_args)})'
elif isinstance(call_expr.callee, MemberAccess):
call_code = self.generate_call_statement(call_expr)
if self._is_shell_exec(call_expr):
cmd = self._extract_shell_command(call_expr)
return f'$(echo "{prev_result}" | {cmd})'
return f'$({call_code} "{prev_result}")'
return prev_result
from typing import List, Optional
from .tokens import Token, TokenType, KEYWORDS
from .errors import CompileError
class Lexer:
def __init__ (self, source: str, filename: str = "<stdin>"):
self.source = source
self.filename = filename
self.pos = 0
self.line = 1
self.column = 1
self.tokens: List[Token] = []
self.errors: List[CompileError] = []
def current (self) -> Optional[str]:
if self.pos >= len (self.source):
return None
return self.source[self.pos]
def peek (self, offset: int = 1) -> Optional[str]:
pos = self.pos + offset
if pos >= len (self.source):
return None
return self.source[pos]
def advance (self) -> Optional[str]:
ch = self.current ()
if ch is None:
return None
self.pos += 1
if ch == '\n':
self.line += 1
self.column = 1
else:
self.column += 1
return ch
def skip_whitespace (self):
while self.current () in (' ', '\t', '\r'):
self.advance ()
def add_token (self, type: TokenType, value=None, line=None, column=None):
self.tokens.append (Token (
type=type,
value=value,
line=line or self.line,
column=column or self.column
))
def error (self, message: str):
self.errors.append (CompileError (
message=message,
filename=self.filename,
line=self.line,
column=self.column
))
def read_string (self) -> str:
start_line = self.line
start_col = self.column
quote = self.advance ()
result = []
while True:
ch = self.current ()
if ch is None:
self.error ("Unterminated string")
break
if ch == quote:
self.advance ()
break
if ch == '\\':
self.advance ()
escaped = self.current ()
if escaped is None:
self.error ("Unterminated escape sequence")
break
escape_map = {
'n': '\n',
't': '\t',
'r': '\r',
'\\': '\\',
'{': '\x00LBRACE\x00',
'}': '\x00RBRACE\x00',
'$': '\x00DOLLAR\x00',
'"': '"',
"'": "'",
}
result.append (escape_map.get (escaped, escaped))
self.advance ()
else:
result.append (ch)
self.advance ()
return ''.join (result)
def read_number (self) -> Token:
start_col = self.column
result = []
is_float = False
while True:
ch = self.current ()
if ch is None:
break
if ch.isdigit ():
result.append (ch)
self.advance ()
elif ch == '.' and not is_float:
if self.peek () and self.peek ().isdigit ():
is_float = True
result.append (ch)
self.advance ()
else:
break
else:
break
value = ''.join (result)
if is_float:
return Token (TokenType.FLOAT, float (value), self.line, start_col)
return Token (TokenType.INTEGER, int (value), self.line, start_col)
def read_identifier (self) -> str:
result = []
while True:
ch = self.current ()
if ch is None:
break
if ch.isalnum () or ch == '_':
result.append (ch)
self.advance ()
else:
break
return ''.join (result)
def tokenize (self) -> List[Token]:
while True:
self.skip_whitespace ()
ch = self.current ()
if ch is None:
self.add_token (TokenType.EOF)
break
start_line = self.line
start_col = self.column
if ch == '#':
while self.current () and self.current () != '\n':
self.advance ()
continue
if ch == '\n':
self.add_token (TokenType.NEWLINE, line=start_line, column=start_col)
self.advance ()
continue
if ch in ('"', "'"):
value = self.read_string ()
self.add_token (TokenType.STRING, value, start_line, start_col)
continue
if ch.isdigit ():
token = self.read_number ()
self.tokens.append (token)
continue
if ch.isalpha () or ch == '_':
value = self.read_identifier ()
token_type = KEYWORDS.get (value, TokenType.IDENTIFIER)
self.add_token (token_type, value, start_line, start_col)
continue
if ch == '=' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.EQ, '==', start_line, start_col)
continue
if ch == '!' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.NEQ, '!=', start_line, start_col)
continue
if ch == '<' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.LTE, '<=', start_line, start_col)
continue
if ch == '>' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.GTE, '>=', start_line, start_col)
continue
if ch == '&' and self.peek () == '&':
self.advance ()
self.advance ()
self.add_token (TokenType.AND, '&&', start_line, start_col)
continue
if ch == '|' and self.peek () == '|':
self.advance ()
self.advance ()
self.add_token (TokenType.OR, '||', start_line, start_col)
continue
if ch == '=' and self.peek () == '>':
self.advance ()
self.advance ()
self.add_token (TokenType.ARROW, '=>', start_line, start_col)
continue
if ch == '+' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.PLUS_ASSIGN, '+=', start_line, start_col)
continue
if ch == '-' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.MINUS_ASSIGN, '-=', start_line, start_col)
continue
if ch == '*' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.STAR_ASSIGN, '*=', start_line, start_col)
continue
if ch == '/' and self.peek () == '=':
self.advance ()
self.advance ()
self.add_token (TokenType.SLASH_ASSIGN, '/=', start_line, start_col)
continue
if ch == '.' and self.peek () == '.' and self.peek (2) == '.':
self.advance ()
self.advance ()
self.advance ()
self.add_token (TokenType.DOTDOTDOT, '...', start_line, start_col)
continue
if ch == '.' and self.peek () == '.':
self.advance ()
self.advance ()
self.add_token (TokenType.DOTDOT, '..', start_line, start_col)
continue
single_char_tokens = {
'+': TokenType.PLUS,
'-': TokenType.MINUS,
'*': TokenType.STAR,
'/': TokenType.SLASH,
'%': TokenType.PERCENT,
'=': TokenType.ASSIGN,
'<': TokenType.LT,
'>': TokenType.GT,
'!': TokenType.NOT,
'.': TokenType.DOT,
':': TokenType.COLON,
'(': TokenType.LPAREN,
')': TokenType.RPAREN,
'{': TokenType.LBRACE,
'}': TokenType.RBRACE,
'[': TokenType.LBRACKET,
']': TokenType.RBRACKET,
',': TokenType.COMMA,
'@': TokenType.AT,
'|': TokenType.PIPE,
}
if ch in single_char_tokens:
self.advance ()
self.add_token (single_char_tokens[ch], ch, start_line, start_col)
continue
if ch == ';':
self.advance ()
continue
self.error (f"Unexpected character: '{ch}'")
self.advance ()
return self.tokens
import sys
import os
import argparse
import tempfile
import subprocess
from pathlib import Path
from .lexer import Lexer
from .parser import Parser
from .codegen import CodeGenerator
def parse_file (source_path: str):
"""Parse a .ct file and return AST or None on error."""
try:
with open (source_path, "r", encoding="utf-8") as f:
source = f.read ()
except FileNotFoundError:
print (f"Error: File not found: {source_path}", file=sys.stderr)
return None
except Exception as e:
print (f"Error reading file: {e}", file=sys.stderr)
return None
filename = os.path.basename (source_path)
lexer = Lexer (source, filename)
tokens = lexer.tokenize ()
if lexer.errors:
for error in lexer.errors:
print (str (error), file=sys.stderr)
return None
parser = Parser (tokens, filename)
ast = parser.parse ()
if parser.errors.has_errors ():
parser.errors.print_errors ()
return None
return ast
def compile_file (source_path: str, output_path: str = None) -> tuple[bool, str]:
"""Compile a single .ct file to bash."""
return compile_files ([source_path])
def compile_files (source_paths: list) -> tuple[bool, str]:
"""Compile multiple .ct files to bash (Vala-style multi-file)."""
asts = []
for source_path in source_paths:
ast = parse_file (source_path)
if ast is None:
return False, ""
asts.append (ast)
codegen = CodeGenerator ()
output = codegen.generate_multi (asts)
if codegen.errors.has_errors ():
codegen.errors.print_errors ()
return False, ""
return True, output
def find_ct_files (directory: str = ".") -> list:
"""Find all .ct files in directory, sorted (main.ct last for proper ordering)."""
import glob
files = sorted (glob.glob (os.path.join (directory, "*.ct")))
main_files = [f for f in files if os.path.basename (f) == "main.ct"]
other_files = [f for f in files if os.path.basename (f) != "main.ct"]
return other_files + main_files
def cmd_build (args):
"""Build command - compile .ct to .sh (supports multiple files)"""
source_paths = args.sources
if source_paths == ["."]:
source_paths = find_ct_files (".")
if not source_paths:
print ("Error: No .ct files found in current directory", file=sys.stderr)
return 1
for source_path in source_paths:
if not source_path.endswith (".ct"):
print (f"Error: Source file must have .ct extension: {source_path}", file=sys.stderr)
return 1
if args.output:
output_path = args.output
else:
output_path = source_paths[0].replace (".ct", ".sh")
success, output = compile_files (source_paths)
if not success:
return 1
try:
with open (output_path, "w", encoding="utf-8") as f:
f.write (output)
os.chmod (output_path, 0o755)
if len (source_paths) == 1:
print (f"Compiled: {source_paths[0]} -> {output_path}")
else:
print (f"Compiled: {', '.join (source_paths)} -> {output_path}")
except Exception as e:
print (f"Error writing output: {e}", file=sys.stderr)
return 1
if args.lint:
print ("Running ShellCheck...")
result = subprocess.run (
["shellcheck", output_path],
capture_output=True,
text=True
)
if result.returncode != 0:
print (result.stdout)
print (result.stderr, file=sys.stderr)
else:
print ("ShellCheck: OK")
return 0
def cmd_run (args):
"""Run command - compile and execute (supports multiple files)"""
all_args = args.sources_and_args
if "--" in all_args:
sep_idx = all_args.index ("--")
source_paths = all_args[:sep_idx]
script_args = all_args[sep_idx + 1:]
else:
source_paths = all_args
script_args = []
if source_paths == ["."]:
source_paths = find_ct_files (".")
if not source_paths:
print ("Error: No .ct files found in current directory", file=sys.stderr)
return 1
for source_path in source_paths:
if not source_path.endswith (".ct"):
print (f"Error: Source file must have .ct extension: {source_path}", file=sys.stderr)
return 1
success, output = compile_files (source_paths)
if not success:
return 1
try:
with tempfile.NamedTemporaryFile (
mode="w",
suffix=".sh",
delete=False,
encoding="utf-8"
) as f:
f.write (output)
temp_path = f.name
os.chmod (temp_path, 0o755)
try:
result = subprocess.run (
["bash", temp_path] + script_args,
check=False
)
return result.returncode
finally:
try:
os.unlink (temp_path)
except:
pass
except Exception as e:
print (f"Error: {e}", file=sys.stderr)
return 1
def cmd_build_lib (args):
"""Build library command"""
source_path = args.source
if not source_path.endswith (".ct"):
print (f"Error: Source file must have .ct extension", file=sys.stderr)
return 1
output_path = source_path.replace (".ct", ".sh")
success, output = compile_file (source_path)
if not success:
return 1
lib_name = Path (source_path).stem
metadata = f'''
'''
footer = '''
'''
output = metadata + output + footer
try:
with open (output_path, "w", encoding="utf-8") as f:
f.write (output)
os.chmod (output_path, 0o644)
print (f"Library built: {source_path} -> {output_path}")
except Exception as e:
print (f"Error writing output: {e}", file=sys.stderr)
return 1
return 0
def main ():
parser = argparse.ArgumentParser (
prog="content",
description="ContenT Compiler - Compile ContenT to Bash"
)
parser.add_argument (
"--version", "-v",
action="version",
version="ContenT 0.1.0 (bootstrap)"
)
subparsers = parser.add_subparsers (dest="command", help="Commands")
build_parser = subparsers.add_parser ("build", help="Compile .ct to .sh")
build_parser.add_argument ("sources", nargs="+", help="Source files (.ct)")
build_parser.add_argument ("-o", "--output", help="Output file (.sh)")
build_parser.add_argument ("--lint", action="store_true", help="Run ShellCheck")
run_parser = subparsers.add_parser ("run", help="Compile and run (use -- to separate script args)")
run_parser.add_argument ("sources_and_args", nargs="+", help="Source files (.ct) [-- script args]")
lib_parser = subparsers.add_parser ("build-lib", help="Build a library")
lib_parser.add_argument ("source", help="Source file (.ct)")
parser.add_argument ("--build-lib", metavar="FILE", help="Build a library")
args = parser.parse_args ()
if args.build_lib:
class LibArgs:
source = args.build_lib
return cmd_build_lib (LibArgs ())
if args.command == "build":
return cmd_build (args)
elif args.command == "run":
return cmd_run (args)
elif args.command == "build-lib":
return cmd_build_lib (args)
else:
parser.print_help ()
return 0
if __name__ == "__main__":
sys.exit (main ())
from typing import List, Optional, Callable
from .tokens import Token, TokenType
from .ast_nodes import *
from .errors import CompileError, ErrorCollector
class Parser:
def __init__ (self, tokens: List[Token], filename: str = "<stdin>"):
self.tokens = tokens
self.filename = filename
self.pos = 0
self.errors = ErrorCollector ()
def current (self) -> Token:
if self.pos >= len (self.tokens):
return self.tokens[-1]
return self.tokens[self.pos]
def peek (self, offset: int = 1) -> Token:
pos = self.pos + offset
if pos >= len (self.tokens):
return self.tokens[-1]
return self.tokens[pos]
def check (self, *types: TokenType) -> bool:
return self.current ().type in types
def match (self, *types: TokenType) -> bool:
if self.check (*types):
self.advance ()
return True
return False
def advance (self) -> Token:
token = self.current ()
if token.type != TokenType.EOF:
self.pos += 1
return token
def expect (self, type: TokenType, message: str = None) -> Token:
if self.check (type):
return self.advance ()
msg = message or f"Expected {type.name}, got {self.current ().type.name}"
self.error (msg)
return self.current ()
def error (self, message: str, token: Token = None):
token = token or self.current ()
self.errors.add_error (
message=message,
filename=self.filename,
line=token.line,
column=token.column
)
def location (self, token: Token = None) -> SourceLocation:
token = token or self.current ()
return SourceLocation (token.line, token.column, self.filename)
def skip_newlines (self):
while self.match (TokenType.NEWLINE):
pass
def parse (self) -> Program:
statements = []
self.skip_newlines ()
while not self.check (TokenType.EOF):
stmt = self.parse_declaration ()
if stmt:
statements.append (stmt)
self.skip_newlines ()
return Program (statements=statements, location=SourceLocation (1, 1, self.filename))
def parse_declaration (self) -> Optional[Union[Declaration, Statement]]:
decorators = []
while self.check (TokenType.AT):
decorators.append (self.parse_decorator ())
self.skip_newlines ()
if self.check (TokenType.FUNC):
return self.parse_function (decorators)
if self.check (TokenType.CLASS):
return self.parse_class ()
if self.check (TokenType.IMPORT):
return self.parse_import ()
if decorators:
self.error ("Decorators can only be applied to functions or methods")
return self.parse_statement ()
def parse_decorator (self) -> Decorator:
loc = self.location ()
self.expect (TokenType.AT)
name = self.expect (TokenType.IDENTIFIER, "Expected decorator name").value
arguments = []
if self.match (TokenType.LPAREN):
if not self.check (TokenType.RPAREN):
arguments = self.parse_decorator_args ()
self.expect (TokenType.RPAREN, "Expected ')' after decorator arguments")
return Decorator (name=name, arguments=arguments, location=loc)
def parse_decorator_args (self) -> List[tuple]:
args = []
while True:
if self.check (TokenType.IDENTIFIER) and self.peek ().type == TokenType.ASSIGN:
name = self.advance ().value
self.advance ()
value = self.parse_expression ()
args.append ((name, value))
else:
value = self.parse_expression ()
args.append ((None, value))
if not self.match (TokenType.COMMA):
break
return args
def parse_function (self, decorators: List[Decorator] = None) -> FunctionDecl:
loc = self.location ()
self.expect (TokenType.FUNC)
name = self.expect (TokenType.IDENTIFIER, "Expected function name").value
self.expect (TokenType.LPAREN, "Expected '(' after function name")
params = self.parse_parameters ()
self.expect (TokenType.RPAREN, "Expected ')' after parameters")
self.skip_newlines ()
body = self.parse_block ()
return FunctionDecl (
name=name,
params=params,
body=body,
decorators=decorators or [],
location=loc
)
def parse_parameters (self) -> List[Parameter]:
params = []
if self.check (TokenType.RPAREN):
return params
while True:
name = self.expect (TokenType.IDENTIFIER, "Expected parameter name").value
is_variadic = False
default = None
if self.match (TokenType.DOTDOTDOT):
is_variadic = True
elif self.match (TokenType.ASSIGN):
default = self.parse_expression ()
params.append (Parameter (name=name, default=default, is_variadic=is_variadic))
if not self.match (TokenType.COMMA):
break
return params
def parse_class (self) -> ClassDecl:
loc = self.location ()
self.expect (TokenType.CLASS)
name = self.expect (TokenType.IDENTIFIER, "Expected class name").value
parent = None
if self.match (TokenType.COLON):
parent = self.expect (TokenType.IDENTIFIER, "Expected parent class name").value
self.skip_newlines ()
self.expect (TokenType.LBRACE, "Expected '{' after class declaration")
self.skip_newlines ()
fields = []
constructor = None
methods = []
while not self.check (TokenType.RBRACE) and not self.check (TokenType.EOF):
decorators = []
while self.check (TokenType.AT):
decorators.append (self.parse_decorator ())
self.skip_newlines ()
if self.check (TokenType.CONSTRUCT):
constructor = self.parse_constructor ()
elif self.check (TokenType.FUNC):
methods.append (self.parse_function (decorators))
elif self.check (TokenType.IDENTIFIER):
field_name = self.advance ().value
default_value = None
if self.match (TokenType.ASSIGN):
default_value = self.parse_expression ()
fields.append ((field_name, default_value))
else:
self.error (f"Unexpected token in class body: {self.current ().type.name}")
self.advance ()
self.skip_newlines ()
self.expect (TokenType.RBRACE, "Expected '}' after class body")
return ClassDecl (
name=name,
parent=parent,
fields=fields,
constructor=constructor,
methods=methods,
location=loc
)
def parse_constructor (self) -> ConstructorDecl:
loc = self.location ()
self.expect (TokenType.CONSTRUCT)
self.expect (TokenType.LPAREN, "Expected '(' after 'construct'")
params = self.parse_parameters ()
self.expect (TokenType.RPAREN, "Expected ')' after parameters")
self.skip_newlines ()
body = self.parse_block ()
return ConstructorDecl (params=params, body=body, location=loc)
def parse_import (self) -> ImportStmt:
loc = self.location ()
self.expect (TokenType.IMPORT)
path = self.expect (TokenType.STRING, "Expected import path").value
return ImportStmt (path=path, location=loc)
def parse_statement (self) -> Optional[Statement]:
if self.check (TokenType.RETURN):
return self.parse_return ()
if self.check (TokenType.BREAK):
return self.parse_break ()
if self.check (TokenType.CONTINUE):
return self.parse_continue ()
if self.check (TokenType.IF):
return self.parse_if ()
if self.check (TokenType.WHILE):
return self.parse_while ()
if self.check (TokenType.FOR):
return self.parse_for ()
if self.check (TokenType.FOREACH):
return self.parse_foreach ()
if self.check (TokenType.TRY):
return self.parse_try ()
if self.check (TokenType.THROW):
return self.parse_throw ()
if self.check (TokenType.DEFER):
return self.parse_defer ()
if self.check (TokenType.WHEN):
return self.parse_when ()
if self.check (TokenType.LBRACE):
return self.parse_block ()
return self.parse_expression_statement ()
def parse_block (self) -> Block:
loc = self.location ()
self.expect (TokenType.LBRACE, "Expected '{'")
self.skip_newlines ()
statements = []
while not self.check (TokenType.RBRACE) and not self.check (TokenType.EOF):
stmt = self.parse_declaration ()
if stmt:
statements.append (stmt)
self.skip_newlines ()
self.expect (TokenType.RBRACE, "Expected '}'")
return Block (statements=statements, location=loc)
def parse_return (self) -> ReturnStmt:
loc = self.location ()
self.expect (TokenType.RETURN)
value = None
if not self.check (TokenType.NEWLINE) and not self.check (TokenType.RBRACE) and not self.check (TokenType.EOF):
value = self.parse_expression ()
return ReturnStmt (value=value, location=loc)
def parse_break (self) -> BreakStmt:
loc = self.location ()
self.expect (TokenType.BREAK)
return BreakStmt (location=loc)
def parse_continue (self) -> ContinueStmt:
loc = self.location ()
self.expect (TokenType.CONTINUE)
return ContinueStmt (location=loc)
def parse_if (self) -> IfStmt:
loc = self.location ()
self.expect (TokenType.IF)
condition = self.parse_expression ()
self.skip_newlines ()
then_branch = self.parse_block ()
elif_branches = []
else_branch = None
self.skip_newlines ()
while self.check (TokenType.ELSE):
self.advance ()
if self.match (TokenType.IF):
elif_cond = self.parse_expression ()
self.skip_newlines ()
elif_block = self.parse_block ()
elif_branches.append ((elif_cond, elif_block))
self.skip_newlines ()
else:
self.skip_newlines ()
else_branch = self.parse_block ()
break
return IfStmt (
condition=condition,
then_branch=then_branch,
elif_branches=elif_branches,
else_branch=else_branch,
location=loc
)
def parse_while (self) -> WhileStmt:
loc = self.location ()
self.expect (TokenType.WHILE)
condition = self.parse_expression ()
self.skip_newlines ()
body = self.parse_block ()
return WhileStmt (condition=condition, body=body, location=loc)
def parse_for (self) -> ForStmt:
loc = self.location ()
self.expect (TokenType.FOR)
variable = self.expect (TokenType.IDENTIFIER, "Expected loop variable").value
self.expect (TokenType.IN, "Expected 'in'")
iterable = self.parse_expression ()
self.skip_newlines ()
body = self.parse_block ()
return ForStmt (variable=variable, iterable=iterable, body=body, location=loc)
def parse_foreach (self) -> ForeachStmt:
loc = self.location ()
self.expect (TokenType.FOREACH)
variables = []
variables.append (self.expect (TokenType.IDENTIFIER, "Expected loop variable").value)
if self.match (TokenType.COMMA):
variables.append (self.expect (TokenType.IDENTIFIER, "Expected second loop variable").value)
self.expect (TokenType.IN, "Expected 'in'")
iterable = self.parse_expression ()
self.skip_newlines ()
body = self.parse_block ()
return ForeachStmt (variables=variables, iterable=iterable, body=body, location=loc)
def parse_try (self) -> TryStmt:
loc = self.location ()
self.expect (TokenType.TRY)
self.skip_newlines ()
try_block = self.parse_block ()
except_clauses = []
finally_block = None
self.skip_newlines ()
while self.match (TokenType.EXCEPT):
exc_type = None
exc_var = None
if self.check (TokenType.IDENTIFIER):
first_id = self.advance ().value
if self.check (TokenType.IDENTIFIER):
exc_type = first_id
exc_var = self.advance ().value
else:
exc_var = first_id
self.skip_newlines ()
exc_block = self.parse_block ()
except_clauses.append ((exc_type, exc_var, exc_block))
self.skip_newlines ()
if self.match (TokenType.FINALLY):
self.skip_newlines ()
finally_block = self.parse_block ()
return TryStmt (
try_block=try_block,
except_clauses=except_clauses,
finally_block=finally_block,
location=loc
)
def parse_throw (self) -> ThrowStmt:
loc = self.location ()
self.expect (TokenType.THROW)
expression = self.parse_expression ()
return ThrowStmt (expression=expression, location=loc)
def parse_defer (self) -> DeferStmt:
loc = self.location ()
self.expect (TokenType.DEFER)
expression = self.parse_expression ()
return DeferStmt (expression=expression, location=loc)
def parse_when (self) -> WhenStmt:
loc = self.location ()
self.expect (TokenType.WHEN)
value = self.parse_expression ()
self.skip_newlines ()
self.expect (TokenType.LBRACE, "Expected '{' after when value")
self.skip_newlines ()
branches = []
while not self.check (TokenType.RBRACE) and not self.check (TokenType.EOF):
branch = self.parse_when_branch ()
branches.append (branch)
self.skip_newlines ()
self.expect (TokenType.RBRACE, "Expected '}' after when branches")
return WhenStmt (value=value, branches=branches, location=loc)
def parse_when_branch (self) -> WhenBranch:
loc = self.location ()
if self.match (TokenType.ELSE):
self.skip_newlines ()
body = self.parse_block ()
return WhenBranch (patterns=[], is_else=True, body=body, location=loc)
patterns = []
while True:
pattern = self.parse_when_pattern ()
patterns.append (pattern)
if not self.match (TokenType.COMMA):
break
self.skip_newlines ()
body = self.parse_block ()
return WhenBranch (patterns=patterns, is_else=False, body=body, location=loc)
def parse_when_pattern (self) -> Expression:
"""Parse a single pattern: value or range (start..end)"""
loc = self.location ()
left = self.parse_primary ()
if self.match (TokenType.DOTDOT):
right = self.parse_primary ()
return RangePattern (start=left, end=right, location=loc)
return left
def parse_expression_statement (self) -> Optional[Statement]:
loc = self.location ()
expr = self.parse_expression ()
if self.check (TokenType.ASSIGN, TokenType.PLUS_ASSIGN, TokenType.MINUS_ASSIGN,
TokenType.STAR_ASSIGN, TokenType.SLASH_ASSIGN):
operator = self.advance ().value
value = self.parse_expression ()
return Assignment (target=expr, operator=operator, value=value, location=loc)
return ExpressionStmt (expression=expr, location=loc)
PRECEDENCE = {
TokenType.PIPE: 0,
TokenType.OR: 1,
TokenType.AND: 2,
TokenType.EQ: 3,
TokenType.NEQ: 3,
TokenType.LT: 4,
TokenType.GT: 4,
TokenType.LTE: 4,
TokenType.GTE: 4,
TokenType.PLUS: 5,
TokenType.MINUS: 5,
TokenType.DOTDOT: 5,
TokenType.STAR: 6,
TokenType.SLASH: 6,
TokenType.PERCENT: 6,
}
def parse_expression (self, min_prec: int = 0) -> Expression:
left = self.parse_unary ()
while True:
prec = self.PRECEDENCE.get (self.current ().type, -1)
if prec < min_prec:
break
operator = self.advance ()
right = self.parse_expression (prec + 1)
left = BinaryOp (left=left, operator=operator.value, right=right, location=left.location)
return left
def parse_unary (self) -> Expression:
if self.check (TokenType.NOT, TokenType.MINUS):
loc = self.location ()
operator = self.advance ()
operand = self.parse_unary ()
return UnaryOp (operator=operator.value, operand=operand, location=loc)
if self.check (TokenType.NEW):
loc = self.location ()
self.advance () # consume 'new'
class_name = self.expect (TokenType.IDENTIFIER, "Expected class name after 'new'").value
self.expect (TokenType.LPAREN, "Expected '(' after class name")
args = []
if not self.check (TokenType.RPAREN):
args = self.parse_arguments ()
self.expect (TokenType.RPAREN, "Expected ')' after constructor arguments")
return NewExpr (class_name=class_name, arguments=args, location=loc)
return self.parse_postfix ()
def parse_postfix (self) -> Expression:
expr = self.parse_primary ()
while True:
if self.match (TokenType.LPAREN):
args = []
if not self.check (TokenType.RPAREN):
args = self.parse_arguments ()
self.expect (TokenType.RPAREN, "Expected ')' after arguments")
expr = CallExpr (callee=expr, arguments=args, location=expr.location)
elif self.match (TokenType.DOT):
member = self.expect (TokenType.IDENTIFIER, "Expected member name").value
expr = MemberAccess (object=expr, member=member, location=expr.location)
elif self.match (TokenType.LBRACKET):
index = self.parse_expression ()
self.expect (TokenType.RBRACKET, "Expected ']' after index")
expr = IndexAccess (object=expr, index=index, location=expr.location)
else:
break
return expr
def parse_arguments (self) -> List[Expression]:
args = []
while True:
args.append (self.parse_expression ())
if not self.match (TokenType.COMMA):
break
return args
def parse_primary (self) -> Expression:
loc = self.location ()
token = self.current ()
if self.match (TokenType.INTEGER):
return IntegerLiteral (value=token.value, location=loc)
if self.match (TokenType.FLOAT):
return FloatLiteral (value=token.value, location=loc)
if self.match (TokenType.STRING):
has_interp = '{' in token.value
return StringLiteral (value=token.value, has_interpolation=has_interp, location=loc)
if self.match (TokenType.TRUE):
return BoolLiteral (value=True, location=loc)
if self.match (TokenType.FALSE):
return BoolLiteral (value=False, location=loc)
if self.match (TokenType.NIL):
return NilLiteral (location=loc)
if self.match (TokenType.THIS):
return ThisExpr (location=loc)
if self.check (TokenType.BASE):
return self.parse_base_call ()
if self.match (TokenType.LBRACKET):
elements = []
if not self.check (TokenType.RBRACKET):
while True:
elements.append (self.parse_expression ())
if not self.match (TokenType.COMMA):
break
self.expect (TokenType.RBRACKET, "Expected ']'")
return ArrayLiteral (elements=elements, location=loc)
if self.check (TokenType.LBRACE):
return self.parse_dict_literal ()
if self.check (TokenType.LPAREN):
return self.parse_paren_or_lambda ()
if self.check (TokenType.IDENTIFIER):
if self.peek ().type == TokenType.ARROW:
return self.parse_lambda ()
self.advance ()
return Identifier (name=token.value, location=loc)
if self.match (TokenType.RANGE):
self.expect (TokenType.LPAREN, "Expected '(' after 'range'")
args = self.parse_arguments ()
self.expect (TokenType.RPAREN, "Expected ')'")
return CallExpr (
callee=Identifier (name="range", location=loc),
arguments=args,
location=loc
)
self.error (f"Unexpected token: {token.type.name}")
self.advance ()
return NilLiteral (location=loc)
def parse_base_call (self) -> BaseCall:
loc = self.location ()
self.expect (TokenType.BASE)
self.expect (TokenType.LPAREN, "Expected '(' after 'base'")
args = []
if not self.check (TokenType.RPAREN):
args = self.parse_arguments ()
self.expect (TokenType.RPAREN, "Expected ')'")
return BaseCall (arguments=args, location=loc)
def parse_dict_literal (self) -> DictLiteral:
loc = self.location ()
self.expect (TokenType.LBRACE)
self.skip_newlines ()
pairs = []
while not self.check (TokenType.RBRACE) and not self.check (TokenType.EOF):
key = self.parse_expression ()
self.expect (TokenType.COLON, "Expected ':' after dict key")
value = self.parse_expression ()
pairs.append ((key, value))
self.skip_newlines ()
if not self.match (TokenType.COMMA):
break
self.skip_newlines ()
self.skip_newlines ()
self.expect (TokenType.RBRACE, "Expected '}'")
return DictLiteral (pairs=pairs, location=loc)
def parse_paren_or_lambda (self) -> Expression:
loc = self.location ()
self.expect (TokenType.LPAREN)
if self.check (TokenType.RPAREN):
self.advance ()
if self.match (TokenType.ARROW):
return self.parse_lambda_body ([], loc)
self.error ("Expected '=>' after '()'")
return NilLiteral (location=loc)
if self.check (TokenType.IDENTIFIER):
saved_pos = self.pos
params = []
is_lambda = True
try:
while True:
if not self.check (TokenType.IDENTIFIER):
is_lambda = False
break
params.append (self.advance ().value)
if not self.match (TokenType.COMMA):
break
if is_lambda and self.match (TokenType.RPAREN):
if self.match (TokenType.ARROW):
return self.parse_lambda_body (params, loc)
self.pos = saved_pos
except:
self.pos = saved_pos
expr = self.parse_expression ()
self.expect (TokenType.RPAREN, "Expected ')'")
return expr
def parse_lambda (self) -> Lambda:
loc = self.location ()
param = self.expect (TokenType.IDENTIFIER).value
self.expect (TokenType.ARROW)
return self.parse_lambda_body ([param], loc)
def parse_lambda_body (self, params: List[str], loc: SourceLocation) -> Lambda:
if self.check (TokenType.LBRACE):
body = self.parse_block ()
else:
body = self.parse_expression ()
return Lambda (params=params, body=body, location=loc)
class StdlibMixin:
"""Mixin class for standard library code generation.
Provides emit_stdlib() method that generates all ContenT
standard library functions in Bash.
"""
def emit_stdlib (self):
"""Emit the ContenT standard library."""
self.emit ("# === ContenT Standard Library ===")
self.emit ()
self._emit_core ()
self._emit_http ()
self._emit_fs ()
self._emit_json ()
self._emit_object_system ()
self._emit_exception ()
self._emit_logger ()
self._emit_string ()
self._emit_array ()
self._emit_regex ()
self._emit_utils ()
self._emit_awk_wrapper ()
self._emit_math ()
self._emit_dict ()
self._emit_misc ()
self.emit ("# === End Standard Library ===")
self.emit ()
def _emit_core (self):
"""Core functions: print, range, len."""
self.emit ("exec 3>&1 # Save stdout to FD3 for print()")
self.emit ()
self.emit ("__ct_print () {")
self.indent_level += 1
self.emit ('local msg="$1"')
self.emit ('echo -e "$msg" >&3')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_range () {")
self.indent_level += 1
self.emit ('local start=0 end step=1')
self.emit ('case $# in')
self.indent_level += 1
self.emit ('1) end=$1 ;;')
self.emit ('2) start=$1; end=$2 ;;')
self.emit ('3) start=$1; end=$2; step=$3 ;;')
self.indent_level -= 1
self.emit ('esac')
self.emit ('seq "$start" "$step" "$((end - 1))"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_len () {")
self.indent_level += 1
self.emit ('local -n arr=$1')
self.emit ('echo "${#arr[@]}"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_http (self):
"""HTTP functions: get, post, put, delete."""
self.emit ("__ct_http_get () {")
self.indent_level += 1
self.emit ('local url="$1"')
self.emit ('local timeout="${2:-30}"')
self.emit ('curl -sS --fail --show-error --max-time "$timeout" "$url"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_http_post () {")
self.indent_level += 1
self.emit ('local url="$1"')
self.emit ('local data="$2"')
self.emit ('local timeout="${3:-30}"')
self.emit ('curl -sS --fail --show-error --max-time "$timeout" -X POST -H "Content-Type: application/json" -d "$data" "$url"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_http_put () {")
self.indent_level += 1
self.emit ('local url="$1"')
self.emit ('local data="$2"')
self.emit ('local timeout="${3:-30}"')
self.emit ('curl -sS --fail --show-error --max-time "$timeout" -X PUT -H "Content-Type: application/json" -d "$data" "$url"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_http_delete () {")
self.indent_level += 1
self.emit ('local url="$1"')
self.emit ('local timeout="${2:-30}"')
self.emit ('curl -sS --fail --show-error --max-time "$timeout" -X DELETE "$url"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_fs (self):
"""Filesystem functions: read, write, append, exists, remove, mkdir, list."""
self.emit ("__ct_fs_read () {")
self.indent_level += 1
self.emit ('cat "$1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_write () {")
self.indent_level += 1
self.emit ('echo -n "$2" > "$1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_append () {")
self.indent_level += 1
self.emit ('echo -n "$2" >> "$1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_exists () {")
self.indent_level += 1
self.emit ('[[ -e "$1" ]] && echo "true" || echo "false"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_remove () {")
self.indent_level += 1
self.emit ('rm -f "$1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_mkdir () {")
self.indent_level += 1
self.emit ('mkdir -p "$1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_fs_list () {")
self.indent_level += 1
self.emit ('ls -1 "$1" 2>/dev/null || true')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_json (self):
"""JSON functions: parse, stringify."""
self.emit ("__ct_json_parse () {")
self.indent_level += 1
self.emit ('echo "$1" | jq -r "."')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_json_stringify () {")
self.indent_level += 1
self.emit ('echo "$1" | jq -c "."')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_object_system (self):
"""Object system: class tracking, method dispatch, field access."""
self.emit ("declare -gA __ct_obj_class=()")
self.emit ("declare -gA __CT_OBJ=()")
self.emit ("declare -g __ct_last_instance=''")
self.emit ()
self.emit ("__ct_call_method () {")
self.indent_level += 1
self.emit ('local __obj="$1"')
self.emit ('local __method="$2"')
self.emit ('shift 2')
self.emit ('local __class="${__ct_obj_class[$__obj]:-}"')
self.emit ('if [[ -z "$__class" ]]; then')
self.indent_level += 1
self.emit ('echo "Error: Unknown object $__obj" >&2')
self.emit ('return 1')
self.indent_level -= 1
self.emit ('fi')
self.emit ('"__ct_class_${__class}_${__method}" "$__obj" "$@"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_get_field () {")
self.indent_level += 1
self.emit ('echo "${__CT_OBJ[$1.$2]}"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("declare -g __CT_RET=''")
self.emit ()
def _emit_exception (self):
"""Exception handling."""
self.emit ("declare -g __ct_exception=''")
self.emit ("declare -g __ct_exception_type=''")
self.emit ()
self.emit ("__ct_throw () {")
self.indent_level += 1
self.emit ('__ct_exception_type="$1"')
self.emit ('__ct_exception="$2"')
self.emit ('return 1')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_logger (self):
"""Logger functions: info, warn, error, debug."""
self.emit ("__ct_logger_info () {")
self.indent_level += 1
self.emit ('echo "[INFO] $1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_logger_warn () {")
self.indent_level += 1
self.emit ('echo "[WARN] $1" >&2')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_logger_error () {")
self.indent_level += 1
self.emit ('echo "[ERROR] $1" >&2')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_logger_debug () {")
self.indent_level += 1
self.emit ('echo "[DEBUG] $1"')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_string (self):
"""String functions."""
self.emit ("# String functions")
self.emit ("__ct_str_len () { __CT_RET=${#1}; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_substr () { __CT_RET=\"${1:$2:$3}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_index () { local i=\"${1%%$2*}\"; [[ \"$i\" == \"$1\" ]] && __CT_RET=-1 || __CT_RET=${#i}; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_contains () { [[ \"$1\" == *\"$2\"* ]] && __CT_RET=true || __CT_RET=false; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_starts () { [[ \"$1\" == \"$2\"* ]] && __CT_RET=true || __CT_RET=false; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_ends () { [[ \"$1\" == *\"$2\" ]] && __CT_RET=true || __CT_RET=false; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_replace () { __CT_RET=\"${1//\"$2\"/\"$3\"}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_split () { local IFS=\"$2\"; read -ra __arr <<< \"$1\"; printf '%s\\n' \"${__arr[@]}\"; }")
self.emit ("__ct_str_trim () { local s=\"$1\"; s=\"${s#\"${s%%[![:space:]]*}\"}\"; __CT_RET=\"${s%\"${s##*[![:space:]]}\"}\" ; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_upper () { __CT_RET=\"${1^^}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_lower () { __CT_RET=\"${1,,}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_char_at () { __CT_RET=\"${1:$2:1}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_str_concat () { __CT_RET=\"$1$2\"; echo \"$__CT_RET\"; }")
self.emit ()
self.emit ("# Character code functions")
self.emit ("__ct_str_ord () { __CT_RET=$(printf '%d' \"'$1\"); echo \"$__CT_RET\"; }")
self.emit ("__ct_str_chr () { printf -v __CT_RET '%b' \"\\\\x$(printf '%02x' \"$1\")\"; echo \"$__CT_RET\"; }")
self.emit ()
def _emit_array (self):
"""Array functions."""
self.emit ("# Array functions (optimized - set __CT_RET and echo)")
self.emit ("__ct_arr_push () { local -n __a=$1; shift; __a+=(\"$@\"); }")
self.emit ("__ct_arr_pop () { local -n __a=$1; unset '__a[-1]'; }")
self.emit ("__ct_arr_shift () { local -n __a=$1; __CT_RET=\"${__a[0]}\"; __a=(\"${__a[@]:1}\"); echo \"$__CT_RET\"; }")
self.emit ("__ct_arr_join () { local -n __a=$1; local sep; printf -v sep '%b' \"$2\"; local IFS=\"$sep\"; __CT_RET=\"${__a[*]}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_arr_len () { local -n __a=$1; __CT_RET=${#__a[@]}; echo \"$__CT_RET\"; }")
self.emit ("__ct_arr_get () { local -n __a=$1; __CT_RET=\"${__a[$2]}\"; echo \"$__CT_RET\"; }")
self.emit ("__ct_arr_set () { local -n __a=$1; __a[$2]=\"$3\"; }")
self.emit ("__ct_arr_slice () { local -n __a=$1; local -a __r=(\"${__a[@]:$2:$3}\"); printf '%s\\n' \"${__r[@]}\"; }")
self.emit ()
self.emit ("# Fast array functions (no echo - use __CT_RET directly)")
self.emit ("__ct_arr_len_fast () { local -n __a=$1; __CT_RET=${#__a[@]}; }")
self.emit ("__ct_arr_get_fast () { local -n __a=$1; __CT_RET=\"${__a[$2]}\"; }")
self.emit ()
def _emit_regex (self):
"""Regex functions."""
self.emit ("# ngrep - pattern search")
self.emit ("__ct_ngrep () {")
self.indent_level += 1
self.emit ('local pattern="$1"')
self.emit ('local text="$2"')
self.emit ('echo "$text" | grep -n "$pattern" || true')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_regex_match () {")
self.indent_level += 1
self.emit ('local str="$1"')
self.emit ('local pattern="$2"')
self.emit ('[[ "$str" =~ $pattern ]] && echo true || echo false')
self.indent_level -= 1
self.emit ("}")
self.emit ()
self.emit ("__ct_regex_extract () {")
self.indent_level += 1
self.emit ('local str="$1"')
self.emit ('local pattern="$2"')
self.emit ('if [[ "$str" =~ $pattern ]]; then')
self.indent_level += 1
self.emit ('echo "${BASH_REMATCH[0]}"')
self.indent_level -= 1
self.emit ('fi')
self.indent_level -= 1
self.emit ("}")
self.emit ()
def _emit_utils (self):
"""Utility functions."""
self.emit ("__ct_exit () { exit \"${1:-0}\"; }")
self.emit ()
self.emit ("__ct_is_number () { [[ \"$1\" =~ ^-?[0-9]+$ ]] && echo true || echo false; }")
self.emit ("__ct_is_empty () { [[ -z \"$1\" ]] && echo true || echo false; }")
self.emit ()
self.emit ('__ct_args=("$@")')
self.emit ('__ct_args_count () { echo ${#__ct_args[@]}; }')
self.emit ("__ct_args_get () { printf '%s\\n' \"${__ct_args[$1]}\"; }")
self.emit ()
def _emit_awk_wrapper (self):
"""AWK wrapper functions."""
self.emit ("# AWK wrapper - uses mawk if available (2-10x faster)")
self.emit ("__ct_awk_cmd=''")
self.emit ("if command -v mawk &>/dev/null; then __ct_awk_cmd=mawk")
self.emit ("elif command -v gawk &>/dev/null; then __ct_awk_cmd=gawk; echo '[WARN] mawk not found, using gawk (slower)' >&2")
self.emit ("elif command -v awk &>/dev/null; then __ct_awk_cmd=awk; echo '[WARN] mawk not found, using awk (slower)' >&2")
self.emit ("else echo '[ERROR] No awk implementation found' >&2; exit 1; fi")
self.emit ('__ct_awk () { "$__ct_awk_cmd" "$@"; }')
self.emit ('__ct_awk_file () { "$__ct_awk_cmd" -f "$1" "$2"; }')
self.emit ()
def _emit_math (self):
"""Math functions."""
self.emit ("# Math functions (fast - no external commands)")
self.emit ("__ct_math_add () { echo $(($1 + $2)); }")
self.emit ("__ct_math_sub () { echo $(($1 - $2)); }")
self.emit ("__ct_math_mul () { echo $(($1 * $2)); }")
self.emit ("__ct_math_div () { echo $(($1 / $2)); }")
self.emit ("__ct_math_mod () { echo $(($1 % $2)); }")
self.emit ("__ct_math_min () { (($1 < $2)) && echo $1 || echo $2; }")
self.emit ("__ct_math_max () { (($1 > $2)) && echo $1 || echo $2; }")
self.emit ("__ct_math_abs () { local n=$1; echo ${n#-}; }")
self.emit ()
def _emit_dict (self):
"""Dict/hash functions."""
self.emit ("# Dict/hash functions (using associative arrays)")
self.emit ('__ct_dict_set () { local -n __d="$1"; __d["$2"]="$3"; }')
self.emit ('__ct_dict_get () { local -n __d="$1"; __CT_RET="${__d[$2]}"; echo "$__CT_RET"; }')
self.emit ('__ct_dict_has () { local -n __d="$1"; [[ -v "__d[$2]" ]] && __CT_RET=true || __CT_RET=false; echo "$__CT_RET"; }')
self.emit ('__ct_dict_del () { local -n __d="$1"; unset "__d[$2]"; }')
self.emit ('__ct_dict_keys () { local -n __d="$1"; printf \'%s\\n\' "${!__d[@]}"; }')
self.emit ()
def _emit_misc (self):
"""Miscellaneous functions."""
self.emit ("# Byte/binary functions")
self.emit ("__ct_byte_to_hex () { printf '%02x' \"$1\"; }")
self.emit ("__ct_hex_to_byte () { printf '%d' \"0x$1\"; }")
self.emit ()
self.emit ("# Time functions")
self.emit ("__ct_time_now () { date +%s; }")
self.emit ("__ct_time_ms () { date +%s%3N; }")
self.emit ()
self.emit ("# Random")
self.emit ("__ct_random () { echo $RANDOM; }")
self.emit ("__ct_random_range () { echo $(($1 + RANDOM % ($2 - $1 + 1))); }")
self.emit ()
self.emit ("__CT_NL=$'\\n'")
self.emit ()
from .ast_nodes import *
class StmtMixin:
"""Mixin for statement generation."""
def generate_statement(self, stmt):
if isinstance(stmt, FunctionDecl):
self.generate_function(stmt)
elif isinstance(stmt, ClassDecl):
self.generate_class(stmt)
elif isinstance(stmt, ImportStmt):
self.generate_import(stmt)
elif isinstance(stmt, Assignment):
self.generate_assignment(stmt)
elif isinstance(stmt, ExpressionStmt):
self.generate_expression_stmt(stmt)
elif isinstance(stmt, IfStmt):
self.generate_if(stmt)
elif isinstance(stmt, WhileStmt):
self.generate_while(stmt)
elif isinstance(stmt, ForStmt):
self.generate_for(stmt)
elif isinstance(stmt, ForeachStmt):
self.generate_foreach(stmt)
elif isinstance(stmt, TryStmt):
self.generate_try(stmt)
elif isinstance(stmt, ThrowStmt):
self.generate_throw(stmt)
elif isinstance(stmt, DeferStmt):
self.generate_defer(stmt)
elif isinstance(stmt, WhenStmt):
self.generate_when(stmt)
elif isinstance(stmt, ReturnStmt):
self.generate_return(stmt)
elif isinstance(stmt, BreakStmt):
self.emit("break")
elif isinstance(stmt, ContinueStmt):
self.emit("continue")
elif isinstance(stmt, Block):
for s in stmt.statements:
self.generate_statement(s)
def generate_import(self, stmt: ImportStmt):
path = stmt.path
if path.startswith("std/"):
self.emit(f"# import {path} (stdlib - already included)")
elif path.endswith(".sh"):
self.emit(f'source "{path}"')
else:
self.emit(f'# import "{path}"')
self.emit(f'if [[ -f "$HOME/.content/libs/{path}.sh" ]]; then')
self.indent_level += 1
self.emit(f'source "$HOME/.content/libs/{path}.sh"')
self.indent_level -= 1
self.emit(f'elif [[ -f "/usr/lib/content/{path}.sh" ]]; then')
self.indent_level += 1
self.emit(f'source "/usr/lib/content/{path}.sh"')
self.indent_level -= 1
self.emit("fi")
self.emit()
def generate_if(self, stmt: IfStmt):
if isinstance(stmt.condition, CallExpr) and isinstance(stmt.condition.callee, Identifier):
func_name = stmt.condition.callee.name
args = [self.generate_expr(a) for a in stmt.condition.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{func_name} {args_str} >/dev/null')
self.emit(f'if [[ "$__CT_RET" == "true" ]]; then')
else:
mapping, _ = self.precompute_all_calls(stmt.condition)
if mapping:
cond = self.generate_condition_with_precompute(stmt.condition, mapping)
else:
cond = self.generate_condition(stmt.condition)
self.emit(f"if {cond}; then")
self.indent_level += 1
for s in stmt.then_branch.statements:
self.generate_statement(s)
self.indent_level -= 1
for elif_cond, elif_block in stmt.elif_branches:
cond = self.generate_condition(elif_cond)
self.emit(f"elif {cond}; then")
self.indent_level += 1
for s in elif_block.statements:
self.generate_statement(s)
self.indent_level -= 1
if stmt.else_branch:
self.emit("else")
self.indent_level += 1
for s in stmt.else_branch.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("fi")
def generate_when(self, stmt: WhenStmt):
value_expr = self.generate_expr(stmt.value)
has_ranges = any(
any(isinstance(p, RangePattern) for p in branch.patterns)
for branch in stmt.branches if not branch.is_else
)
if has_ranges:
self._generate_when_if_chain(stmt, value_expr)
else:
self._generate_when_case(stmt, value_expr)
def _generate_when_case(self, stmt: WhenStmt, value_expr: str):
self.emit(f'case "{value_expr}" in')
self.indent_level += 1
for branch in stmt.branches:
if branch.is_else:
self.emit("*)")
else:
patterns = []
for p in branch.patterns:
val = self.generate_expr(p)
if isinstance(p, StringLiteral):
patterns.append(f'"{val}"' if val else '""')
else:
patterns.append(val)
self.emit(f'{"|".join(patterns)})')
self.indent_level += 1
for s in branch.body.statements:
self.generate_statement(s)
self.emit(";;")
self.indent_level -= 1
self.indent_level -= 1
self.emit("esac")
def _generate_when_if_chain(self, stmt: WhenStmt, value_expr: str):
self.emit(f'__when_val="{value_expr}"')
first = True
for branch in stmt.branches:
if branch.is_else:
self.emit("else")
else:
conditions = []
for p in branch.patterns:
if isinstance(p, RangePattern):
start = self.generate_expr(p.start)
end = self.generate_expr(p.end)
conditions.append(f'(( __when_val >= {start} && __when_val <= {end} ))')
else:
val = self.generate_expr(p)
conditions.append(f'[[ "$__when_val" == "{val}" ]]')
cond_str = " || ".join(conditions)
if first:
self.emit(f"if {cond_str}; then")
first = False
else:
self.emit(f"elif {cond_str}; then")
self.indent_level += 1
for s in branch.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("fi")
def generate_while(self, stmt: WhileStmt):
mapping, regen_code = self.precompute_all_calls(stmt.condition)
if mapping:
cond = self.generate_condition_with_precompute(stmt.condition, mapping)
self.emit(f"while {cond}; do")
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
if regen_code:
self.emit("# CSE: re-compute condition vars")
for call_line, assign_line in regen_code:
self.emit(call_line)
if assign_line:
self.emit(assign_line)
self.indent_level -= 1
self.emit("done")
return
if isinstance(stmt.condition, CallExpr) and isinstance(stmt.condition.callee, Identifier):
func_name = stmt.condition.callee.name
args = [self.generate_expr(a) for a in stmt.condition.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit("while true; do")
self.indent_level += 1
self.emit(f'{func_name} {args_str} >/dev/null')
self.emit(f'if [[ "$__CT_RET" != "true" ]]; then break; fi')
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
return
cond = self.generate_condition(stmt.condition)
self.emit(f"while {cond}; do")
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
def generate_for(self, stmt: ForStmt):
var = stmt.variable
if isinstance(stmt.iterable, CallExpr) and isinstance(stmt.iterable.callee, Identifier):
if stmt.iterable.callee.name == "range":
args = [self.generate_expr(a) for a in stmt.iterable.arguments]
if len(args) == 1:
self.emit(f"for {var} in $(seq 0 $(({args[0]} - 1))); do")
elif len(args) == 2:
self.emit(f"for {var} in $(seq {args[0]} $(({args[1]} - 1))); do")
else:
self.emit(f"for {var} in $(seq {args[0]} {args[2]} $(({args[1]} - 1))); do")
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
return
iterable = self.generate_expr(stmt.iterable)
self.emit(f'for {var} in {iterable}; do')
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
def generate_foreach(self, stmt: ForeachStmt):
if isinstance(stmt.iterable, CallExpr):
if isinstance(stmt.iterable.callee, Identifier) and stmt.iterable.callee.name == "range":
args = [self.generate_expr(a) for a in stmt.iterable.arguments]
var = stmt.variables[0]
if len(args) == 1:
self.emit(f"for {var} in $(seq 0 $(({args[0]} - 1))); do")
elif len(args) == 2:
self.emit(f"for {var} in $(seq {args[0]} $(({args[1]} - 1))); do")
else:
self.emit(f"for {var} in $(seq {args[0]} {args[2]} $(({args[1]} - 1))); do")
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
return
if isinstance(stmt.iterable, Identifier):
arr_name = stmt.iterable.name
if len(stmt.variables) == 1:
var = stmt.variables[0]
self.emit(f'for {var} in "${{{arr_name}[@]}}"; do')
else:
idx_var = stmt.variables[0]
val_var = stmt.variables[1]
self.emit(f'{idx_var}=0')
self.emit(f'for {val_var} in "${{{arr_name}[@]}}"; do')
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
if len(stmt.variables) == 2:
self.emit(f'((++{stmt.variables[0]}))')
self.indent_level -= 1
self.emit("done")
return
if isinstance(stmt.iterable, CallExpr):
if isinstance(stmt.iterable.callee, MemberAccess):
if (isinstance(stmt.iterable.callee.object, Identifier) and
stmt.iterable.callee.object.name == "str" and
stmt.iterable.callee.member == "split" and
len(stmt.iterable.arguments) == 2):
str_arg = self.generate_expr(stmt.iterable.arguments[0])
delim_arg = self.generate_expr(stmt.iterable.arguments[1])
var = stmt.variables[0]
self.emit(f'IFS=\'{delim_arg}\' read -ra __ct_split_arr <<< "{str_arg}"')
if len(stmt.variables) == 1:
self.emit(f'for {var} in "${{__ct_split_arr[@]}}"; do')
else:
idx_var = stmt.variables[0]
val_var = stmt.variables[1]
self.emit(f'{idx_var}=0')
self.emit(f'for {val_var} in "${{__ct_split_arr[@]}}"; do')
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
if len(stmt.variables) == 2:
self.emit(f'((++{stmt.variables[0]}))')
self.indent_level -= 1
self.emit("done")
return
iterable = self.generate_expr(stmt.iterable)
var = stmt.variables[0]
self.emit(f'for {var} in {iterable}; do')
self.indent_level += 1
for s in stmt.body.statements:
self.generate_statement(s)
self.indent_level -= 1
self.emit("done")
def generate_try(self, stmt: TryStmt):
self.emit("# try/except block")
self.emit("set +e")
self.emit("__ct_exception=''")
self.emit("__ct_exception_type=''")
self.emit("__ct_try_failed=0")
self.emit()
self.emit("while true; do")
self.indent_level += 1
for s in stmt.try_block.statements:
self.generate_statement(s)
self.emit('if [[ $? -ne 0 ]]; then')
self.indent_level += 1
self.emit('__ct_try_failed=1')
self.emit('__ct_exception_type="Error"')
self.emit('__ct_exception="Command failed"')
self.emit('break')
self.indent_level -= 1
self.emit('fi')
self.emit("break")
self.indent_level -= 1
self.emit("done")
self.emit()
self.emit("set -e")
self.emit()
self.emit('if [[ "$__ct_try_failed" == "1" ]]; then')
self.indent_level += 1
for i, (exc_type, exc_var, exc_block) in enumerate(stmt.except_clauses):
if i == 0:
if exc_type:
self.emit(f'if [[ "$__ct_exception_type" == "{exc_type}" ]]; then')
else:
if exc_type:
self.emit(f'elif [[ "$__ct_exception_type" == "{exc_type}" ]]; then')
else:
self.emit("else")
if exc_type or i > 0:
self.indent_level += 1
if exc_var:
self.emit(f'{exc_var}="$__ct_exception"')
for s in exc_block.statements:
self.generate_statement(s)
if exc_type or i > 0:
self.indent_level -= 1
if stmt.except_clauses and stmt.except_clauses[0][0] is not None:
self.emit("fi")
self.indent_level -= 1
self.emit("fi")
if stmt.finally_block:
self.emit()
self.emit("# finally block")
for s in stmt.finally_block.statements:
self.generate_statement(s)
def generate_throw(self, stmt: ThrowStmt):
if isinstance(stmt.expression, CallExpr):
if isinstance(stmt.expression.callee, Identifier):
exc_type = stmt.expression.callee.name
exc_args = [self.generate_expr(a) for a in stmt.expression.arguments]
exc_msg = exc_args[0] if exc_args else ""
self.emit(f'__ct_throw "{exc_type}" "{exc_msg}"')
return
expr = self.generate_expr(stmt.expression)
self.emit(f'__ct_throw "Error" "{expr}"')
def generate_defer(self, stmt: DeferStmt):
if isinstance(stmt.expression, CallExpr):
call = self.generate_call_statement(stmt.expression)
self.deferred_calls.append(call)
else:
expr = self.generate_expr(stmt.expression)
self.deferred_calls.append(expr)
def generate_return(self, stmt: ReturnStmt):
if self.deferred_calls:
self.emit("# Deferred calls before return")
for call in reversed(self.deferred_calls):
self.emit(call)
if stmt.value:
if isinstance(stmt.value, CallExpr) and isinstance(stmt.value.callee, MemberAccess):
if isinstance(stmt.value.callee.object, Identifier) and stmt.value.callee.object.name == "str":
result = self._generate_inline_str_return(stmt.value)
if result:
return
if isinstance(stmt.value, CallExpr):
result = self._generate_call_return(stmt.value)
if result:
return
if isinstance(stmt.value, NewExpr):
args = [self.generate_expr(arg) for arg in stmt.value.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{stmt.value.class_name} {args_str}')
self.emit('__CT_RET="$__ct_last_instance"')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return
if isinstance(stmt.value, BinaryOp) and stmt.value.operator in ("==", "!=", "<", ">", "<=", ">=", "&&", "||"):
cond = self.generate_condition(stmt.value)
self.emit(f'{cond} && __CT_RET=true || __CT_RET=false')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return
value = self.generate_expr(stmt.value)
self.emit(f'__CT_RET="{value}"')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
else:
self.emit("return 0")
def _generate_inline_str_return(self, expr: CallExpr) -> bool:
"""Inline str.contains/starts/ends for returns."""
method = expr.callee.member
if method == "contains" and len(expr.arguments) == 2:
haystack = self.generate_expr(expr.arguments[0])
needle = self.generate_expr(expr.arguments[1])
self.emit(f'[[ "{haystack}" == *"{needle}"* ]] && __CT_RET=true || __CT_RET=false')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
elif method == "starts" and len(expr.arguments) == 2:
s = self.generate_expr(expr.arguments[0])
prefix = self.generate_expr(expr.arguments[1])
self.emit(f'[[ "{s}" == "{prefix}"* ]] && __CT_RET=true || __CT_RET=false')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
elif method == "ends" and len(expr.arguments) == 2:
s = self.generate_expr(expr.arguments[0])
suffix = self.generate_expr(expr.arguments[1])
self.emit(f'[[ "{s}" == *"{suffix}" ]] && __CT_RET=true || __CT_RET=false')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
return False
def _generate_call_return(self, expr: CallExpr) -> bool:
"""Generate return for function/method calls."""
if isinstance(expr.callee, MemberAccess):
if isinstance(expr.callee.object, ThisExpr) and self.current_class:
method = expr.callee.member
args = [self.generate_expr(arg) for arg in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'__ct_class_{self.current_class}_{method} "$this" {args_str} >/dev/null')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
elif isinstance(expr.callee.object, Identifier):
obj_name = expr.callee.object.name
method = expr.callee.member
args = [self.generate_expr(arg) for arg in expr.arguments]
builtin_namespaces = {"fs", "http", "json", "logger", "regex", "args", "shell"}
if obj_name not in builtin_namespaces:
result = self._dispatch_instance_method_return(obj_name, method, args)
if result:
return True
elif isinstance(expr.callee, Identifier):
func_name = expr.callee.name
if func_name in self.functions:
args = [self.generate_expr(arg) for arg in expr.arguments]
args_str = " ".join([f'"{a}"' for a in args])
self.emit(f'{func_name} {args_str} >/dev/null')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
return False
def _dispatch_instance_method_return(self, obj_name: str, method: str, args: list) -> bool:
"""Dispatch instance method for return statement."""
arr_methods = {
"len": "__ct_arr_len", "push": "__ct_arr_push", "pop": "__ct_arr_pop",
"shift": "__ct_arr_shift", "join": "__ct_arr_join", "get": "__ct_arr_get",
"set": "__ct_arr_set", "slice": "__ct_arr_slice",
}
dict_methods = {
"get": "__ct_dict_get", "set": "__ct_dict_set", "has": "__ct_dict_has",
"del": "__ct_dict_del", "keys": "__ct_dict_keys",
}
str_methods = {
"len": "__ct_str_len", "upper": "__ct_str_upper", "lower": "__ct_str_lower",
"trim": "__ct_str_trim", "contains": "__ct_str_contains", "starts": "__ct_str_starts",
"ends": "__ct_str_ends", "index": "__ct_str_index", "replace": "__ct_str_replace",
"substr": "__ct_str_substr", "split": "__ct_str_split", "charAt": "__ct_str_char_at",
}
args_str = " ".join([f'"{a}"' for a in args])
if obj_name in self.array_vars and method in arr_methods:
func_name = arr_methods[method]
self.emit(f'{func_name} "{obj_name}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
elif obj_name in self.dict_vars and method in dict_methods:
func_name = dict_methods[method]
self.emit(f'{func_name} "{obj_name}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
elif method in str_methods:
func_name = str_methods[method]
self.emit(f'{func_name} "${{{obj_name}}}" {args_str} >/dev/null'.replace(' ', ' '))
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
self.emit(f'__ct_call_method "${{{obj_name}}}" "{method}" {args_str} >/dev/null')
self.emit('echo "$__CT_RET"')
self.emit("return 0")
return True
from enum import Enum, auto
from dataclasses import dataclass
from typing import Any
class TokenType (Enum):
INTEGER = auto ()
FLOAT = auto ()
STRING = auto ()
TRUE = auto ()
FALSE = auto ()
NIL = auto ()
IDENTIFIER = auto ()
FUNC = auto ()
CLASS = auto ()
CONSTRUCT = auto ()
THIS = auto ()
BASE = auto ()
RETURN = auto ()
IF = auto ()
ELSE = auto ()
FOREACH = auto ()
FOR = auto ()
IN = auto ()
WHILE = auto ()
BREAK = auto ()
CONTINUE = auto ()
IMPORT = auto ()
TRY = auto ()
EXCEPT = auto ()
FINALLY = auto ()
THROW = auto ()
DEFER = auto ()
RANGE = auto ()
WHEN = auto ()
NEW = auto ()
PLUS = auto ()
MINUS = auto ()
STAR = auto ()
SLASH = auto ()
PERCENT = auto ()
ASSIGN = auto ()
EQ = auto ()
NEQ = auto ()
LT = auto ()
GT = auto ()
LTE = auto ()
GTE = auto ()
AND = auto ()
OR = auto ()
PIPE = auto ()
NOT = auto ()
ARROW = auto ()
PLUS_ASSIGN = auto ()
MINUS_ASSIGN = auto ()
STAR_ASSIGN = auto ()
SLASH_ASSIGN = auto ()
DOT = auto ()
DOTDOT = auto ()
DOTDOTDOT = auto ()
COLON = auto ()
LPAREN = auto ()
RPAREN = auto ()
LBRACE = auto ()
RBRACE = auto ()
LBRACKET = auto ()
RBRACKET = auto ()
COMMA = auto ()
NEWLINE = auto ()
AT = auto ()
COMMENT = auto ()
EOF = auto ()
KEYWORDS = {
'func': TokenType.FUNC,
'class': TokenType.CLASS,
'construct': TokenType.CONSTRUCT,
'this': TokenType.THIS,
'base': TokenType.BASE,
'return': TokenType.RETURN,
'if': TokenType.IF,
'else': TokenType.ELSE,
'foreach': TokenType.FOREACH,
'for': TokenType.FOR,
'in': TokenType.IN,
'while': TokenType.WHILE,
'break': TokenType.BREAK,
'continue': TokenType.CONTINUE,
'import': TokenType.IMPORT,
'try': TokenType.TRY,
'except': TokenType.EXCEPT,
'finally': TokenType.FINALLY,
'throw': TokenType.THROW,
'defer': TokenType.DEFER,
'range': TokenType.RANGE,
'when': TokenType.WHEN,
'new': TokenType.NEW,
'true': TokenType.TRUE,
'false': TokenType.FALSE,
'nil': TokenType.NIL,
}
@dataclass
class Token:
type: TokenType
value: Any
line: int
column: int
def __repr__ (self):
return f"Token({self.type.name}, {self.value!r}, {self.line}:{self.column})"
#!/usr/bin/env python3
"""
ContenT Compiler Entry Point
"""
import sys
import os
# Add bootstrap to path
sys.path.insert (0, os.path.dirname (os.path.abspath (__file__)))
from bootstrap.main import main
if __name__ == "__main__":
sys.exit (main ())
# Simple benchmark: @awk vs bash
# Test pure computation speed
# ========== AWK versions ==========
@awk
func awk_fib (n) {
a = 0
b = 1
for i in range (n) {
tmp = a
a = b
b = tmp + b
}
return a
}
@awk
func awk_sum_to_n (n) {
total = 0
for i in range (1, n + 1) {
total += i
}
return total
}
@awk
func awk_factorial (n) {
result = 1
for i in range (1, n + 1) {
result *= i
}
return result
}
@awk
func awk_count_primes (max) {
count = 0
for n in range (2, max) {
is_prime = 1
for i in range (2, n) {
if n % i == 0 {
is_prime = 0
break
}
}
if is_prime == 1 {
count += 1
}
}
return count
}
# ========== Bash versions ==========
func bash_fib (n) {
a = 0
b = 1
for i in range (n) {
tmp = a
a = b
b = tmp + b
}
return a
}
func bash_sum_to_n (n) {
total = 0
for i in range (1, n + 1) {
total += i
}
return total
}
func bash_factorial (n) {
result = 1
for i in range (1, n + 1) {
result *= i
}
return result
}
func bash_count_primes (max) {
count = 0
for n in range (2, max) {
is_prime = 1
for i in range (2, n) {
if n % i == 0 {
is_prime = 0
break
}
}
if is_prime == 1 {
count += 1
}
}
return count
}
# ========== Main ==========
print ("ContenT @awk vs Bash - Simple Benchmark")
print ("=======================================")
print ("")
# Verify correctness
print ("Verification (should be identical):")
print (" fib(20): AWK={awk_fib (20)} Bash={bash_fib (20)}")
print (" sum_to_n(100): AWK={awk_sum_to_n (100)} Bash={bash_sum_to_n (100)}")
print (" factorial(10): AWK={awk_factorial (10)} Bash={bash_factorial (10)}")
print (" primes(<50): AWK={awk_count_primes (50)} Bash={bash_count_primes (50)}")
print ("")
print ("Run with 'time' to compare performance:")
print (" time bash script.sh awk")
print (" time bash script.sh bash")
# Heavy string benchmark - bash should take ~1 minute
@awk
func awk_process_lines (n) {
result = ""
for i in range (n) {
line = "item_" .. i .. "_data_" .. (i * 7) .. "_end"
upper = line.upper ()
if upper.contains ("DATA") {
result = result .. upper.len () .. ","
}
}
return result.len ()
}
@awk
func awk_word_stats (n) {
total_len = 0
word_count = 0
for i in range (n) {
words = "alpha beta gamma delta epsilon zeta eta theta"
num = words.split (" ")
for j in range (1, num + 1) {
word = __split_arr[j]
total_len += word.len ()
word_count += 1
}
}
return total_len
}
@awk
func awk_build_csv (rows, cols) {
result = ""
for r in range (rows) {
for c in range (cols) {
val = (r * cols + c) * 13 % 1000
result = result .. val
if c < cols - 1 {
result = result .. ","
}
}
result = result .. "\n"
}
return result.len ()
}
@awk
func awk_search_pattern (n) {
count = 0
for i in range (n) {
text = "error_log_" .. i .. "_warning_" .. (i % 100) .. "_info"
if text.contains ("warning") {
count += 1
}
if text.contains ("error") {
count += 1
}
if text.contains ("info") {
count += 1
}
}
return count
}
@awk
func awk_concat_heavy (n) {
s = ""
for i in range (n) {
s = s .. "x"
}
return s.len ()
}
# === BASH versions ===
func bash_process_lines (n) {
result = ""
for i in range (n) {
line = "item_" .. i .. "_data_" .. (i * 7) .. "_end"
upper = line.upper ()
if upper.contains ("DATA") {
result = result .. upper.len () .. ","
}
}
return result.len ()
}
func bash_word_stats (n) {
total_len = 0
word_count = 0
for i in range (n) {
words = "alpha beta gamma delta epsilon zeta eta theta"
foreach word in words.split (" ") {
total_len = total_len + word.len ()
word_count = word_count + 1
}
}
return total_len
}
func bash_build_csv (rows, cols) {
result = ""
for r in range (rows) {
for c in range (cols) {
val = (r * cols + c) * 13 % 1000
result = result .. val
if c < cols - 1 {
result = result .. ","
}
}
result = result .. "\n"
}
return result.len ()
}
func bash_search_pattern (n) {
count = 0
for i in range (n) {
text = "error_log_" .. i .. "_warning_" .. (i % 100) .. "_info"
if text.contains ("warning") {
count = count + 1
}
if text.contains ("error") {
count = count + 1
}
if text.contains ("info") {
count = count + 1
}
}
return count
}
func bash_concat_heavy (n) {
s = ""
for i in range (n) {
s = s .. "x"
}
return s.len ()
}
# Main
print ("Heavy String Benchmark")
print ("======================")
print ("")
mode = "both"
if mode == "awk" {
print ("Running AWK version...")
print (" process_lines(5000): {awk_process_lines (5000)}")
print (" word_stats(3000): {awk_word_stats (3000)}")
print (" build_csv(200,50): {awk_build_csv (200, 50)}")
print (" search_pattern(10000): {awk_search_pattern (10000)}")
print (" concat_heavy(10000): {awk_concat_heavy (10000)}")
} else if mode == "bash" {
print ("Running BASH version...")
print (" process_lines(5000): {bash_process_lines (5000)}")
print (" word_stats(3000): {bash_word_stats (3000)}")
print (" build_csv(200,50): {bash_build_csv (200, 50)}")
print (" search_pattern(10000): {bash_search_pattern (10000)}")
print (" concat_heavy(10000): {bash_concat_heavy (10000)}")
} else {
print ("Running both versions...")
print ("")
print ("AWK:")
print (" process_lines(5000): {awk_process_lines (5000)}")
print (" word_stats(3000): {awk_word_stats (3000)}")
print (" build_csv(200,50): {awk_build_csv (200, 50)}")
print (" search_pattern(10000): {awk_search_pattern (10000)}")
print (" concat_heavy(10000): {awk_concat_heavy (10000)}")
print ("")
print ("BASH:")
print (" process_lines(5000): {bash_process_lines (5000)}")
print (" word_stats(3000): {bash_word_stats (3000)}")
print (" build_csv(200,50): {bash_build_csv (200, 50)}")
print (" search_pattern(10000): {bash_search_pattern (10000)}")
print (" concat_heavy(10000): {bash_concat_heavy (10000)}")
}
print ("")
print ("Done!")
# Heavy string benchmark - AWK only
@awk
func awk_process_lines (n) {
result = ""
for i in range (n) {
line = "item_" .. i .. "_data_" .. (i * 7) .. "_end"
upper = line.upper ()
if upper.contains ("DATA") {
result = result .. upper.len () .. ","
}
}
return result.len ()
}
@awk
func awk_word_stats (n) {
total_len = 0
word_count = 0
for i in range (n) {
words = "alpha beta gamma delta epsilon zeta eta theta"
num = words.split (" ")
for j in range (1, num + 1) {
word = __split_arr[j]
total_len += word.len ()
word_count += 1
}
}
return total_len
}
@awk
func awk_build_csv (rows, cols) {
result = ""
for r in range (rows) {
for c in range (cols) {
val = (r * cols + c) * 13 % 1000
result = result .. val
if c < cols - 1 {
result = result .. ","
}
}
result = result .. "\n"
}
return result.len ()
}
@awk
func awk_search_pattern (n) {
count = 0
for i in range (n) {
text = "error_log_" .. i .. "_warning_" .. (i % 100) .. "_info"
if text.contains ("warning") {
count += 1
}
if text.contains ("error") {
count += 1
}
if text.contains ("info") {
count += 1
}
}
return count
}
@awk
func awk_concat_heavy (n) {
s = ""
for i in range (n) {
s = s .. "x"
}
return s.len ()
}
print ("=== AWK String Benchmark ===")
print ("process_lines(5000): {awk_process_lines (5000)}")
print ("word_stats(3000): {awk_word_stats (3000)}")
print ("build_csv(200,50): {awk_build_csv (200, 50)}")
print ("search_pattern(10000): {awk_search_pattern (10000)}")
print ("concat_heavy(10000): {awk_concat_heavy (10000)}")
print ("Done!")
# Heavy string benchmark - BASH only
func bash_process_lines (n) {
result = ""
for i in range (n) {
line = "item_" .. i .. "_data_" .. (i * 7) .. "_end"
upper = line.upper ()
if upper.contains ("DATA") {
result = result .. upper.len () .. ","
}
}
return result.len ()
}
func bash_word_stats (n) {
total_len = 0
word_count = 0
for i in range (n) {
words = "alpha beta gamma delta epsilon zeta eta theta"
foreach word in words.split (" ") {
total_len = total_len + word.len ()
word_count = word_count + 1
}
}
return total_len
}
func bash_build_csv (rows, cols) {
result = ""
for r in range (rows) {
for c in range (cols) {
val = (r * cols + c) * 13 % 1000
result = result .. val
if c < cols - 1 {
result = result .. ","
}
}
result = result .. "\n"
}
return result.len ()
}
func bash_search_pattern (n) {
count = 0
for i in range (n) {
text = "error_log_" .. i .. "_warning_" .. (i % 100) .. "_info"
if text.contains ("warning") {
count = count + 1
}
if text.contains ("error") {
count = count + 1
}
if text.contains ("info") {
count = count + 1
}
}
return count
}
func bash_concat_heavy (n) {
s = ""
for i in range (n) {
s = s .. "x"
}
return s.len ()
}
print ("=== BASH String Benchmark ===")
print ("process_lines(5000): {bash_process_lines (5000)}")
print ("word_stats(3000): {bash_word_stats (3000)}")
print ("build_csv(200,50): {bash_build_csv (200, 50)}")
print ("search_pattern(10000): {bash_search_pattern (10000)}")
print ("concat_heavy(10000): {bash_concat_heavy (10000)}")
print ("Done!")
# Speed benchmark: @awk vs bash
# Measure actual execution time
@awk
func awk_fib (n) {
a = 0
b = 1
for i in range (n) {
tmp = a
a = b
b = tmp + b
}
return a
}
@awk
func awk_sum (n) {
total = 0
for i in range (1, n + 1) {
total += i
}
return total
}
@awk
func awk_primes (max) {
count = 0
for n in range (2, max) {
is_prime = 1
for i in range (2, n) {
if n % i == 0 {
is_prime = 0
break
}
}
if is_prime == 1 {
count += 1
}
}
return count
}
# Main - run AWK benchmarks multiple times
print ("@awk Benchmark Results:")
print ("=======================")
# Warmup
awk_fib (10)
awk_sum (10)
# Run tests
iterations = 100
print ("fib(30) x {iterations}:")
for i in range (iterations) {
awk_fib (30)
}
print (" Done")
print ("sum(1000) x {iterations}:")
for i in range (iterations) {
awk_sum (1000)
}
print (" Done")
print ("primes(100) x 10:")
for i in range (10) {
awk_primes (100)
}
print (" Done")
print ("")
print ("Results verification:")
print (" fib(30) = {awk_fib (30)}")
print (" sum(1000) = {awk_sum (1000)}")
print (" primes(100) = {awk_primes (100)}")
# Speed benchmark: pure Bash (no @awk)
# Measure actual execution time
func bash_fib (n) {
a = 0
b = 1
for i in range (n) {
c = a + b
a = b
b = c
}
return a
}
func bash_sum (n) {
total = 0
for i in range (1, n + 1) {
total = total + i
}
return total
}
func bash_primes (max) {
count = 0
for n in range (2, max) {
is_prime = 1
for i in range (2, n) {
if n % i == 0 {
is_prime = 0
break
}
}
if is_prime == 1 {
count = count + 1
}
}
return count
}
# Main - run Bash benchmarks multiple times
print ("Pure Bash Benchmark Results:")
print ("============================")
# Warmup
bash_fib (10)
bash_sum (10)
# Run tests
iterations = 100
print ("fib(30) x {iterations}:")
for i in range (iterations) {
bash_fib (30)
}
print (" Done")
print ("sum(1000) x {iterations}:")
for i in range (iterations) {
bash_sum (1000)
}
print (" Done")
print ("primes(100) x 10:")
for i in range (10) {
bash_primes (100)
}
print (" Done")
print ("")
print ("Results verification:")
print (" fib(30) = {bash_fib (30)}")
print (" sum(1000) = {bash_sum (1000)}")
print (" primes(100) = {bash_primes (100)}")
# Benchmark: @awk vs pure bash string operations
# ========== AWK versions ==========
@awk
func awk_count_words (text) {
count = 0
n = text.split (" ")
for i in range (1, n + 1) {
count += 1
}
return count
}
@awk
func awk_sum_numbers (text) {
total = 0
n = text.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
@awk
func awk_transform (text) {
result = ""
n = text.split (" ")
for i in range (1, n + 1) {
word = __split_arr[i]
upper = word.upper ()
result = result .. upper
if i < n {
result = result .. "-"
}
}
return result
}
@awk
func awk_stats (text) {
total = 0
count = 0
min = 999999999
max = -999999999
n = text.split (" ")
for i in range (1, n + 1) {
val = __split_arr[i]
total += val
count += 1
if val < min {
min = val
}
if val > max {
max = val
}
}
avg = total / count
return sprintf ("sum=%d count=%d min=%d max=%d avg=%.2f", total, count, min, max, avg)
}
# ========== Bash versions ==========
func bash_count_words (text) {
count = 0
foreach word in text.split (" ") {
count += 1
}
return count
}
func bash_sum_numbers (text) {
total = 0
foreach num in text.split (" ") {
total += num
}
return total
}
func bash_transform (text) {
result = ""
words = text.split (" ")
foreach i, word in words {
result = result .. word.upper ()
if i < words.len () - 1 {
result = result .. "-"
}
}
return result
}
func bash_stats (text) {
total = 0
count = 0
min = 999999999
max = -999999999
foreach num in text.split (" ") {
total += num
count += 1
if num < min {
min = num
}
if num > max {
max = num
}
}
avg = total / count
return "sum={total} count={count} min={min} max={max} avg={avg}"
}
# ========== Generate test data ==========
func generate_words (n) {
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
result = ""
for i in range (n) {
idx = i % 7
result = result .. words[idx]
if i < n - 1 {
result = result .. " "
}
}
return result
}
func generate_numbers (n) {
result = ""
for i in range (n) {
num = (i * 17 + 31) % 1000
result = result .. num
if i < n - 1 {
result = result .. " "
}
}
return result
}
# ========== Benchmark runner ==========
func benchmark (name, iterations) {
print ("=== {name} ===")
print ("Iterations: {iterations}")
print ("")
}
# Main
print ("ContenT @awk vs Bash Benchmark")
print ("==============================")
print ("")
# Generate test data
word_data = generate_words (100)
num_data = generate_numbers (100)
print ("Test data: 100 words, 100 numbers")
print ("")
# Warmup
awk_count_words (word_data)
bash_count_words (word_data)
# Run benchmarks
iterations = 50
print ("Running {iterations} iterations of each function...")
print ("")
# Count words benchmark
print ("1. Count Words:")
print (" AWK: Run 'time' externally to measure")
print (" Bash: Run 'time' externally to measure")
# Show sample output
print ("")
print ("Sample outputs:")
print (" awk_count_words: {awk_count_words (word_data)}")
print (" bash_count_words: {bash_count_words (word_data)}")
print (" awk_sum_numbers: {awk_sum_numbers (num_data)}")
print (" bash_sum_numbers: {bash_sum_numbers (num_data)}")
print (" awk_transform (5 words): {awk_transform (generate_words (5))}")
print (" bash_transform (5 words): {bash_transform (generate_words (5))}")
print (" awk_stats: {awk_stats (num_data)}")
print (" bash_stats: {bash_stats (num_data)}")
# Class method decorators example
class Calculator {
value = 0
construct (initial = 0) {
this.value = initial
}
@log
func add (x) {
this.value += x
return this.value
}
@cache (ttl = 60)
func expensiveCompute (x) {
print ("Computing {x}...")
return x * x
}
@retry (attempts = 3, delay = 1)
func unreliableOp () {
print ("Trying unreliable operation...")
return "success"
}
# @awk method - no access to 'this', pass data as params
@awk
func fastSum (numbers) {
total = 0
n = numbers.split (" ")
for i in range (1, n + 1) {
total += __split_arr[i]
}
return total
}
}
# Test
calc = Calculator (10)
print ("Testing @log decorator on method:")
result = calc.add (5)
print ("Result: {result}")
print ("")
print ("Testing @cache decorator on method:")
result = calc.expensiveCompute (7)
print ("First call: {result}")
result = calc.expensiveCompute (7)
print ("Cached call: {result}")
print ("")
print ("Testing @awk decorator on method:")
result = calc.fastSum ("1 2 3 4 5")
print ("Sum of 1-5: {result}")
# Classes example
class Logger {
level = "INFO"
prefix = ""
construct (level = "INFO") {
this.level = level
}
func log (msg) {
print ("[{this.level}] {msg}")
}
func setLevel (level) {
this.level = level
}
}
# Create instance
logger = Logger ("DEBUG")
logger.log ("Application started")
logger.setLevel ("INFO")
logger.log ("Running...")
# cli.ct - Class-based CLI library (inspired by urfave/cli v3)
# ============================================
# Flag classes
# ============================================
class Flag {
name = ""
short = ""
usage = ""
construct (name, usage) {
this.name = name
this.usage = usage
}
func with_short (short) {
this.short = short
return this
}
}
class StringFlag : Flag {
value = ""
construct (name, value, usage) {
base (name, usage)
this.value = value
}
}
class BoolFlag : Flag {
value = "false"
construct (name, usage) {
base (name, usage)
this.value = "false"
}
}
class IntFlag : Flag {
value = "0"
construct (name, value, usage) {
base (name, usage)
this.value = value
}
}
# ============================================
# Command class
# ============================================
class Command {
name = ""
usage = ""
version = ""
category = ""
aliases = []
flags = []
commands = []
_flag_values = {}
_args = []
_matched_cmd = ""
construct (name, usage) {
this.name = name
this.usage = usage
}
# Builder methods
func with_version (v) {
this.version = v
return this
}
func with_category (cat) {
this.category = cat
return this
}
func add_flag (flag) {
this.flags.push (flag)
# Set default value
this._flag_values.set (flag.name, flag.value)
return this
}
func add_command (cmd) {
this.commands.push (cmd)
return this
}
# Flag value getters
func string (name) {
return this._flag_values.get (name)
}
func bool (name) {
v = this._flag_values.get (name)
return v == "true"
}
func int (name) {
return this._flag_values.get (name)
}
# Args access
func args () {
return this._args
}
func arg (index) {
return this._args.get (index)
}
func narg () {
return this._args.len ()
}
# Get matched subcommand name
func matched () {
return this._matched_cmd
}
# Find flag by name or short
func _find_flag (name_or_short) {
num_flags = this.flags.len ()
i = 0
while i < num_flags {
flag = this.flags.get (i)
if flag.name == name_or_short {
return flag
}
if flag.short == name_or_short {
return flag
}
i = i + 1
}
return ""
}
# Find subcommand by name or alias
func _find_command (name) {
num_cmds = this.commands.len ()
i = 0
while i < num_cmds {
cmd = this.commands.get (i)
if cmd.name == name {
return cmd
}
# Check aliases
num_aliases = cmd.aliases.len ()
j = 0
while j < num_aliases {
alias = cmd.aliases.get (j)
if alias == name {
return cmd
}
j = j + 1
}
i = i + 1
}
return ""
}
# Parse command line arguments
func _parse () {
argc = args.count ()
i = 0
while i < argc {
arg = args.get (i)
# Long flag: --name=value or --name value
if arg.starts ("--") {
flag_part = arg.substr (2, 100)
if flag_part.contains ("=") {
eq_pos = flag_part.index ("=")
flag_name = flag_part.substr (0, eq_pos)
flag_value = flag_part.substr (eq_pos + 1, 100)
flag = this._find_flag (flag_name)
if flag != "" {
this._flag_values.set (flag.name, flag_value)
}
} else {
flag = this._find_flag (flag_part)
if flag != "" {
# Bool flag doesn't need value
if flag.value == "false" {
this._flag_values.set (flag.name, "true")
} else {
i = i + 1
if i < argc {
flag_value = args.get (i)
this._flag_values.set (flag.name, flag_value)
}
}
}
}
} else if arg.starts ("-") {
# Short flag: -n value or -n (for bool)
flag_short = arg.substr (1, 10)
flag = this._find_flag (flag_short)
if flag != "" {
# Bool flag doesn't need value
if flag.value == "false" {
this._flag_values.set (flag.name, "true")
} else {
i = i + 1
if i < argc {
flag_value = args.get (i)
this._flag_values.set (flag.name, flag_value)
}
}
}
} else {
# Positional argument
this._args.push (arg)
}
i = i + 1
}
}
# Print help
func help () {
if this.version != "" {
print ("{this.name} v{this.version}")
} else {
print (this.name)
}
if this.usage != "" {
print (this.usage)
}
print ("")
print ("USAGE:")
print (" {this.name} [flags] [command] [args...]")
print ("")
# Print flags
num_flags = this.flags.len ()
if num_flags > 0 {
print ("FLAGS:")
i = 0
while i < num_flags {
flag = this.flags.get (i)
if flag.short != "" {
print (" --{flag.name}, -{flag.short}")
} else {
print (" --{flag.name}")
}
print (" {flag.usage} (default: {flag.value})")
i = i + 1
}
print ("")
}
# Print commands (grouped by category)
num_cmds = this.commands.len ()
if num_cmds > 0 {
print ("COMMANDS:")
# First, print uncategorized commands
i = 0
while i < num_cmds {
cmd = this.commands.get (i)
if cmd.category == "" {
print (" {cmd.name}")
print (" {cmd.usage}")
}
i = i + 1
}
# Collect and print categorized commands
categories = []
i = 0
while i < num_cmds {
cmd = this.commands.get (i)
if cmd.category != "" {
# Check if category already in list
found = 0
j = 0
num_cats = categories.len ()
while j < num_cats {
cat = categories.get (j)
if cat == cmd.category {
found = 1
}
j = j + 1
}
if found == 0 {
categories.push (cmd.category)
}
}
i = i + 1
}
# Print each category
num_cats = categories.len ()
c = 0
while c < num_cats {
cat = categories.get (c)
print ("")
print (" {cat}:")
i = 0
while i < num_cmds {
cmd = this.commands.get (i)
if cmd.category == cat {
print (" {cmd.name}")
print (" {cmd.usage}")
}
i = i + 1
}
c = c + 1
}
}
}
# Run the command
func run () {
this._parse ()
# Check for help flag (built-in)
help_flag = this._find_flag ("help")
if help_flag != "" {
h = this.bool ("help")
if h {
this.help ()
return ""
}
}
# Check for version flag (built-in)
version_flag = this._find_flag ("version")
if version_flag != "" {
v = this.bool ("version")
if v {
print ("{this.name} v{this.version}")
return ""
}
}
# Find subcommand from first positional arg
if this.narg () > 0 {
cmd_name = this.arg (0)
subcmd = this._find_command (cmd_name)
if subcmd != "" {
this._matched_cmd = subcmd.name
# Remove command name from args and copy rest to subcommand
i = 1
while i < this.narg () {
a = this.arg (i)
subcmd._args.push (a)
i = i + 1
}
return subcmd.name
} else {
# Unknown command
this._matched_cmd = cmd_name
return cmd_name
}
}
return ""
}
}
# ============================================
# Convenience constructors
# ============================================
func new_app (name, usage) {
cmd = new Command (name, usage)
# Add built-in flags
help_flag = new BoolFlag ("help", "Show help")
help_flag.with_short ("h")
cmd.add_flag (help_flag)
version_flag = new BoolFlag ("version", "Show version")
version_flag.with_short ("v")
cmd.add_flag (version_flag)
return cmd
}
func new_command (name, usage) {
return new Command (name, usage)
}
func new_string_flag (name, value, usage) {
return new StringFlag (name, value, usage)
}
func new_bool_flag (name, usage) {
return new BoolFlag (name, usage)
}
func new_int_flag (name, value, usage) {
return new IntFlag (name, value, usage)
}
# main.ct - Example app using class-based cli.ct library
# Similar to urfave/cli v3 style
# Create app with built-in help and version flags
app = new_app ("myapp", "A sample CLI application")
app.with_version ("1.0.0")
# Add custom flags
name_flag = new_string_flag ("name", "World", "Name to greet")
name_flag.with_short ("n")
app.add_flag (name_flag)
count_flag = new_int_flag ("count", "1", "Number of times to greet")
count_flag.with_short ("c")
app.add_flag (count_flag)
loud_flag = new_bool_flag ("loud", "Use uppercase")
loud_flag.with_short ("l")
app.add_flag (loud_flag)
# Create commands
greet_cmd = new_command ("greet", "Greet someone")
app.add_command (greet_cmd)
calc_cmd = new_command ("calc", "Simple calculator")
calc_cmd.with_category ("math")
app.add_command (calc_cmd)
add_cmd = new_command ("add", "Add two numbers")
add_cmd.with_category ("math")
app.add_command (add_cmd)
# Run and get matched command
cmd = app.run ()
# Handle commands
when cmd {
"greet" {
name = app.string ("name")
count = app.int ("count")
loud = app.bool ("loud")
i = 0
while i < count {
if loud {
print ("HELLO, {name}!")
} else {
print ("Hello, {name}!")
}
i = i + 1
}
}
"calc" {
if calc_cmd.narg () < 3 {
print ("Usage: myapp calc <num1> <op> <num2>")
print ("Example: myapp calc 10 + 5")
} else {
# Args are in the subcommand
a = calc_cmd.arg (0)
op = calc_cmd.arg (1)
b = calc_cmd.arg (2)
when op {
"+" {
result = a + b
print ("{a} + {b} = {result}")
}
"-" {
result = a - b
print ("{a} - {b} = {result}")
}
"x" {
result = a * b
print ("{a} * {b} = {result}")
}
"/" {
result = a / b
print ("{a} / {b} = {result}")
}
else {
print ("Unknown operator: {op}")
}
}
}
}
"add" {
if add_cmd.narg () < 2 {
print ("Usage: myapp add <num1> <num2>")
} else {
a = add_cmd.arg (0)
b = add_cmd.arg (1)
result = a + b
print ("{a} + {b} = {result}")
}
}
"" {
# No command - show help
app.help ()
}
else {
print ("Unknown command: {cmd}")
app.help ()
}
}
# Decorators example
@retry (attempts = 3, delay = 1)
func fetchData (url) {
print ("Fetching: {url}")
return http.get (url)
}
@log
func processData (data) {
print ("Processing: {data}")
return data
}
@cache (ttl = 60)
func expensiveOperation (x) {
print ("Computing for {x}...")
return x
}
# Test decorators
result = expensiveOperation (42)
print ("Result: {result}")
result = expensiveOperation (42)
print ("Cached result: {result}")
# Defer example
func processFile (path) {
print ("Opening file: {path}")
f = fs.read (path)
defer print ("Cleanup: closing file")
defer print ("Cleanup: releasing resources")
print ("Processing file content...")
print ("File content: {f}")
return "done"
}
# Test
result = processFile ("/etc/hostname")
print ("Result: {result}")
# Exception handling example
# Simple error handling demonstration
print ("=== Exception Handling Demo ===")
print ("")
# Example 1: Direct try/except (not in function)
print ("Test 1: Reading non-existent file")
try {
data = fs.read ("/etc/myapp/nonexistent.json")
print ("Data: {data}")
} except e {
print ("Caught error: {e}")
}
print ("")
print ("Test 2: Reading existing file")
try {
data = fs.read ("/etc/hostname")
print ("Hostname: {data}")
} except e {
print ("Error: {e}")
}
print ("")
print ("Test 3: Finally block")
try {
print ("In try block")
x = 1
} except e {
print ("This should not print")
} finally {
print ("Finally always runs")
}
print ("")
print ("=== Done ===")
# Hello World example
name = "World"
print ("Hello, {name}!")
# Function example
func greet (name, greeting = "Hello") {
print ("{greeting}, {name}!")
}
greet ("Alice")
greet ("Bob", "Hi")
# Loop example
foreach i in range (5) {
print ("Count: {i}")
}
# HTTP API example
func fetchUser (id) {
url = "https://jsonplaceholder.typicode.com/users/{id}"
response = http.get (url)
return response
}
func createPost (title, body, userId) {
data = json.stringify ({
"title": title,
"body": body,
"userId": userId
})
response = http.post ("https://jsonplaceholder.typicode.com/posts", data)
return response
}
# Fetch user
print ("Fetching user 1...")
user = fetchUser (1)
print ("User data:")
print (user)
# Create post
print ("Creating new post...")
post = createPost ("My Post", "This is content", 1)
print ("Created post:")
print (post)
# Lambdas example
# Single parameter lambda
double = x => x * 2
# Multiple parameters lambda
add = (a, b) => a + b
# Lambda with block
process = item => {
print ("Processing: {item}")
result = item * 10
return result
}
# Test lambdas
print ("double(5) = ")
print (double (5))
print ("add(3, 4) = ")
print (add (3, 4))
print ("process(7) = ")
print (process (7))
# main.ct - Main program (uses utils.ct)
# Use functions from utils.ct
greet ("World")
greet ("ContenT")
result = add (10, 20)
print ("10 + 20 = {result}")
# Use class from utils.ct
counter = Counter (5)
print ("Initial: {counter.get ()}")
counter.increment ()
counter.increment ()
print ("After 2 increments: {counter.get ()}")
# utils.ct - Utility functions
func greet (name) {
print ("Hello, {name}!")
}
func add (a, b) {
return a + b
}
class Counter {
value = 0
construct (initial = 0) {
this.value = initial
}
func increment () {
this.value += 1
return this.value
}
func get () {
return this.value
}
}
# Test shell-like pipe
print ("=== Shell-like pipe test ===")
files = shell.exec ("echo -e 'file1.txt\nfile2.txt\nfile3.ct'") | shell.exec ("grep ct")
print ("Files with .ct: {files}")
# Test multiple pipes
count = shell.exec ("echo -e 'a\nb\nc\nd\ne'") | shell.exec ("grep -v a") | shell.exec ("wc -l")
print ("Count (should be 4): {count}")
# Test functional pipe
func double (x) {
return x * 2
}
func add_ten (x) {
return x + 10
}
# 5 | double | add_ten = add_ten(double(5)) = add_ten(10) = 20
result = 5 | double | add_ten
print ("5 | double | add_ten = {result}")
print ("=== Done ===")
# Test when statement
func testWhen (value) {
when value {
1 {
print ("one")
}
2, 3 {
print ("two or three")
}
else {
print ("other")
}
}
}
func testWhenRange (value) {
when value {
1 {
print ("one")
}
2..5 {
print ("two to five")
}
6, 7, 8 {
print ("six, seven or eight")
}
9..20 {
print ("nine to twenty")
}
else {
print ("out of range")
}
}
}
# Test simple when (no ranges - uses case)
print ("Testing simple when:")
testWhen (1)
testWhen (2)
testWhen (3)
testWhen (5)
print ("")
print ("Testing when with ranges:")
testWhenRange (1)
testWhenRange (3)
testWhenRange (7)
testWhenRange (15)
testWhenRange (100)
# Test when statement in @awk functions
@awk
func categorize (value) {
when value {
1 {
return "one"
}
2, 3 {
return "few"
}
4..10 {
return "several"
}
else {
return "many"
}
}
}
print (categorize (1))
print (categorize (2))
print (categorize (7))
print (categorize (100))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment