First commit on new branch
This commit is contained in:
65
DOCS.md
65
DOCS.md
@@ -1,65 +0,0 @@
|
||||
# 📚 Documentação da Linguagem RedDust
|
||||
|
||||
**RedDust** é uma linguagem minimalista projetada para ser executada em uma máquina virtual ou em um computador físico construído com redstone (7SPM - Seven Segment Programmable Machine).
|
||||
|
||||
---
|
||||
|
||||
## ✅ **Formato das Instruções**
|
||||
Cada linha do programa deve conter **4 valores em hexadecimal**, separados por ponto e vírgula (`;`), conforme:
|
||||
|
||||
```
|
||||
CMD;A;B;C
|
||||
```
|
||||
|
||||
- **CMD** → Código da instrução (0 a F)
|
||||
- **A, B, C** → Operandos (endereços de memória ou valores imediatos)
|
||||
- Cada instrução ocupa **4 dígitos obrigatórios** para manter compatibilidade com a arquitetura 7SPM.
|
||||
- Valores em hexadecimal de **1 digito**, e em letra maiúscula.
|
||||
|
||||
Exemplo:
|
||||
```
|
||||
1;1;A;0 // INPUT → Salva valor imediato A (10) no registrador 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔢 **Tabela de Instruções**
|
||||
| Código | Comando | Descrição | Exemplo |
|
||||
|--------|--------------|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
|
||||
| **0** | **HALT** | Finaliza a execução do programa. | `0;0;0;0 // encerra o programa` |
|
||||
| **1** | **INPUT** | Lê um número do usuário (se B=0) ou usa valor imediato (B≠0) e salva em A. | `1;1;5;0 // salva 5 no R1` |
|
||||
| **2** | **OUTPUT** | Exibe o valor armazenado no endereço A. | `2;1;0;0 // mostra valor de R1` |
|
||||
| **3** | **ADD** | Soma (mem[A] + mem[B]) e salva em C. | `3;1;2;3 // R3 = R1 + R2` |
|
||||
| **4** | **SUB** | Subtrai (mem[A] - mem[B]) e salva em C. | `4;1;2;3 // R3 = R1 - R2` |
|
||||
| **5** | **DIV** | Divide (mem[A] ÷ mem[B]) e salva em C (divisão inteira). | `5;1;2;3 // R3 = R1 / R2` |
|
||||
| **6** | **MUL** | Multiplica (mem[A] × mem[B]) e salva em C. | `6;1;2;3 // R3 = R1 * R2` |
|
||||
| **7** | **COND JUMP**| Pula para a linha C se mem[A] == B. | `7;1;3;8 // Se R1 == 3 → pula para linha 8` |
|
||||
| **8** | **JUMP** | Pula incondicionalmente para a linha A. | `8;A;0;0 // Pula para linha A (10)` |
|
||||
| **9** | **CLEAR** | Zera mem[A]. | `9;1;0;0 // R1 = 0` |
|
||||
| **A** | **RANDOM** | Salva em A um número aleatório entre B e C. | `A;A;B;1 // R1 = valor aleatório (A-B)` |
|
||||
| **B** | **CMP GREATER**| Compara mem[A] > mem[B]; salva 1 (sim) ou 0 (não) em C. | `B;1;2;3 // Se R1 > R2 → R3 = 1, senão 0` |
|
||||
| **C** | **CMP EQUAL**| Verifica se mem[A] == mem[B], salva 1 (sim) ou 0 (não) em C. | `C;1;2;0 // troca R1 com R2` |
|
||||
| **D** | **MOVE** | Copia mem[A] para mem[B]. | `D;1;2;0 // R2 = R1` |
|
||||
| **E** | **INC/DEC** | Incrementa (flag=1) ou decrementa (flag=0) mem[A]. | `E;1;1;0 // R1++` \| `E;1;0;0 // R1--` |
|
||||
| **F** | **WAIT** | Pausa por A segundos (HEX → decimal). | `F;A;0;0 // Espera 10 segundos` |
|
||||
|
||||
---
|
||||
|
||||
## ✅ **Exemplo de Programa**
|
||||
**Objetivo:** Solicitar 2 números, somar e exibir o resultado.
|
||||
|
||||
```
|
||||
1;1;0;0 // INPUT → mem[1]
|
||||
1;2;0;0 // INPUT → mem[2]
|
||||
3;1;2;3 // ADD → mem[3] = mem[1] + mem[2]
|
||||
2;3;0;0 // OUTPUT → mem[3]
|
||||
0;0;0;0 // HALT
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠ Observações
|
||||
- Todos os valores são **HEX (0-F)**.
|
||||
- Cada linha deve ter **4 parâmetros obrigatórios** para compatibilidade com o **7SPM**.
|
||||
- Comentários iniciam com `//`.
|
||||
|
||||
21
LICENSE
21
LICENSE
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Syntax
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,11 +1,9 @@
|
||||
<img width="1000" height="500" alt="Inserir um título(1)" src="https://github.com/user-attachments/assets/323b1f5e-5e44-4c48-989e-47eff36bf2d6" />
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
**RedDust** é uma linguagem minimalista projetada para simular lógica em um computador construído com Redstone no *Minecraft*, especificamente o 7SPM.
|
||||
Este repositório contém o interpretador, suporte para sintaxe em múltiplos editores e scripts para instalação global.
|
||||
*RedDust* é uma linguagem de programação
|
||||
|
||||
Confira a [documentação](DOCS.md)
|
||||
|
||||
|
||||
100
redd-install.sh
100
redd-install.sh
@@ -1,100 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
INSTALL_DIR="/usr/local/bin"
|
||||
ICON_DIR="/usr/share/icons/reddust"
|
||||
MIME_DIR="/usr/share/mime/packages"
|
||||
GITHUB_RAW="https://raw.githubusercontent.com/SynthX7/reddust/main"
|
||||
|
||||
echo "[INFO] Iniciando instalação do RedDust..."
|
||||
|
||||
# 1. Verifica se Python 3 está instalado
|
||||
if ! command -v python3 &> /dev/null; then
|
||||
echo "[INFO] Python3 não encontrado. Instalando..."
|
||||
if [ -f /etc/debian_version ]; then
|
||||
sudo apt-get update && sudo apt-get install -y python3
|
||||
elif [ -f /etc/arch-release ]; then
|
||||
sudo pacman -Sy --noconfirm python
|
||||
else
|
||||
echo "[ERRO] Não foi possível detectar a distribuição. Instale Python 3 manualmente."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "[INFO] Python3 já está instalado."
|
||||
fi
|
||||
|
||||
# 2. Instala interpretador
|
||||
echo "[INFO] Instalando interpretador RedDust..."
|
||||
sudo curl -fsSL "$GITHUB_RAW/reddust" -o "$INSTALL_DIR/reddust"
|
||||
sudo chmod +x "$INSTALL_DIR/reddust"
|
||||
|
||||
# 3. Ícone
|
||||
echo "[INFO] Instalando ícone..."
|
||||
sudo mkdir -p "$ICON_DIR"
|
||||
sudo curl -fsSL "$GITHUB_RAW/icon/reddust.png" -o "$ICON_DIR/icon.png"
|
||||
|
||||
# 4. Configuração MIME
|
||||
echo "[INFO] Configurando MIME..."
|
||||
sudo tee "$MIME_DIR/reddust.xml" > /dev/null <<EOF
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
||||
<mime-type type="text/reddust">
|
||||
<comment>RedDust Source Code</comment>
|
||||
<glob pattern="*.redd"/>
|
||||
<icon name="reddust"/>
|
||||
</mime-type>
|
||||
</mime-info>
|
||||
EOF
|
||||
sudo update-mime-database /usr/share/mime
|
||||
if command -v gtk-update-icon-cache &> /dev/null; then
|
||||
sudo gtk-update-icon-cache -f /usr/share/icons/hicolor
|
||||
fi
|
||||
|
||||
# 5. VSCode Syntax (somente se VSCode estiver instalado)
|
||||
echo "[INFO] Verificando VSCode..."
|
||||
if [ -d "$HOME/.vscode/extensions" ]; then
|
||||
echo "[INFO] Instalando suporte para VSCode..."
|
||||
EXT_DIR="$HOME/.vscode/extensions/reddust-syntax"
|
||||
mkdir -p "$EXT_DIR"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/vscode-reddust/package.json" -o "$EXT_DIR/package.json"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/vscode-reddust/reddust.tmLanguage.json" -o "$EXT_DIR/reddust.tmLanguage.json"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/vscode-reddust/language-configuration.json" -o "$EXT_DIR/language-configuration.json"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/vscode-reddust/icon.png" -o "$EXT_DIR/icon.png"
|
||||
else
|
||||
echo "[AVISO] VSCode não encontrado (pasta ~/.vscode/extensions ausente). Pulei a instalação."
|
||||
fi
|
||||
|
||||
# 6. Geany Syntax
|
||||
echo "[INFO] Verificando Geany..."
|
||||
if [ -d "$HOME/.config/geany/filedefs" ]; then
|
||||
echo "[INFO] Instalando suporte para Geany..."
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/geany-reddust/filetypes.reddust.conf" -o "$HOME/.config/geany/filedefs/filetypes.reddust.conf"
|
||||
else
|
||||
echo "[AVISO] Geany não encontrado (pasta ~/.config/geany/filedefs ausente). Pulei a instalação."
|
||||
fi
|
||||
|
||||
# 7. Vim Syntax
|
||||
echo "[INFO] Verificando Vim..."
|
||||
if [ -d "$HOME/.vim" ]; then
|
||||
mkdir -p "$HOME/.vim/syntax"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/vim-reddust/reddust.vim" -o "$HOME/.vim/syntax/reddust.vim"
|
||||
if [ -f "$HOME/.vimrc" ]; then
|
||||
grep -qxF 'au BufNewFile,BufRead *.redd set filetype=reddust' "$HOME/.vimrc" || echo 'au BufNewFile,BufRead *.redd set filetype=reddust' >> "$HOME/.vimrc"
|
||||
else
|
||||
echo "[AVISO] ~/.vimrc não encontrado. Pulei configuração automática do Vim."
|
||||
fi
|
||||
else
|
||||
echo "[AVISO] Vim não encontrado (pasta ~/.vim ausente). Pulei a instalação."
|
||||
fi
|
||||
|
||||
# 8. Nano Syntax
|
||||
if [ -f "$HOME/.nanorc" ]; then
|
||||
mkdir -p "$HOME/.nano"
|
||||
grep -qxF 'include ~/.nano/reddust.nanorc' "$HOME/.nanorc" || echo 'include ~/.nano/reddust.nanorc' >> "$HOME/.nanorc"
|
||||
curl -fsSL "$GITHUB_RAW/highlighting/nano-reddust/reddust.nanorc" -o "$HOME/.nano/reddust.nanorc"
|
||||
else
|
||||
echo "[AVISO] ~/.nanorc não encontrado. Pulei suporte ao Nano."
|
||||
fi
|
||||
|
||||
echo "[INFO] Instalação concluída! É recomendável reiniciar o sistema ou a sessão atual."
|
||||
echo "✅ Use com: reddust arquivo.redd"
|
||||
@@ -1,28 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "[INFO] Removendo RedDust..."
|
||||
|
||||
# Interpretador
|
||||
sudo rm -f /usr/local/bin/reddust
|
||||
|
||||
# Ícone e MIME
|
||||
sudo rm -rf /usr/share/icons/reddust
|
||||
sudo rm -f /usr/share/mime/packages/reddust.xml
|
||||
sudo update-mime-database /usr/share/mime
|
||||
|
||||
# VSCode
|
||||
rm -rf ~/.vscode/extensions/reddust-syntax
|
||||
|
||||
# Geany
|
||||
rm -f ~/.config/geany/filedefs/filetypes.reddust.conf
|
||||
|
||||
# Vim
|
||||
rm -f ~/.vim/syntax/reddust.vim
|
||||
sed -i '/reddust/d' ~/.vimrc
|
||||
|
||||
# Nano
|
||||
sed -i '/reddust.nanorc/d' ~/.nanorc
|
||||
rm -f ~/.nano/reddust.nanorc
|
||||
|
||||
echo "[INFO] RedDust removido com sucesso!"
|
||||
216
reddust
216
reddust
@@ -1,216 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import random
|
||||
import time
|
||||
|
||||
# Memória da máquina
|
||||
memory = [0] * 256 # 256 endereços possíveis
|
||||
|
||||
|
||||
def parse_line(line):
|
||||
# Remove comentários após "//"
|
||||
line = line.split('//')[0].strip()
|
||||
if not line:
|
||||
return None
|
||||
|
||||
tokens = [t.strip() for t in line.split(';') if t.strip()]
|
||||
|
||||
if len(tokens) != 4:
|
||||
print(f"[ERRO] Linha inválida (esperado 4 valores): {line}")
|
||||
return None
|
||||
|
||||
try:
|
||||
return [int(t, 16) for t in tokens] # HEX -> int
|
||||
except ValueError:
|
||||
print(f"[ERRO] Valores inválidos na linha: {line}")
|
||||
return None
|
||||
|
||||
|
||||
def to_hex(val):
|
||||
return format(val, 'X')
|
||||
|
||||
|
||||
def run_program(program, debug=False):
|
||||
pc = 0
|
||||
while pc < len(program):
|
||||
instr = program[pc]
|
||||
cmd = format(instr[0], 'X')
|
||||
|
||||
if debug:
|
||||
hex_instr = [to_hex(x) for x in instr]
|
||||
hex_mem = [to_hex(x) for x in memory[:16]]
|
||||
print(f"[DEBUG] PC={to_hex(pc+1)}, CMD={hex_instr}, MEM[0..F]={hex_mem}")
|
||||
|
||||
if cmd == "0": # HALT
|
||||
print("[INFO] Programa finalizado.")
|
||||
break
|
||||
|
||||
elif cmd == "1": # INPUT
|
||||
a, b = instr[1], instr[2]
|
||||
if b != 0:
|
||||
memory[a] = b
|
||||
else:
|
||||
print("[INFO] Waiting for input...")
|
||||
try:
|
||||
value = input(f"Digite valor HEX para mem[{to_hex(a)}]: ").strip()
|
||||
memory[a] = int(value, 16)
|
||||
except KeyboardInterrupt:
|
||||
print("\n[INFO] Entrada cancelada pelo usuário (Ctrl+C).")
|
||||
sys.exit(0)
|
||||
except ValueError:
|
||||
print("[ERRO] Valor inválido! Use HEX (ex.: A, F, 1F)")
|
||||
return None
|
||||
|
||||
elif cmd == "2": # OUTPUT
|
||||
addr = instr[1]
|
||||
print(f"[OUTPUT] {to_hex(memory[addr])}")
|
||||
|
||||
elif cmd == "3": # ADD
|
||||
a, b, c = instr[1], instr[2], instr[3]
|
||||
memory[c] = memory[a] + memory[b]
|
||||
|
||||
elif cmd == "4": # SUB
|
||||
a, b, c = instr[1], instr[2], instr[3]
|
||||
memory[c] = memory[a] - memory[b]
|
||||
|
||||
elif cmd == "5": # DIV
|
||||
a, b, c = instr[1], instr[2], instr[3]
|
||||
memory[c] = memory[a] // memory[b] if memory[b] != 0 else 0
|
||||
|
||||
elif cmd == "6": # MUL
|
||||
a, b, c = instr[1], instr[2], instr[3]
|
||||
memory[c] = memory[a] * memory[b]
|
||||
|
||||
elif cmd == "7": # COND JUMP
|
||||
addr, val, target = instr[1], instr[2], instr[3]
|
||||
if memory[addr] == val:
|
||||
pc = target - 1
|
||||
continue
|
||||
|
||||
elif cmd == "8": # JUMP
|
||||
pc = instr[1] - 1
|
||||
continue
|
||||
|
||||
elif cmd == "9": # CLEAR
|
||||
addr = instr[1]
|
||||
memory[addr] = 0
|
||||
|
||||
elif cmd == "A": # RANDOM
|
||||
addr = instr[1]
|
||||
memory[addr] = random.randint(0, 15)
|
||||
|
||||
elif cmd == "B": # CMP GREATER
|
||||
x, y, out = instr[1], instr[2], instr[3]
|
||||
memory[out] = 1 if memory[x] > memory[y] else 0
|
||||
|
||||
elif cmd == "C": # CMP LESS
|
||||
x, y, out = instr[1], instr[2], instr[3]
|
||||
memory[out] = 1 if memory[x] < memory[y] else 0
|
||||
|
||||
elif cmd == "D": # MOVE
|
||||
src, dst = instr[1], instr[2]
|
||||
memory[dst] = memory[src]
|
||||
|
||||
elif cmd == "E": # INC/DEC
|
||||
addr, flag = instr[1], instr[2]
|
||||
if flag == 1:
|
||||
memory[addr] += 1
|
||||
elif flag == 0:
|
||||
memory[addr] -= 1
|
||||
else:
|
||||
print(f"[ERRO] Flag inválida: {to_hex(flag)}")
|
||||
return None
|
||||
|
||||
elif cmd == "F": # WAIT
|
||||
delay = instr[1]
|
||||
print(f"[INFO] Esperando {delay} segundos...")
|
||||
time.sleep(delay)
|
||||
|
||||
else:
|
||||
print(f"[ERRO] Comando inválido: {cmd}")
|
||||
return None
|
||||
|
||||
pc += 1
|
||||
|
||||
|
||||
def repl():
|
||||
print("Modo REPL RedDust (digite 'exit' para sair)")
|
||||
program = []
|
||||
line_num = 1
|
||||
while True:
|
||||
try:
|
||||
line = input(f"linha {line_num}> ").strip()
|
||||
if line.lower() == "exit":
|
||||
print("[INFO] Saindo do REPL e executando programa...")
|
||||
break
|
||||
instr = parse_line(line)
|
||||
if instr:
|
||||
program.append(instr)
|
||||
line_num += 1
|
||||
except KeyboardInterrupt:
|
||||
print("\n[INFO] Interrompido pelo usuário (Ctrl+C).")
|
||||
sys.exit(0)
|
||||
run_program(program)
|
||||
|
||||
|
||||
def show_help():
|
||||
print("""
|
||||
RedDust Interpreter v3.1
|
||||
Uso:
|
||||
reddust <arquivo.redd> Executa um programa RedDust
|
||||
reddust Inicia modo interativo (REPL)
|
||||
reddust --debug <arquivo> Executa com debug (mostra memória)
|
||||
reddust --version Mostra versão
|
||||
reddust --help Exibe esta ajuda
|
||||
|
||||
Formato do código:
|
||||
Cada linha deve conter 4 valores HEX separados por ponto-e-vírgula (;)
|
||||
Exemplo:
|
||||
1;A;0;0 // INPUT: pede valor para mem[A]
|
||||
2;A;0;0 // OUTPUT: mostra mem[A]
|
||||
0;0;0;0 // HALT
|
||||
""")
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
if "--help" in sys.argv:
|
||||
show_help()
|
||||
sys.exit(0)
|
||||
|
||||
if "--version" in sys.argv:
|
||||
print("RedDust Interpreter v3.1 (HEX Mode)")
|
||||
sys.exit(0)
|
||||
|
||||
debug = "--debug" in sys.argv
|
||||
|
||||
if len(sys.argv) == 1 or (len(sys.argv) == 2 and debug):
|
||||
repl()
|
||||
return
|
||||
|
||||
filename = sys.argv[1]
|
||||
if not filename.endswith(".redd"):
|
||||
print("[ERRO] Arquivo deve ter extensão .redd")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
with open(filename, 'r') as f:
|
||||
lines = f.readlines()
|
||||
except FileNotFoundError:
|
||||
print(f"[ERRO] Arquivo '{filename}' não encontrado.")
|
||||
sys.exit(1)
|
||||
|
||||
program = []
|
||||
for line in lines:
|
||||
instr = parse_line(line)
|
||||
if instr:
|
||||
program.append(instr)
|
||||
run_program(program, debug)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n[INFO] Execução interrompida pelo usuário (Ctrl+C).")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user