petcarescript
Version:
PetCareScript - A modern, expressive programming language designed for humans
705 lines (578 loc) • 14.9 kB
Markdown
PetCareScript foi projetado para ser **expressivo, humano e intuitivo**. A sintaxe usa palavras em inglês que fazem sentido natural, tornando o código mais legível para iniciantes e expressivo para desenvolvedores experientes.
```javascript
// Comentário de linha única
/*
Comentário de
múltiplas linhas
*/
```
```javascript
// Declaração simples
store name = "João";
store age = 25;
store isActive = yes; // Booleano verdadeiro
store isEmpty = no; // Booleano falso
store nothing = empty; // Valor nulo
// Múltiplas declarações
store x = 10, y = 20, z = 30;
```
```javascript
// Números
store integer = 42;
store decimal = 3.14;
store negative = -15;
// Strings
store message = "Olá, mundo!";
store template = 'Template com aspas simples';
// Booleanos
store isTrue = yes;
store isFalse = no;
// Nulo
store empty_value = empty;
```
```javascript
// Array simples
store numbers = [1, 2, 3, 4, 5];
store names = ["Alice", "Bob", "Charlie"];
store mixed = [1, "texto", yes, empty];
// Array vazio
store empty_list = [];
// Acesso a elementos
store first = numbers[0]; // 1
store last = numbers[4]; // 5
// Modificação
numbers[0] = 10; // Altera primeiro elemento
```
```javascript
// Objeto simples
store person = {
name: "Maria",
age: 30,
city: "São Paulo"
};
// Objeto aninhado
store company = {
name: "TechCorp",
employees: [
{ name: "Ana", role: "Developer" },
{ name: "Carlos", role: "Designer" }
],
address: {
street: "Rua das Flores, 123",
city: "Rio de Janeiro"
}
};
// Acesso a propriedades
store companyName = company.name;
store firstEmployee = company.employees[0].name;
```
```javascript
store sum = 10 + 5; // 15
store difference = 10 - 3; // 7
store product = 4 * 6; // 24
store quotient = 15 / 3; // 5
```
```javascript
store isEqual = (5 == 5); // yes
store isNotEqual = (5 != 3); // yes
store isGreater = (10 > 5); // yes
store isGreaterEqual = (10 >= 10); // yes
store isLess = (3 < 8); // yes
store isLessEqual = (5 <= 5); // yes
```
```javascript
store andResult = yes also yes; // yes (AND)
store orResult = yes either no; // yes (OR)
store notResult = !yes; // no (NOT)
// Expressões complexas
store complex = (age > 18) also (hasLicense == yes);
```
```javascript
store x = 10;
x = x + 5; // x = 15
// Nota: Operadores += ainda não implementados
```
```javascript
// Função simples
build greet() {
show "Olá, mundo!";
}
// Função com parâmetros
build greet(name) {
show "Olá, " + name + "!";
}
// Função com múltiplos parâmetros
build add(a, b) {
give a + b; // Retorna o resultado
}
// Função com valor padrão (simulado)
build greetWithDefault(name) {
check (name == empty) {
name = "Visitante";
}
show "Olá, " + name + "!";
}
```
```javascript
// Chamadas simples
greet(); // "Olá, mundo!"
greet("Maria"); // "Olá, Maria!"
// Usando retorno
store result = add(5, 3); // result = 8
store sum = add(10, add(2, 3)); // Aninhada: sum = 15
```
```javascript
build printArray(items) {
store i = 0;
repeat (i < length(items)) {
show items[i];
i = i + 1;
}
}
// Função que modifica array
build addToList(list, item) {
// Simulação de push (não implementado ainda)
store newIndex = length(list);
list[newIndex] = item;
give list;
}
```
```javascript
store age = 18;
check (age >= 18) {
show "Você é maior de idade";
}
```
```javascript
store temperature = 25;
check (temperature > 30) {
show "Está muito quente!";
} otherwise {
show "Temperatura agradável";
}
```
```javascript
store score = 85;
check (score >= 90) {
show "Excelente!";
} otherwise check (score >= 80) {
show "Muito bom!";
} otherwise check (score >= 70) {
show "Bom!";
} otherwise {
show "Precisa melhorar";
}
```
```javascript
store weather = "sunny";
store temperature = 25;
check (weather == "sunny") {
check (temperature > 20) {
show "Perfeito para um passeio!";
} otherwise {
show "Ensolarado, mas um pouco frio";
}
} otherwise {
show "Melhor ficar em casa";
}
```
```javascript
store counter = 0;
repeat (counter < 5) {
show "Contador: " + counter;
counter = counter + 1;
}
```
```javascript
// For tradicional
again (store i = 0; i < 10; i = i + 1) {
show "Número: " + i;
}
// For com array
store fruits = ["maçã", "banana", "laranja"];
again (store j = 0; j < length(fruits); j = j + 1) {
show "Fruta: " + fruits[j];
}
```
```javascript
// Tabuada
again (store i = 1; i <= 5; i = i + 1) {
again (store j = 1; j <= 5; j = j + 1) {
store result = i * j;
show i + " x " + j + " = " + result;
}
}
```
```javascript
blueprint Animal {
// Construtor
build init(name, species) {
self.name = name;
self.species = species;
self.energy = 100;
}
// Métodos
build speak() {
show self.name + " faz algum som";
}
build eat() {
self.energy = self.energy + 10;
show self.name + " está comendo";
}
build getInfo() {
give self.name + " é um " + self.species;
}
}
```
```javascript
// Criar instâncias
store dog = Animal("Rex", "cachorro");
store cat = Animal("Mimi", "gato");
// Usar métodos
dog.speak(); // "Rex faz algum som"
cat.eat(); // "Mimi está comendo"
// Acessar propriedades
show dog.name; // "Rex"
show cat.energy; // 110 (após comer)
// Usar métodos com retorno
store info = dog.getInfo(); // "Rex é um cachorro"
show info;
```
```javascript
blueprint Dog from Animal {
build init(name, breed) {
parent.init(name, "cachorro");
self.breed = breed;
}
build speak() {
show self.name + " faz: Au au!";
}
build wagTail() {
show self.name + " está balançando o rabo";
}
}
blueprint Cat from Animal {
build init(name, color) {
parent.init(name, "gato");
self.color = color;
}
build speak() {
show self.name + " faz: Miau!";
}
build purr() {
show self.name + " está ronronando";
}
}
```
```javascript
// Criar instâncias especializadas
store goldenRetriever = Dog("Buddy", "Golden Retriever");
store persianCat = Cat("Luna", "branco");
// Métodos específicos
goldenRetriever.speak(); // "Buddy faz: Au au!"
goldenRetriever.wagTail(); // "Buddy está balançando o rabo"
persianCat.speak(); // "Luna faz: Miau!"
persianCat.purr(); // "Luna está ronronando"
// Métodos herdados
goldenRetriever.eat(); // "Buddy está comendo"
persianCat.eat(); // "Luna está comendo"
```
```javascript
// Mostrar valores
show "Texto simples";
show 42;
show yes;
show [1, 2, 3];
// Concatenação
store name = "João";
show "Olá, " + name + "!";
// Múltiplas variáveis
store a = 10, b = 20;
show "A soma de " + a + " e " + b + " é " + (a + b);
```
```javascript
store value = 42;
store type = typeOf(value); // "number"
store text = "hello";
store textType = typeOf(text); // "string"
store list = [1, 2, 3];
store listType = typeOf(list); // "array"
```
```javascript
store text = "Hello";
store textLength = length(text); // 5
store numbers = [1, 2, 3, 4, 5];
store arrayLength = length(numbers); // 5
store person = { name: "Ana", age: 25 };
store objectLength = length(person); // 2
```
```javascript
store now = currentTime(); // Timestamp atual
show "Tempo atual: " + now;
```
```javascript
// Sintaxe planejada para versões futuras
attempt {
store result = riskyOperation();
show "Sucesso: " + result;
} handle error {
show "Erro capturado: " + error;
} always {
show "Este bloco sempre executa";
}
```
```javascript
blueprint Calculator {
build add(a, b) {
give a + b;
}
build subtract(a, b) {
give a - b;
}
build multiply(a, b) {
give a * b;
}
build divide(a, b) {
check (b == 0) {
show "Erro: Divisão por zero!";
give empty;
}
give a / b;
}
}
store calc = Calculator();
store sum = calc.add(10, 5); // 15
store product = calc.multiply(4, 3); // 12
show "10 + 5 = " + sum;
show "4 * 3 = " + product;
```
```javascript
blueprint TodoList {
build init() {
self.tasks = [];
self.nextId = 1;
}
build addTask(description) {
store task = {
id: self.nextId,
description: description,
completed: no
};
// Simulação de push
store index = length(self.tasks);
self.tasks[index] = task;
self.nextId = self.nextId + 1;
show "Tarefa adicionada: " + description;
}
build listTasks() {
show "=== Lista de Tarefas ===";
again (store i = 0; i < length(self.tasks); i = i + 1) {
store task = self.tasks[i];
store status = task.completed ? "[✓]" : "[ ]";
show status + " " + task.id + ". " + task.description;
}
}
build completeTask(id) {
again (store i = 0; i < length(self.tasks); i = i + 1) {
check (self.tasks[i].id == id) {
self.tasks[i].completed = yes;
show "Tarefa " + id + " concluída!";
give;
}
}
show "Tarefa " + id + " não encontrada";
}
}
// Uso da lista de tarefas
store todo = TodoList();
todo.addTask("Estudar PetCareScript");
todo.addTask("Fazer exercícios");
todo.addTask("Ler documentação");
todo.listTasks();
todo.completeTask(1);
todo.listTasks();
```
```javascript
blueprint GuessingGame {
build init(maxNumber) {
self.secretNumber = 42; // Simulação de random
self.maxNumber = maxNumber;
self.attempts = 0;
self.gameOver = no;
}
build makeGuess(guess) {
check (self.gameOver) {
show "O jogo já terminou!";
give;
}
self.attempts = self.attempts + 1;
check (guess == self.secretNumber) {
show "Parabéns! Você acertou em " + self.attempts + " tentativas!";
self.gameOver = yes;
} otherwise check (guess < self.secretNumber) {
show "Muito baixo! Tente um número maior.";
} otherwise {
show "Muito alto! Tente um número menor.";
}
}
build getHint() {
check (self.secretNumber < 25) {
show "Dica: O número é menor que 25";
} otherwise check (self.secretNumber < 50) {
show "Dica: O número está entre 25 e 50";
} otherwise {
show "Dica: O número é maior que 50";
}
}
}
// Jogar o jogo
store game = GuessingGame(100);
show "Bem-vindo ao jogo de adivinhação!";
show "Tente adivinhar um número entre 1 e 100";
game.makeGuess(30); // "Muito baixo!"
game.makeGuess(50); // "Muito alto!"
game.getHint(); // "Dica: O número está entre 25 e 50"
game.makeGuess(42); // "Parabéns!"
```
```javascript
// Em vez de:
if (condition && otherCondition || thirdCondition) { }
// PetCareScript usa:
check (condition also otherCondition either thirdCondition) { }
```
```javascript
// Declarações
store // var/let
build // function
blueprint // class
give // return
show // print/console.log
// Controle de fluxo
check // if
otherwise // else
repeat // while
again // for
// Valores especiais
yes // true
no // false
empty // null/undefined
self // this
parent // super
```
```javascript
// Lógicos
also // &&
either // ||
! // ! (mantido familiar)
// Comparação (mantidos familiares)
==, !=, <, >, <=, >=
```
```javascript
// Modules/Imports
use "math-utils" as math;
use { add, subtract } from "calculator";
// Async/Await
build async fetchData(url) {
store response = await fetch(url);
give response.json();
}
// Destructuring
store { name, age } = person;
store [first, second, ...rest] = numbers;
// Template Strings
store message = `Olá, ${name}! Você tem ${age} anos.`;
// Arrow Functions
store add = (a, b) => a + b;
// Spread Operator
store newArray = [...oldArray, newItem];
```
---
- **store**: Declarar variáveis
- **build**: Declarar funções
- **blueprint**: Declarar classes
- **give**: Retornar valores
- **show**: Imprimir/mostrar
- **check**: Condicionais (if)
- **otherwise**: Else
- **repeat**: Loop while
- **again**: Loop for
- **yes/no**: Booleanos
- **empty**: Null
- **self**: This
- **parent**: Super
- **also**: AND lógico
- **either**: OR lógico
```javascript
// Programa PetCareScript típico
store variavel = valor;
build funcao(parametros) {
// código
give resultado;
}
blueprint Classe {
build init(parametros) {
self.propriedade = valor;
}
build metodo() {
// código
}
}
store instancia = Classe(argumentos);
instancia.metodo();
```
A sintaxe do PetCareScript prioriza **legibilidade, expressividade e facilidade de aprendizado**, tornando-o ideal para iniciantes enquanto mantém poder suficiente para projetos complexos.