UNPKG

petcarescript

Version:

PetCareScript - A modern, expressive programming language designed for humans

705 lines (578 loc) 14.9 kB
# PetCareScript - Guia Completo de Sintaxe ## 🎯 Filosofia da Linguagem 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. ## 📝 Sintaxe Básica ### Comentários ```javascript // Comentário de linha única /* Comentário de múltiplas linhas */ ``` ### Declaração de Variáveis ```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; ``` ### Tipos de Dados #### Primitivos ```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; ``` #### Arrays ```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 ``` #### Objetos ```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; ``` ## 🔧 Operadores ### Operadores Aritméticos ```javascript store sum = 10 + 5; // 15 store difference = 10 - 3; // 7 store product = 4 * 6; // 24 store quotient = 15 / 3; // 5 ``` ### Operadores de Comparação ```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 ``` ### Operadores Lógicos ```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); ``` ### Operadores de Atribuição ```javascript store x = 10; x = x + 5; // x = 15 // Nota: Operadores += ainda não implementados ``` ## 🔨 Funções ### Declaração de Funções ```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 + "!"; } ``` ### Chamada de Funções ```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 ``` ### Funções com Arrays ```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; } ``` ## 🔄 Estruturas de Controle ### Condicionais #### If Simples ```javascript store age = 18; check (age >= 18) { show "Você é maior de idade"; } ``` #### If-Else ```javascript store temperature = 25; check (temperature > 30) { show "Está muito quente!"; } otherwise { show "Temperatura agradável"; } ``` #### If-ElseIf-Else ```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"; } ``` #### Condicionais Aninhadas ```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"; } ``` ### Loops #### While Loop ```javascript store counter = 0; repeat (counter < 5) { show "Contador: " + counter; counter = counter + 1; } ``` #### For Loop ```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]; } ``` #### Loops Aninhados ```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; } } ``` ## 🏗️ Programação Orientada a Objetos ### Blueprints (Classes) #### Declaração Básica ```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; } } ``` #### Instanciação e Uso ```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; ``` #### Herança ```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"; } } ``` #### Uso de Herança ```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" ``` ## 📤 Input/Output ### Saída ```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); ``` ### Funções Built-in #### Funções de Tipo ```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" ``` #### Funções de Tamanho ```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 ``` #### Funções de Tempo ```javascript store now = currentTime(); // Timestamp atual show "Tempo atual: " + now; ``` ## 🚫 Tratamento de Erros ### Try-Catch (Futuro) ```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"; } ``` ## 🔗 Exemplos Completos ### Exemplo 1: Calculadora ```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; ``` ### Exemplo 2: Lista de Tarefas ```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(); ``` ### Exemplo 3: Jogo de Adivinhação ```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!" ``` ## 🎨 Características Especiais ### 1. Sintaxe Humanizada ```javascript // Em vez de: if (condition && otherCondition || thirdCondition) { } // PetCareScript usa: check (condition also otherCondition either thirdCondition) { } ``` ### 2. Palavras-chave Expressivas ```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 ``` ### 3. Operadores Naturais ```javascript // Lógicos also // && either // || ! // ! (mantido familiar) // Comparação (mantidos familiares) ==, !=, <, >, <=, >= ``` ## 🚀 Futuras Expansões ### Recursos Planejados ```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]; ``` --- ## 📚 Resumo da Sintaxe ### Palavras-chave Principais - **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 ### Estrutura Geral ```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.