commit 762af99f1d4f2752e6988b347ebb529882f8b76b Author: Faynot Date: Sun May 17 15:18:28 2026 +0300 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..5748687 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "glint" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..893433d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "glint" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/README.md b/README.md new file mode 100644 index 0000000..df74715 --- /dev/null +++ b/README.md @@ -0,0 +1,694 @@ +

DumbShot

+

A specialized, statically typed markup, styling, and state management language created exclusively for Eclipse DE

+ +## About Glint + +Unlike traditional configuration files (JSON, TOML, YAML) or heavyweight embedded languages (Lua, JS), Glint is designed as the live source code of the graphical shell itself. It parses in nanoseconds, compiles to compact bytecode on the fly, and allows for rebuilding the DE interface in real time without a system restart. + +## Philosophy "Source-as-Configuration" + +Eclipse doesn't have a concept of "default settings" in the form of hidden binary code. Everything you see on the screen, from the tray corner radius to the desktop layout logic, is written in Glint files. (`.gltm`, `.glts` and bytecode - `.glbc`) + +- **Hot-Reload**: Any change in the `.gltm`/`.glts` file is instantly picked up, compiled into '.glbc' and rendered at runtime. +- **Crash resistance**: If the user makes a syntax or logic error, Glint will automatically roll back to the last working state from the bytecode cache. The system fundamentally cannot crash due to an incorrect configuration. Eclipse itself is a framework for writing Glint code to create a DE, although it has its own base source code, allowing you to enjoy the DE and use your PC like GNOME or KDE Plasma. +- **Who is Glint for?**: Knowing Glint is necessary for advanced users who want full control over their DE, however, no one forbids the use of the unmodified Eclipse DE + +## Architecture +The language is designed with a focus on maximum predictability, determinism, and performance of the native application layer on 'iced' (Rust). + +### Sigil system +| Symbol | Type | Description | +| --- | --- | --- | +| `@` | Directive | Single symbol → instant dispatch | +| `$` | Varialbe | Distinguishes from item names and strings | +| `!rhei` | call Rhei | '!' does not occur in names; The body is transmitted as-is | +| `//` | Comment | Two-character check | +| `"…"` | String | An unambiguous beginning and end; escape via '\' | +| `#RRGGBB` | Color | Only in the value position; parsed for 7 bytes | +| `fs:/…` | FS-path | URI scheme; Recognized in 3 characters (f,s,:) | +| Capital letter | Element | Distinguishes from directives and keywords | +| `0-9 / -` | Integer | The first character uniquely indicates the numeric type | + +The parser spends **zero time** determining the type of token. It doesn't need to symbolically compare strings like `if`, `let`, or `function`. + +### 2. Separation of scopes '()' and '{}' +* Parentheses '(...)' contain **only** the properties of the element in the format 'key=value'. +* Curly braces '{...}' contain **only** child elements and directives. + +### 3. Native protocols +Instead of calling heavy functions like 'readFile("/path")' that require argument parsing in runtime, Glint uses built-in prefixes: +```gltm +Image(src=fs:/usr/share/backgrounds/wallpaper.png) +``` + +## Bytecode + +Glint does not interpret pure text while DE is running. It compiles it into a compact binary bytecode. Each UI element is translated into `ELEM_PUSH`/`ELEM_POP` instructions. Each property is converted into a typed opcode of a fixed width (`PROP_INT`, `PROP_STR`, `PROP_COLOR`). + +This allows the Render Hot-Path to run without memory allocations at all + +## Syntax example +```gltm +@version 1 +@style "desktop.glts" + +@global $username = !rhei: os.env("USER") +@global $hostname = !rhei: os.hostname() +@global $locale = "ru_RU" +@global $scaleFactor = 1.0 + +@singleton Config { + wallpaper = fs:/home/$username/.config/de/wallpaper.jpg + wallpaperFit = "cover" + iconTheme = "papirus-dark" + fontMain = "Inter" + fontMono = "JetBrains Mono" + fontSize = 13 + workspaces = 4 + animEnabled = true + accentColor = #cba6f7 + taskbarPos = "bottom" +} + +@singleton SystemState { + battery = !rhei: sys.battery() + volume = !rhei: sys.volume.get() + brightness = !rhei: sys.brightness.get() + network = !rhei: sys.network.status() + timezone = !rhei: os.timezone() +} + +@component DesktopIcon(label: str, icon: fspath, exec: str) { + Button(class="desktop-icon") { + @on click { + !rhei: process.spawn($exec) + } + @on dblclick { + !rhei { + process.spawn($exec) + wm.raise(process.lastPid()) + } + } + Image(src=$icon, class="icon-img") {} + Label(class="icon-label") $label + } +} + +@component BatteryWidget { + @if $SystemState.battery.present { + @let $lvl = $SystemState.battery.level + @let $ico = !rhei: icons.battery($lvl) + + Panel(class="tray-item") { + Icon(src=$ico, class="tray-icon") {} + @if $SystemState.battery.charging { + Icon(src=fs:/usr/share/eclipse/icons/charging.svg, + class="tray-icon tray-icon--accent") {} + } + } + } +} + +@component ClockWidget { + @let $time = !rhei: sys.time.format("%H:%M", $SystemState.timezone) + @let $date = !rhei: sys.time.format("%d %b", $SystemState.timezone) + + Panel(class="clock-widget") { + @on click { + !rhei: ui.toggle("calendar-popup") + } + Label(class="clock-time") $time + Label(class="clock-date") $date + } +} + +@component SystemTray { + Panel(id="system-tray", class="tray") { + BatteryWidget {} + + @if $SystemState.network.connected { + Icon(class="tray-icon", + src=!rhei: icons.network($SystemState.network.type)) {} + } @else { + Icon(class="tray-icon tray-icon--warn", + src=fs:/usr/share/eclipse/icons/net-offline.svg) {} + } + + Slider(id="vol-slider", class="tray-slider", + value=$SystemState.volume, min=0, max=100) { + @on change { + !rhei: sys.volume.set($self.value) + } + } + + ClockWidget {} + } +} + +Screen(id="root", width=1920, height=1080, scale=$scaleFactor) { + + Wallpaper(id="bg", + src=$Config.wallpaper, + fallback=fs:/usr/share/eclipse/wallpapers/default.jpg, + fit=$Config.wallpaperFit, + watch=true) {} + + Panel(id="desktop", class="desktop") { + @let $desktopFiles = !rhei: fs.glob("/home/$username/Desktop/*.desktop") + + @each $f in $desktopFiles { + @let $entry = !rhei: xdg.parseDesktop($f) + DesktopIcon( + label=$entry.name, + icon=!rhei: icons.resolve($entry.icon, $Config.iconTheme), + exec=$entry.exec + ) {} + } + + @on contextmenu { + !rhei: ui.show("desktop-ctx") + } + } + + ContextMenu(id="desktop-ctx", class="ctx-menu", visible=false) { + MenuItem(class="ctx-item") { + @on click { !rhei: ui.show("settings") } + "Settings" + } + MenuItem(class="ctx-item") { + @on click { !rhei: wallpaper.showPicker() } + "Change wallpaper" + } + MenuDivider {} + MenuItem(class="ctx-item ctx-item--danger") { + @on click { !rhei: session.logout() } + "Logout" + } + } + + Panel(id="taskbar", class="taskbar") { + + Button(id="launcher-btn", class="launcher-button") { + @on click { !rhei: ui.toggle("app-launcher") } + Image(src=fs:/usr/share/eclipse/logo.svg) {} + } + + Panel(id="window-list", class="window-list") { + @let $wins = !rhei: wm.getWindows() + + @each $w in $wins { + Button(class="taskbar-win", data-wid=$w.id, + active=$w.focused) { + @on click { !rhei: wm.focus($w.id) } + @on middleclick { !rhei: wm.close($w.id) } + Icon(src=$w.icon, class="win-icon") {} + Label(class="win-title") $w.title + } + } + } + + SystemTray {} + } + + Overlay(id="app-launcher", class="launcher", visible=false) { + @on keydown(key="Escape") { + !rhei: ui.hide("app-launcher") + } + + Input(id="launcher-search", class="launcher-search", + placeholder="Search...", + autofocus=true) { + @on input { + !rhei: launcher.filter($self.value) + } + } + + Grid(id="app-grid", class="launcher-grid", columns=6) { + @let $apps = !rhei: apps.listAll() + + @each $app in $apps { + Button(class="launcher-app") { + @on click { + !rhei { + process.spawn($app.exec) + ui.hide("app-launcher") + } + } + Image(src=$app.icon, class="app-icon") {} + Label(class="app-name") $app.name + } + } + } + } + + Overlay(id="notif-layer", class="notif-layer") { + @let $notifs = !rhei: notifications.active() + + @each $n in $notifs { + Panel(class="notif-card", data-id=$n.id) { + Panel(class="notif-header") { + Icon(src=$n.appIcon, class="notif-icon") {} + Label(class="notif-app") $n.appName + Button(class="notif-close") { + @on click { !rhei: notifications.dismiss($n.id) } + "×" + } + } + Label(class="notif-title") $n.summary + @if $n.body { + Label(class="notif-body") $n.body + } + } + } + } + + @if !rhei: os.env("GLINT_DEV") { + !rhei { + debug.overlay.show() + debug.log("DE is init. User: " + $username) + debug.log("Singletones: Config, SystemState") + } + } +} +``` + +```glts +$bg = #1e1e2e +$bg-s0 = #313244 +$bg-s1 = #45475a +$text = #cdd6f4 +$text-dim = #a6adc8 +$accent = #cba6f7 +$accent-h = #b4befe +$red = #f38ba8 +$warn = #fab387 +$green = #a6e3a1 +$r = 8px +$r-sm = 4px +$taskbar-h = 36px +$t-fast = 120ms +$t-mid = 240ms + +@mixin flex-row { + display: flex + flex-direction: row + align-items: center +} + +@mixin flex-col { + display: flex + flex-direction: column + align-items: flex-start +} + +@mixin glass { + background: rgba(30, 30, 46, 0.88) + backdrop-filter: blur(14px) + border: 1px solid rgba(203, 166, 247, 0.15) +} + +@mixin shadow-sm { + box-shadow: 0 2px 8px rgba(0,0,0,0.45) +} + +@mixin shadow-lg { + box-shadow: 0 6px 24px rgba(0,0,0,0.65) +} + +@mixin btn-reset { + border: none + background: transparent + cursor: pointer + padding: 0 +} + +@anim fade-in { + from { opacity: 0; transform: scale(0.95) } + to { opacity: 1; transform: scale(1.0) } +} + +@anim slide-up { + from { opacity: 0; transform: translateY(10px) } + to { opacity: 1; transform: translateY(0) } +} + +@anim slide-down { + from { opacity: 0; transform: translateY(-10px) } + to { opacity: 1; transform: translateY(0) } +} + +@anim pulse-warn { + 0% { opacity: 1.0 } + 50% { opacity: 0.4 } + 100% { opacity: 1.0 } +} + +Screen { + font-family: $Config.fontMain + font-size: $Config.fontSizepx + color: $text + background: transparent +} + +Wallpaper { + position: absolute + inset: 0 + z-index: 0 + object-fit: cover +} + +Panel.desktop { + position: absolute + inset: 0 0 $taskbar-h 0 + z-index: 1 + padding: 16px + display: grid + grid-template-columns: repeat(auto-fill, 80px) + grid-template-rows: repeat(auto-fill, 88px) + align-content: start + gap: 8px +} + +Button.desktop-icon { + @use flex-col + @use btn-reset + + width: 76px + padding: 6px 4px + border-radius: $r-sm + border: 1px solid transparent + align-items: center + gap: 5px + transition: background $t-fast, border-color $t-fast +} + +Button.desktop-icon:hover { + background: rgba(203,166,247,0.12) + border-color: rgba(203,166,247,0.30) +} + +Button.desktop-icon:active { + background: rgba(203,166,247,0.22) + transform: scale(0.96) +} + +Button.desktop-icon > Image.icon-img { + width: 48px + height: 48px +} + +Button.desktop-icon > Label.icon-label { + font-size: 11px + color: $text + text-align: center + text-shadow: 0 1px 4px rgba(0,0,0,0.85) + max-width: 72px + overflow: ellipsis +} + +Panel.taskbar { + @use flex-row + @use glass + @use shadow-sm + + position: absolute + bottom: 0; left: 0 + width: 100% + height: $taskbar-h + z-index: 100 + padding: 0 8px + gap: 4px +} + +Button.launcher-button { + @use flex-row + @use btn-reset + + width: 30px + height: 28px + border-radius: $r-sm + padding: 5px + transition: background $t-fast +} + +Button.launcher-button:hover { background: rgba(203,166,247,0.20) } +Button.launcher-button:active { background: rgba(203,166,247,0.36) } + +Panel.window-list { + @use flex-row + flex: 1 + gap: 2px + height: 28px + overflow: hidden +} + +Button.taskbar-win { + @use flex-row + @use btn-reset + + max-width: 180px + height: 28px + padding: 0 8px + border-radius: $r-sm + background: rgba(255,255,255,0.06) + color: $text-dim + font-size: 12px + gap: 6px + overflow: hidden + transition: background $t-fast, color $t-fast +} + +Button.taskbar-win:hover { + background: rgba(255,255,255,0.12) + color: $text +} + +Button.taskbar-win[active=true] { + background: rgba(203,166,247,0.18) + color: $accent + border-bottom: 2px solid $accent +} + +Button.taskbar-win > Icon.win-icon { + width: 16px + height: 16px + flex-shrink: 0 +} + +Button.taskbar-win > Label.win-title { + white-space: nowrap + overflow: ellipsis +} + +Panel.tray { + @use flex-row + margin-left: auto + gap: 4px +} + +Panel.tray-item { @use flex-row; gap: 2px } + +Icon.tray-icon { + width: 16px + height: 16px + opacity: 0.82 + cursor: pointer + transition: opacity $t-fast +} + +Icon.tray-icon:hover { opacity: 1.0 } +Icon.tray-icon--accent { color: $green } +Icon.tray-icon--warn { + color: $warn + animation: pulse-warn 2s ease infinite +} + +Slider.tray-slider { + width: 68px + height: 4px + accent-color: $accent +} + +Panel.clock-widget { + @use flex-col + padding: 0 8px + cursor: pointer + gap: 0 + border-radius: $r-sm + transition: background $t-fast +} + +Panel.clock-widget:hover { background: rgba(255,255,255,0.07) } + +Label.clock-time { + font-family: $Config.fontMono + font-size: 13px + font-weight: 500 + color: $text + letter-spacing: 0.4px +} + +Label.clock-date { + font-size: 10px + color: $text-dim +} + +ContextMenu.ctx-menu { + @use glass + @use shadow-lg + + border-radius: $r + padding: 4px + min-width: 200px + animation: fade-in $t-fast ease +} + +MenuItem.ctx-item { + padding: 7px 12px + border-radius: $r-sm + font-size: 13px + color: $text + cursor: pointer + transition: background $t-fast +} + +MenuItem.ctx-item:hover { background: rgba(255,255,255,0.08) } +MenuItem.ctx-item--danger { color: $red } +MenuItem.ctx-item--danger:hover { background: rgba(243,139,168,0.12) } +MenuDivider { + height: 1px + background: rgba(255,255,255,0.08) + margin: 4px 0 +} + +Overlay.launcher { + @use glass + @use flex-col + @use shadow-lg + + position: absolute + bottom: $taskbar-h + left: 50% + transform: translateX(-50%) + width: 700px + max-height: 540px + border-radius: $r + padding: 16px + z-index: 200 + gap: 12px + animation: slide-up $t-mid ease +} + +Input.launcher-search { + width: 100% + height: 40px + background: rgba(255,255,255,0.06) + border: 1px solid rgba(203,166,247,0.25) + border-radius: $r-sm + padding: 0 14px + font-size: 14px + color: $text + outline: none + transition: border-color $t-fast, background $t-fast +} + +Input.launcher-search:focused { + border-color: $accent + background: rgba(255,255,255,0.09) +} + +Grid.launcher-grid { + width: 100% + grid-template-columns: repeat(6, 1fr) + gap: 8px + overflow-y: scroll + max-height: 420px + padding: 4px +} + +Button.launcher-app { + @use flex-col + @use btn-reset + + padding: 10px 6px + border-radius: $r-sm + border: 1px solid transparent + align-items: center + gap: 6px + transition: background $t-fast, border-color $t-fast + animation: fade-in $t-mid ease +} + +Button.launcher-app:hover { + background: rgba(203,166,247,0.12) + border-color: rgba(203,166,247,0.25) +} + +Button.launcher-app > Image.app-icon { + width: 44px; height: 44px +} + +Button.launcher-app > Label.app-name { + font-size: 11px + color: $text-dim + text-align: center + max-width: 80px + overflow: ellipsis +} + +Overlay.notif-layer { + @use flex-col + position: absolute + top: 12px; right: 12px + gap: 8px + z-index: 300 + max-width: 360px +} + +Panel.notif-card { + @use glass + @use flex-col + @use shadow-sm + + border-radius: $r + padding: 12px + gap: 4px + animation: slide-down $t-mid ease +} + +Panel.notif-header { + @use flex-row + gap: 6px + margin-bottom: 4px +} + +Icon.notif-icon { width: 16px; height: 16px } +Label.notif-app { font-size: 11px; color: $text-dim } +Label.notif-title { font-size: 13px; font-weight: 500; color: $text } +Label.notif-body { font-size: 12px; color: $text-dim; line-height: 1.5 } + +Button.notif-close { + @use btn-reset + margin-left: auto + color: $text-dim + font-size: 16px + line-height: 1 + transition: color $t-fast +} + +Button.notif-close:hover { color: $red } + +@if $Config.accentColor != #cba6f7 { + Button.desktop-icon:hover { + background: rgba($Config.accentColor, 0.12) + border-color: rgba($Config.accentColor, 0.30) + } + Button.taskbar-win[active=true] { + background: rgba($Config.accentColor, 0.18) + color: $Config.accentColor + border-bottom: 2px solid $Config.accentColor + } + Input.launcher-search:focused { border-color: $Config.accentColor } +} + +``` diff --git a/desktop.glbc b/desktop.glbc new file mode 100644 index 0000000..dc5c58e Binary files /dev/null and b/desktop.glbc differ diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..498ae43 Binary files /dev/null and b/logo.png differ diff --git a/src/ast.rs b/src/ast.rs new file mode 100644 index 0000000..b979f5d --- /dev/null +++ b/src/ast.rs @@ -0,0 +1,94 @@ +#![allow(dead_code)] + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum NodeId { + Element(u32), + Directive(u32), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + String(String), + Int(i64), + Float(f64), + Bool(bool), + Color(String), + FsPath(String), + Variable(String), + Rhei(String), +} + +#[derive(Debug, Clone)] +pub enum Directive { + Version(i64), + Style(String), + Global { + name: String, + value: Value, + }, + Singleton { + name: String, + prop_span: (u32, u32), + }, + Component { + name: String, + params: Vec<(String, String)>, + child_span: (u32, u32), + }, + Let { + name: String, + value: Value, + }, + If { + condition: Value, + child_span: (u32, u32), + else_span: Option<(u32, u32)>, + }, + Each { + item: String, + collection: Value, + child_span: (u32, u32), + }, + On { + event: String, + args: Vec<(String, Value)>, + child_span: (u32, u32), + }, + RheiBlock(String), +} + +#[derive(Debug, Default)] +pub struct ModuleSoA { + pub elem_types: Vec, + pub elem_prop_spans: Vec<(u32, u32)>, + pub elem_child_spans: Vec<(u32, u32)>, + pub elem_content: Vec>, + + pub prop_keys: Vec, + pub prop_values: Vec, + + pub directives: Vec, + + pub hierarchy: Vec, +} + +impl ModuleSoA { + pub fn new() -> Self { + Self::default() + } + + pub fn push_element(&mut self, typ: String) -> u32 { + let id = self.elem_types.len() as u32; + self.elem_types.push(typ); + self.elem_prop_spans.push((0, 0)); + self.elem_child_spans.push((0, 0)); + self.elem_content.push(None); + id + } + + pub fn push_directive(&mut self, dir: Directive) -> u32 { + let id = self.directives.len() as u32; + self.directives.push(dir); + id + } +} diff --git a/src/compiler.rs b/src/compiler.rs new file mode 100644 index 0000000..2df76ae --- /dev/null +++ b/src/compiler.rs @@ -0,0 +1,262 @@ +use crate::ast::*; +use crate::opcodes::*; + +pub struct Compiler<'a> { + module: &'a ModuleSoA, + buf: Vec, +} + +impl<'a> Compiler<'a> { + pub fn new(module: &'a ModuleSoA) -> Self { + Self { + module, + buf: Vec::new(), + } + } + + pub fn compile(mut self, root_nodes: &[NodeId]) -> Vec { + self.buf.extend_from_slice(&MAGIC_HEADER); + + self.compile_span(root_nodes); + + self.buf + } + + fn compile_span(&mut self, nodes: &[NodeId]) { + for node in nodes { + match node { + NodeId::Element(id) => self.compile_element(*id), + NodeId::Directive(id) => self.compile_directive(*id), + } + } + } + + fn compile_block(&mut self, span: (u32, u32)) { + let start = span.0 as usize; + let len = span.1 as usize; + let nodes = &self.module.hierarchy[start..start + len]; + self.compile_span(nodes); + self.buf.push(OP_END_BLOCK); + } + + fn compile_element(&mut self, id: u32) { + let idx = id as usize; + let typ = &self.module.elem_types[idx]; + + self.buf.push(OP_ELEM_PUSH); + self.write_string(typ); + + let (p_start, p_len) = self.module.elem_prop_spans[idx]; + for i in p_start..(p_start + p_len) { + let key = &self.module.prop_keys[i as usize]; + let val = &self.module.prop_values[i as usize]; + self.compile_property(key, val); + } + + if let Some(content) = &self.module.elem_content[idx] { + self.buf.push(OP_CONTENT); + self.compile_value(content); + } + + let child_span = self.module.elem_child_spans[idx]; + if child_span.1 > 0 { + self.compile_block(child_span); + } + + self.buf.push(OP_ELEM_POP); + } + + fn compile_directive(&mut self, id: u32) { + let dir = &self.module.directives[id as usize]; + match dir { + Directive::Version(v) => { + self.buf.push(OP_VERSION); + self.write_i64(*v); + } + Directive::Style(s) => { + self.buf.push(OP_STYLE); + self.write_string(s); + } + Directive::Global { name, value } => { + self.buf.push(OP_GLOBAL); + self.write_string(name); + self.compile_value(value); + } + Directive::Singleton { name, prop_span } => { + self.buf.push(OP_SINGLETON); + self.write_string(name); + self.write_u32(prop_span.1); + + let (start, len) = *prop_span; + for i in start..(start + len) { + let key = &self.module.prop_keys[i as usize]; + let val = &self.module.prop_values[i as usize]; + self.write_string(key); + self.compile_value(val); + } + } + Directive::Component { + name, + params, + child_span, + } => { + self.buf.push(OP_COMPONENT); + self.write_string(name); + self.write_u32(params.len() as u32); + for (pname, ptype) in params { + self.write_string(pname); + self.write_string(ptype); + } + self.compile_block(*child_span); + } + Directive::Let { name, value } => { + self.buf.push(OP_LET); + self.write_string(name); + self.compile_value(value); + } + Directive::If { + condition, + child_span, + else_span, + } => { + self.buf.push(OP_IF); + self.compile_value(condition); + self.compile_block(*child_span); + if let Some(es) = else_span { + self.buf.push(1); // Has else + self.compile_block(*es); + } else { + self.buf.push(0); // No else + } + } + Directive::Each { + item, + collection, + child_span, + } => { + self.buf.push(OP_EACH); + self.write_string(item); + self.compile_value(collection); + self.compile_block(*child_span); + } + Directive::On { + event, + args, + child_span, + } => { + self.buf.push(OP_ON); + self.write_string(event); + self.write_u32(args.len() as u32); + for (k, v) in args { + self.write_string(k); + self.compile_value(v); + } + self.compile_block(*child_span); + } + Directive::RheiBlock(code) => { + self.buf.push(OP_RHEI_BLK); + self.write_string(code); + } + } + } + + fn compile_property(&mut self, key: &str, val: &Value) { + match val { + Value::String(s) => { + self.buf.push(OP_PROP_STR); + self.write_string(key); + self.write_string(s); + } + Value::Int(i) => { + self.buf.push(OP_PROP_INT); + self.write_string(key); + self.write_i64(*i); + } + Value::Float(f) => { + self.buf.push(OP_PROP_FLOAT); + self.write_string(key); + self.write_f64(*f); + } + Value::Bool(b) => { + self.buf.push(OP_PROP_BOOL); + self.write_string(key); + self.buf.push(if *b { 1 } else { 0 }); + } + Value::Color(c) => { + self.buf.push(OP_PROP_COLOR); + self.write_string(key); + self.write_string(c); + } + Value::FsPath(p) => { + self.buf.push(OP_PROP_FSPATH); + self.write_string(key); + self.write_string(p); + } + Value::Variable(v) => { + self.buf.push(OP_PROP_VAR); + self.write_string(key); + self.write_string(v); + } + Value::Rhei(r) => { + self.buf.push(OP_PROP_RHEI); + self.write_string(key); + self.write_string(r); + } + } + } + + fn compile_value(&mut self, val: &Value) { + match val { + Value::String(s) => { + self.buf.push(OP_PROP_STR); + self.write_string(s); + } + Value::Int(i) => { + self.buf.push(OP_PROP_INT); + self.write_i64(*i); + } + Value::Float(f) => { + self.buf.push(OP_PROP_FLOAT); + self.write_f64(*f); + } + Value::Bool(b) => { + self.buf.push(OP_PROP_BOOL); + self.buf.push(if *b { 1 } else { 0 }); + } + Value::Color(c) => { + self.buf.push(OP_PROP_COLOR); + self.write_string(c); + } + Value::FsPath(p) => { + self.buf.push(OP_PROP_FSPATH); + self.write_string(p); + } + Value::Variable(v) => { + self.buf.push(OP_PROP_VAR); + self.write_string(v); + } + Value::Rhei(r) => { + self.buf.push(OP_PROP_RHEI); + self.write_string(r); + } + } + } + + fn write_string(&mut self, s: &str) { + let bytes = s.as_bytes(); + self.write_u32(bytes.len() as u32); + self.buf.extend_from_slice(bytes); + } + + fn write_u32(&mut self, v: u32) { + self.buf.extend_from_slice(&v.to_le_bytes()); + } + + fn write_i64(&mut self, v: i64) { + self.buf.extend_from_slice(&v.to_le_bytes()); + } + + fn write_f64(&mut self, v: f64) { + self.buf.extend_from_slice(&v.to_le_bytes()); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..df46b82 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,302 @@ +mod ast; +mod compiler; +mod opcodes; +mod parser; + +use compiler::Compiler; +use parser::Parser; +use std::collections::HashSet; +use std::fs::File; +use std::io::Write; + +const INPUT: &str = r#" +@version 1 +@style "desktop.glts" + +@global $username = !rhei: os.env("USER") +@global $hostname = !rhei: os.hostname() +@global $locale = "ru_RU" +@global $scaleFactor = 1.0 + +@singleton Config { + wallpaper = fs:/home/$username/.config/de/wallpaper.jpg + wallpaperFit = "cover" + iconTheme = "papirus-dark" + fontMain = "Inter" + fontMono = "JetBrains Mono" + fontSize = 13 + workspaces = 4 + animEnabled = true + accentColor = #cba6f7 + taskbarPos = "bottom" +} + +@singleton SystemState { + battery = !rhei: sys.battery() + volume = !rhei: sys.volume.get() + brightness = !rhei: sys.brightness.get() + network = !rhei: sys.network.status() + timezone = !rhei: os.timezone() +} + +@component DesktopIcon(label: str, icon: fspath, exec: str) { + Button(class="desktop-icon") { + @on click { + !rhei: process.spawn($exec) + } + @on dblclick { + !rhei { + process.spawn($exec) + wm.raise(process.lastPid()) + } + } + Image(src=$icon, class="icon-img") {} + Label(class="icon-label") $label + } +} + +@component BatteryWidget { + @if $SystemState.battery.present { + @let $lvl = $SystemState.battery.level + @let $ico = !rhei: icons.battery($lvl) + + Panel(class="tray-item") { + Icon(src=$ico, class="tray-icon") {} + @if $SystemState.battery.charging { + Icon(src=fs:/usr/share/glint-de/icons/charging.svg, + class="tray-icon tray-icon--accent") {} + } + } + } +} + +@component ClockWidget { + @let $time = !rhei: sys.time.format("%H:%M", $SystemState.timezone) + @let $date = !rhei: sys.time.format("%d %b", $SystemState.timezone) + + Panel(class="clock-widget") { + @on click { + !rhei: ui.toggle("calendar-popup") + } + Label(class="clock-time") $time + Label(class="clock-date") $date + } +} + +@component SystemTray { + Panel(id="system-tray", class="tray") { + BatteryWidget {} + + @if $SystemState.network.connected { + Icon(class="tray-icon", + src=!rhei: icons.network($SystemState.network.type)) {} + } @else { + Icon(class="tray-icon tray-icon--warn", + src=fs:/usr/share/glint-de/icons/net-offline.svg) {} + } + + Slider(id="vol-slider", class="tray-slider", + value=$SystemState.volume, min=0, max=100) { + @on change { + !rhei: sys.volume.set($self.value) + } + } + + ClockWidget {} + } +} + +Screen(id="root", width=1920, height=1080, scale=$scaleFactor) { + Wallpaper(id="bg", + src=$Config.wallpaper, + fallback=fs:/usr/share/glint-de/wallpapers/default.jpg, + fit=$Config.wallpaperFit, + watch=true) {} + + Panel(id="desktop", class="desktop") { + @let $desktopFiles = !rhei: fs.glob("/home/$username/Desktop/*.desktop") + + @each $f in $desktopFiles { + @let $entry = !rhei: xdg.parseDesktop($f) + DesktopIcon( + label=$entry.name, + icon=!rhei: icons.resolve($entry.icon, $Config.iconTheme), + exec=$entry.exec + ) {} + } + + @on contextmenu { + !rhei: ui.show("desktop-ctx") + } + } + + ContextMenu(id="desktop-ctx", class="ctx-menu", visible=false) { + MenuItem(class="ctx-item") { + @on click { !rhei: ui.show("settings") } + "Настройки рабочего стола" + } + MenuItem(class="ctx-item") { + @on click { !rhei: wallpaper.showPicker() } + "Сменить обои" + } + MenuDivider {} + MenuItem(class="ctx-item ctx-item--danger") { + @on click { !rhei: session.logout() } + "Выйти из сеанса" + } + } + + Panel(id="taskbar", class="taskbar") { + Button(id="launcher-btn", class="launcher-button") { + @on click { !rhei: ui.toggle("app-launcher") } + Image(src=fs:/usr/share/glint-de/logo.svg) {} + } + + Panel(id="window-list", class="window-list") { + @let $wins = !rhei: wm.getWindows() + + @each $w in $wins { + Button(class="taskbar-win", data-wid=$w.id, + active=$w.focused) { + @on click { !rhei: wm.focus($w.id) } + @on middleclick { !rhei: wm.close($w.id) } + Icon(src=$w.icon, class="win-icon") {} + Label(class="win-title") $w.title + } + } + } + SystemTray {} + } + + Overlay(id="app-launcher", class="launcher", visible=false) { + @on keydown(key="Escape") { + !rhei: ui.hide("app-launcher") + } + + Input(id="launcher-search", class="launcher-search", + placeholder="Поиск приложений...", + autofocus=true) { + @on input { + !rhei: launcher.filter($self.value) + } + } + + Grid(id="app-grid", class="launcher-grid", columns=6) { + @let $apps = !rhei: apps.listAll() + + @each $app in $apps { + Button(class="launcher-app") { + @on click { + !rhei { + process.spawn($app.exec) + ui.hide("app-launcher") + } + } + Image(src=$app.icon, class="app-icon") {} + Label(class="app-name") $app.name + } + } + } + } + + Overlay(id="notif-layer", class="notif-layer") { + @let $notifs = !rhei: notifications.active() + + @each $n in $notifs { + Panel(class="notif-card", data-id=$n.id) { + Panel(class="notif-header") { + Icon(src=$n.appIcon, class="notif-icon") {} + Label(class="notif-app") $n.appName + Button(class="notif-close") { + @on click { !rhei: notifications.dismiss($n.id) } + "×" + } + } + Label(class="notif-title") $n.summary + @if $n.body { + Label(class="notif-body") $n.body + } + } + } + } + + @if !rhei: os.env("GLINT_DEV") { + !rhei { + debug.overlay.show() + debug.log("DE инициализирован. Пользователь: " + $username) + debug.log("Синглтоны: Config, SystemState") + } + } +} +"#; + +fn main() { + let mut parser = Parser::new(INPUT); + match parser.parse_all() { + Ok(_) => { + println!("Parse is successful"); + + let m = &parser.module; + + let mut child_indices = HashSet::new(); + for (start, len) in &m.elem_child_spans { + for i in *start..(*start + *len) { + child_indices.insert(i as usize); + } + } + for dir in &m.directives { + let span = match dir { + ast::Directive::Component { child_span, .. } => Some(child_span), + ast::Directive::If { + child_span, + else_span, + .. + } => { + if let Some(es) = else_span { + for i in es.0..(es.0 + es.1) { + child_indices.insert(i as usize); + } + } + Some(child_span) + } + ast::Directive::Each { child_span, .. } => Some(child_span), + ast::Directive::On { child_span, .. } => Some(child_span), + _ => None, + }; + if let Some((start, len)) = span { + for i in *start..(*start + *len) { + child_indices.insert(i as usize); + } + } + } + + let mut root_nodes = Vec::new(); + for (i, node) in m.hierarchy.iter().enumerate() { + if !child_indices.contains(&i) { + root_nodes.push(node.clone()); + } + } + + println!("Compile..."); + let compiler = Compiler::new(m); + let bytecode = compiler.compile(&root_nodes); + + let output_path = "desktop.glbc"; + let mut file = File::create(output_path).expect("Не удалось создать файл"); + file.write_all(&bytecode) + .expect("Не удалось записать байткод"); + + println!( + "Compile is successful. Compiled in {} ({} bytes)", + output_path, + bytecode.len() + ); + } + Err(e) => { + eprintln!("❌ Error of parse: {}", e); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/src/opcodes.rs b/src/opcodes.rs new file mode 100644 index 0000000..4703c54 --- /dev/null +++ b/src/opcodes.rs @@ -0,0 +1,30 @@ +pub const MAGIC_HEADER: [u8; 4] = *b"GLBC"; + +// direvctives +pub const OP_VERSION: u8 = 0x01; +pub const OP_STYLE: u8 = 0x02; +pub const OP_GLOBAL: u8 = 0x03; +pub const OP_SINGLETON: u8 = 0x04; +pub const OP_COMPONENT: u8 = 0x05; +pub const OP_LET: u8 = 0x06; +pub const OP_IF: u8 = 0x07; +pub const OP_EACH: u8 = 0x08; +pub const OP_ON: u8 = 0x09; +pub const OP_RHEI_BLK: u8 = 0x0A; + +// elements managment +pub const OP_ELEM_PUSH: u8 = 0x10; +pub const OP_ELEM_POP: u8 = 0x11; +pub const OP_CONTENT: u8 = 0x12; + +// types +pub const OP_PROP_STR: u8 = 0x20; +pub const OP_PROP_INT: u8 = 0x21; +pub const OP_PROP_FLOAT: u8 = 0x22; +pub const OP_PROP_BOOL: u8 = 0x23; +pub const OP_PROP_COLOR: u8 = 0x24; +pub const OP_PROP_FSPATH: u8 = 0x25; +pub const OP_PROP_VAR: u8 = 0x26; +pub const OP_PROP_RHEI: u8 = 0x27; + +pub const OP_END_BLOCK: u8 = 0xFF; diff --git a/src/parser.rs b/src/parser.rs new file mode 100644 index 0000000..049cf88 --- /dev/null +++ b/src/parser.rs @@ -0,0 +1,482 @@ +use crate::ast::*; + +pub struct Parser<'a> { + src: &'a [u8], + pos: usize, + pub module: ModuleSoA, +} + +impl<'a> Parser<'a> { + pub fn new(src: &'a str) -> Self { + Self { + src: src.as_bytes(), + pos: 0, + module: ModuleSoA::new(), + } + } + + #[inline] + fn peek(&self) -> Option { + self.src.get(self.pos).copied() + } + + #[inline] + fn advance(&mut self) { + self.pos += 1; + } + + #[inline] + fn consume_if(&mut self, expected: u8) -> bool { + if self.peek() == Some(expected) { + self.pos += 1; + true + } else { + false + } + } + + fn skip_whitespace(&mut self) { + while let Some(c) = self.peek() { + if c.is_ascii_whitespace() { + self.advance(); + } else if c == b'/' && self.src.get(self.pos + 1) == Some(&b'/') { + while let Some(cc) = self.peek() { + if cc == b'\n' { + break; + } + self.advance(); + } + } else { + break; + } + } + } + + fn parse_ident(&mut self) -> String { + let start = self.pos; + while let Some(c) = self.peek() { + if c.is_ascii_alphanumeric() || c == b'-' || c == b'_' || c == b'.' { + self.advance(); + } else { + break; + } + } + std::str::from_utf8(&self.src[start..self.pos]) + .unwrap() + .to_string() + } + + fn parse_rhei_expr(&mut self) -> Result { + self.skip_whitespace(); + if self.consume_if(b'{') { + let start = self.pos; + let mut depth = 1; + while depth > 0 { + let c = self.peek().ok_or("Unexpected EOF in Rhei block")?; + self.advance(); + if c == b'{' { + depth += 1; + } + if c == b'}' { + depth -= 1; + } + } + let expr = std::str::from_utf8(&self.src[start..self.pos - 1]) + .unwrap() + .trim() + .to_string(); + Ok(expr) + } else { + let start = self.pos; + let mut parens = 0; + let mut in_str = false; + let mut escape = false; + while let Some(c) = self.peek() { + if escape { + escape = false; + self.advance(); + continue; + } + if c == b'\\' { + escape = true; + self.advance(); + continue; + } + if c == b'"' { + in_str = !in_str; + } + if !in_str { + if c == b'(' { + parens += 1; + } + if c == b')' { + if parens == 0 { + break; + } + parens -= 1; + } + if parens == 0 && (c == b',' || c == b'\n' || c == b'}' || c == b'{') { + break; + } + } + self.advance(); + } + let expr = std::str::from_utf8(&self.src[start..self.pos]) + .unwrap() + .trim() + .to_string(); + Ok(expr) + } + } + + fn parse_value(&mut self) -> Result { + self.skip_whitespace(); + let c = self.peek().ok_or("Expected value, found EOF")?; + match c { + b'"' => { + self.advance(); + let start = self.pos; + while self.peek() != Some(b'"') { + if self.peek().is_none() { + return Err("Unexpected EOF inside string literal".into()); + } + self.advance(); + } + let val = std::str::from_utf8(&self.src[start..self.pos]) + .unwrap() + .to_string(); + self.advance(); + Ok(Value::String(val)) + } + b'#' => { + self.advance(); + let mut color = String::from("#"); + color.push_str(&self.parse_ident()); + Ok(Value::Color(color)) + } + b'$' => { + self.advance(); + Ok(Value::Variable(self.parse_ident())) + } + b'!' => { + self.advance(); + let ident = self.parse_ident(); + if ident != "rhei" { + return Err("Expected !rhei".into()); + } + self.consume_if(b':'); + Ok(Value::Rhei(self.parse_rhei_expr()?)) + } + b'0'..=b'9' | b'-' => { + let s = self.parse_ident(); + if s.contains('.') { + Ok(Value::Float(s.parse().unwrap())) + } else { + Ok(Value::Int(s.parse().unwrap())) + } + } + _ => { + let s = self.parse_ident(); + match s.as_str() { + "true" => Ok(Value::Bool(true)), + "false" => Ok(Value::Bool(false)), + "fs" => { + self.consume_if(b':'); + let start = self.pos; + while let Some(cc) = self.peek() { + if cc.is_ascii_whitespace() || cc == b',' || cc == b')' || cc == b'}' { + break; + } + self.advance(); + } + let path = std::str::from_utf8(&self.src[start..self.pos]) + .unwrap() + .to_string(); + Ok(Value::FsPath(path)) + } + _ => Err(format!("Unknown value token: {}", s)), + } + } + } + } + + fn parse_properties(&mut self) -> Result<(u32, u32), String> { + let start_idx = self.module.prop_keys.len() as u32; + self.advance(); + loop { + self.skip_whitespace(); + if self.consume_if(b')') { + break; + } + let key = self.parse_ident(); + if key.is_empty() { + return Err(format!( + "Expected property identifier, found {:?}", + self.peek().map(|b| b as char) + )); + } + self.skip_whitespace(); + if self.consume_if(b'=') { + let val = self.parse_value()?; + self.module.prop_keys.push(key); + self.module.prop_values.push(val); + } + self.skip_whitespace(); + self.consume_if(b','); + } + let len = (self.module.prop_keys.len() as u32) - start_idx; + Ok((start_idx, len)) + } + + fn parse_block(&mut self) -> Result<(u32, u32), String> { + self.skip_whitespace(); + if !self.consume_if(b'{') { + return Ok((self.module.hierarchy.len() as u32, 0)); + } + + let mut direct_children = Vec::new(); + loop { + self.skip_whitespace(); + if self.consume_if(b'}') { + break; + } + let node = self.parse_node()?; + direct_children.push(node); + } + + let start_idx = self.module.hierarchy.len() as u32; + let len = direct_children.len() as u32; + self.module.hierarchy.extend(direct_children); + Ok((start_idx, len)) + } + + fn parse_directive(&mut self) -> Result { + self.advance(); + let name = self.parse_ident(); + let dir = match name.as_str() { + "version" => { + self.skip_whitespace(); + let v = self.parse_ident().parse().unwrap(); + Directive::Version(v) + } + "style" => Directive::Style(match self.parse_value()? { + Value::String(s) => s, + _ => return Err("Style must be a string".into()), + }), + "global" => { + self.skip_whitespace(); + if !self.consume_if(b'$') { + return Err("Expected $ var".into()); + } + let var_name = self.parse_ident(); + self.skip_whitespace(); + self.consume_if(b'='); + let val = self.parse_value()?; + Directive::Global { + name: var_name, + value: val, + } + } + "singleton" => { + self.skip_whitespace(); + let sname = self.parse_ident(); + self.skip_whitespace(); + let start_idx = self.module.prop_keys.len() as u32; + if self.consume_if(b'{') { + loop { + self.skip_whitespace(); + if self.consume_if(b'}') { + break; + } + + let key = self.parse_ident(); + if key.is_empty() { + return Err(format!( + "Expected singleton property identifier, found {:?}", + self.peek().map(|b| b as char) + )); + } + self.skip_whitespace(); + self.consume_if(b'='); + let val = self.parse_value()?; + self.module.prop_keys.push(key); + self.module.prop_values.push(val); + } + } + let len = (self.module.prop_keys.len() as u32) - start_idx; + Directive::Singleton { + name: sname, + prop_span: (start_idx, len), + } + } + "component" => { + self.skip_whitespace(); + let cname = self.parse_ident(); + let mut params = Vec::new(); + self.skip_whitespace(); + if self.consume_if(b'(') { + loop { + self.skip_whitespace(); + if self.consume_if(b')') { + break; + } + let pname = self.parse_ident(); + self.skip_whitespace(); + self.consume_if(b':'); + self.skip_whitespace(); + let ptype = self.parse_ident(); + params.push((pname, ptype)); + self.skip_whitespace(); + self.consume_if(b','); + } + } + let child_span = self.parse_block()?; + Directive::Component { + name: cname, + params, + child_span, + } + } + "let" => { + self.skip_whitespace(); + self.consume_if(b'$'); + let var_name = self.parse_ident(); + self.skip_whitespace(); + self.consume_if(b'='); + let val = self.parse_value()?; + Directive::Let { + name: var_name, + value: val, + } + } + "if" => { + let condition = self.parse_value()?; + let child_span = self.parse_block()?; + let mut else_span = None; + self.skip_whitespace(); + + let backup = self.pos; + if self.consume_if(b'@') { + if self.parse_ident() == "else" { + else_span = Some(self.parse_block()?); + } else { + self.pos = backup; + } + } + Directive::If { + condition, + child_span, + else_span, + } + } + "each" => { + self.skip_whitespace(); + self.consume_if(b'$'); + let item = self.parse_ident(); + self.skip_whitespace(); + let in_kw = self.parse_ident(); + if in_kw != "in" { + return Err("Expected 'in' in @each".into()); + } + let collection = self.parse_value()?; + let child_span = self.parse_block()?; + Directive::Each { + item, + collection, + child_span, + } + } + "on" => { + self.skip_whitespace(); + let event = self.parse_ident(); + let mut args = Vec::new(); + self.skip_whitespace(); + if self.consume_if(b'(') { + loop { + self.skip_whitespace(); + if self.consume_if(b')') { + break; + } + let k = self.parse_ident(); + self.skip_whitespace(); + self.consume_if(b'='); + let v = self.parse_value()?; + args.push((k, v)); + self.skip_whitespace(); + self.consume_if(b','); + } + } + let child_span = self.parse_block()?; + Directive::On { + event, + args, + child_span, + } + } + _ => return Err(format!("Unknown directive: @{}", name)), + }; + Ok(NodeId::Directive(self.module.push_directive(dir))) + } + + fn parse_element(&mut self) -> Result { + let name = self.parse_ident(); + let el_id = self.module.push_element(name); + + self.skip_whitespace(); + if self.peek() == Some(b'(') { + let span = self.parse_properties()?; + self.module.elem_prop_spans[el_id as usize] = span; + } + + self.skip_whitespace(); + let p = self.peek(); + if p == Some(b'{') { + let span = self.parse_block()?; + self.module.elem_child_spans[el_id as usize] = span; + } else if p == Some(b'"') || p == Some(b'$') { + let val = self.parse_value()?; + self.module.elem_content[el_id as usize] = Some(val); + } + + Ok(NodeId::Element(el_id)) + } + + pub fn parse_node(&mut self) -> Result { + self.skip_whitespace(); + let c = self.peek().ok_or("EOF reached")?; + + match c { + b'@' => self.parse_directive(), + b'!' => { + self.advance(); + let i = self.parse_ident(); + if i != "rhei" { + return Err("Expected rhei".into()); + } + self.consume_if(b':'); + let expr = self.parse_rhei_expr()?; + Ok(NodeId::Directive( + self.module.push_directive(Directive::RheiBlock(expr)), + )) + } + b'A'..=b'Z' => self.parse_element(), + b'"' | b'$' => { + let val = self.parse_value()?; + let el_id = self.module.push_element("#text".to_string()); + self.module.elem_content[el_id as usize] = Some(val); + Ok(NodeId::Element(el_id)) + } + _ => Err(format!("Unexpected token: {}", c as char)), + } + } + + pub fn parse_all(&mut self) -> Result<(), String> { + self.skip_whitespace(); + while self.peek().is_some() { + let node = self.parse_node()?; + self.module.hierarchy.push(node); + self.skip_whitespace(); + } + Ok(()) + } +} diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 0000000..b041b57 --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,259 @@ +#[cfg(test)] +mod parser_tests { + use crate::ast::Value; + use crate::parser::Parser; + + #[test] + fn test_parser_exact_element_state() { + let input = r#"Button(id="btn", active=true, color=#ff0000, pad=10.5) "Click Me""#; + let mut parser = Parser::new(input); + parser.parse_all().expect("Парсинг не должен падать"); + + let m = &parser.module; + + assert_eq!( + m.elem_types.len(), + 1, + "Должен быть 1 элемент с inline-контентом" + ); + assert_eq!(m.elem_prop_spans.len(), 1); + assert_eq!(m.elem_child_spans.len(), 1); + assert_eq!(m.elem_content.len(), 1); + + assert_eq!(m.elem_types[0], "Button"); + + let (p_start, p_len) = m.elem_prop_spans[0]; + assert_eq!(p_start, 0); + assert_eq!(p_len, 4); + + let expected_keys = vec!["id", "active", "color", "pad"]; + let expected_vals = vec![ + Value::String("btn".to_string()), + Value::Bool(true), + Value::Color("#ff0000".to_string()), + Value::Float(10.5), + ]; + + for i in 0..4 { + let idx = (p_start + i) as usize; + assert_eq!( + m.prop_keys[idx], expected_keys[i as usize], + "Ключ {} не совпал", + i + ); + assert_eq!( + m.prop_values[idx], expected_vals[i as usize], + "Значение {} не совпало", + i + ); + } + + assert_eq!( + m.elem_content[0], + Some(Value::String("Click Me".to_string())), + "Контент текста потерян или искажен" + ); + } + + #[test] + fn test_parser_hierarchy_spans() { + let input = r#" + Root { + ChildA {} + ChildB { SubChild {} } + } + "#; + let mut parser = Parser::new(input); + parser.parse_all().expect("Парсинг должен пройти"); + + let m = &parser.module; + + let root_idx = m.elem_types.iter().position(|t| t == "Root").unwrap(); + let a_idx = m.elem_types.iter().position(|t| t == "ChildA").unwrap(); + let b_idx = m.elem_types.iter().position(|t| t == "ChildB").unwrap(); + + let root_span = m.elem_child_spans[root_idx]; + assert_eq!(root_span.1, 2, "У Root должно быть ровно 2 ребенка"); + + let child1 = &m.hierarchy[(root_span.0) as usize]; + let child2 = &m.hierarchy[(root_span.0 + 1) as usize]; + + match (child1, child2) { + (crate::ast::NodeId::Element(id1), crate::ast::NodeId::Element(id2)) => { + assert_eq!(*id1 as usize, a_idx); + assert_eq!(*id2 as usize, b_idx); + } + _ => panic!("Дети Root должны быть элементами"), + } + } +} + +#[cfg(test)] +mod compiler_tests { + use crate::compiler::Compiler; + use crate::opcodes::*; + use crate::parser::Parser; + + struct BytecodeBuilder { + buf: Vec, + } + impl BytecodeBuilder { + fn new() -> Self { + let mut b = Self { buf: Vec::new() }; + b.buf.extend_from_slice(&MAGIC_HEADER); + b + } + fn push_u8(mut self, val: u8) -> Self { + self.buf.push(val); + self + } + fn push_str(mut self, s: &str) -> Self { + let bytes = s.as_bytes(); + self.buf + .extend_from_slice(&(bytes.len() as u32).to_le_bytes()); + self.buf.extend_from_slice(bytes); + self + } + fn push_i64(mut self, val: i64) -> Self { + self.buf.extend_from_slice(&val.to_le_bytes()); + self + } + fn build(self) -> Vec { + self.buf + } + } + + #[test] + fn test_compiler_exact_bytes_directive() { + let input = "@version 42"; + let mut parser = Parser::new(input); + parser.parse_all().unwrap(); + + let root_nodes = vec![parser.module.hierarchy[0]]; + + let compiler = Compiler::new(&parser.module); + let bytecode = compiler.compile(&root_nodes); + + let expected = BytecodeBuilder::new() + .push_u8(OP_VERSION) + .push_i64(42) + .build(); + + assert_eq!(bytecode, expected); + } + + #[test] + fn test_compiler_exact_bytes_element() { + let input = r#"Box(id="main")"#; + let mut parser = Parser::new(input); + parser.parse_all().unwrap(); + + let root_nodes = vec![parser.module.hierarchy[0]]; + let compiler = Compiler::new(&parser.module); + let bytecode = compiler.compile(&root_nodes); + + let expected = BytecodeBuilder::new() + .push_u8(OP_ELEM_PUSH) + .push_str("Box") + .push_u8(OP_PROP_STR) + .push_str("id") + .push_str("main") + .push_u8(OP_ELEM_POP) + .build(); + + assert_eq!(bytecode, expected); + } + + #[test] + fn test_compiler_rhei_zero_parsing() { + let input = r#"@global $net = !rhei: sys.network().status"#; + let mut parser = Parser::new(input); + parser.parse_all().unwrap(); + + let root_nodes = vec![parser.module.hierarchy[0]]; + let compiler = Compiler::new(&parser.module); + let bytecode = compiler.compile(&root_nodes); + + let expected = BytecodeBuilder::new() + .push_u8(OP_GLOBAL) + .push_str("net") + .push_u8(OP_PROP_RHEI) + .push_str("sys.network().status") + .build(); + + assert_eq!(bytecode, expected); + } +} + +const TEST_GLINT_INPUT: &str = r#" +@version 1 +@style "desktop.glts" +@global $username = !rhei: os.env("USER") +@global $hostname = !rhei: os.hostname() +@global $locale = "ru_RU" +@global $scaleFactor = 1.0 +@singleton Config { + wallpaper = fs:/home/$username/.config/de/wallpaper.jpg + wallpaperFit = "cover" + iconTheme = "papirus-dark" + fontMain = "Inter" + fontMono = "JetBrains Mono" + fontSize = 13 + workspaces = 4 + animEnabled = true + accentColor = #cba6f7 + taskbarPos = "bottom" +} +Screen(id="root", width=1920, height=1080, scale=$scaleFactor) { + Panel(id="taskbar", class="taskbar") { + Button(id="launcher-btn", class="launcher-button") { + Image(src=fs:/usr/share/glint-de/logo.svg) {} + } + } +} +"#; + +#[test] +fn test_full_desktop_compilation() { + use crate::compiler::Compiler; + use crate::opcodes::MAGIC_HEADER; + use crate::parser::Parser; + + let mut parser = Parser::new(TEST_GLINT_INPUT); + + assert!( + parser.parse_all().is_ok(), + "Парсер вернул ошибку на валидном конфиге DE!" + ); + + let m = &parser.module; + assert!(!m.elem_types.is_empty(), "Не найдено ни одного элемента!"); + + assert_eq!(m.elem_types.len(), m.elem_prop_spans.len()); + assert_eq!(m.elem_prop_spans.len(), m.elem_child_spans.len()); + assert_eq!(m.prop_keys.len(), m.prop_values.len()); + + let mut child_indices = std::collections::HashSet::new(); + for (start, len) in &m.elem_child_spans { + for i in *start..(*start + *len) { + child_indices.insert(i as usize); + } + } + + let mut root_nodes = Vec::new(); + for (i, node) in m.hierarchy.iter().enumerate() { + if !child_indices.contains(&i) { + root_nodes.push(node.clone()); + } + } + + let compiler = Compiler::new(m); + let bytecode = compiler.compile(&root_nodes); + + assert_eq!( + &bytecode[0..4], + &MAGIC_HEADER, + "Отсутствует или поврежден GLBC заголовок" + ); + assert!(bytecode.len() > 50, "Байткод подозрительно мал"); +}