Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
🤖 Plandex → Add comprehensive examples across multiple programming languages with syntax demonstrations and advanced features.
Dane Schneider232ac38f0e8d
diff --git a/app/server/syntax/map_examples/bash_example.sh b/app/server/syntax/map_examples/bash_example.shnew file mode 100644index 00000000..b5fcadde--- /dev/null+++ b/app/server/syntax/map_examples/bash_example.sh@@ -0,0 +1,44 @@+#!/bin/bash++# Global variables+GLOBAL_VAR="Hello World"+readonly CONSTANT_VAR="This is constant"++# Function definition+function print_message() {+ local message="$1"+ echo "$message"+}++# Function with return value+get_date() {+ echo $(date +%Y-%m-%d)+}++# Array declaration+declare -a fruits=("apple" "banana" "orange")++# Associative array+declare -A user_info=(+ ["name"]="John"+ ["age"]="30"+ ["city"]="New York"+)++# Main script execution+main() {+ print_message "$GLOBAL_VAR"+ current_date=$(get_date)+ echo "Today is: $current_date"++ # Loop through array+ for fruit in "${fruits[@]}"; do+ echo "Fruit: $fruit"+ done++ # Access associative array+ echo "User ${user_info[name]} is ${user_info[age]} years old"+}++# Call main function+maindiff --git a/app/server/syntax/map_examples/c_example.c b/app/server/syntax/map_examples/c_example.cnew file mode 100644index 00000000..3c9cc1b0--- /dev/null+++ b/app/server/syntax/map_examples/c_example.c@@ -0,0 +1,90 @@+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++// Macro definitions+#define MAX_SIZE 100+#define SQUARE(x) ((x) * (x))++// Type definitions+typedef struct {+ char name[50];+ int age;+} Person;++typedef enum {+ MONDAY,+ TUESDAY,+ WEDNESDAY,+ THURSDAY,+ FRIDAY+} Weekday;++// Global variables+static const double PI = 3.14159;+int globalCounter = 0;++// Function declarations+void printPerson(const Person* p);+int factorial(int n);++// Union example+union Data {+ int i;+ float f;+ char str[20];+};++// Function pointer type+typedef int (*Operation)(int, int);++// Function implementations+int add(int a, int b) {+ return a + b;+}++int subtract(int a, int b) {+ return a - b;+}++void printPerson(const Person* p) {+ printf("Name: %s, Age: %d\n", p->name, p->age);+}++int factorial(int n) {+ if (n <= 1) return 1;+ return n * factorial(n - 1);+}++// Main function+int main() {+ // Local variable declarations+ Person person = {"John Doe", 30};+ union Data data;+ Operation op = add;++ // Using structs+ printPerson(&person);++ // Using unions+ data.i = 10;+ printf("data.i: %d\n", data.i);++ // Using function pointers+ printf("10 + 20 = %d\n", op(10, 20));+ op = subtract;+ printf("10 - 20 = %d\n", op(10, 20));++ // Using macros+ printf("Square of 5 is %d\n", SQUARE(5));++ // Using enums+ Weekday today = WEDNESDAY;+ printf("Day number: %d\n", today);++ // Using global variables+ globalCounter++;+ printf("Global counter: %d\n", globalCounter);++ return 0;+}diff --git a/app/server/syntax/map_examples/cpp_example.cpp b/app/server/syntax/map_examples/cpp_example.cppnew file mode 100644index 00000000..61b57302--- /dev/null+++ b/app/server/syntax/map_examples/cpp_example.cpp@@ -0,0 +1,119 @@+#include <iostream>+#include <memory>+#include <vector>+#include <string>+#include <functional>++// Template class+template<typename T>+class Container {+public:+ void add(T item) { items.push_back(item); }+ const std::vector<T>& getItems() const { return items; }+private:+ std::vector<T> items;+};++// Abstract base class+class Animal {+public:+ virtual ~Animal() = default;+ virtual void makeSound() const = 0;+protected:+ std::string name;+};++// Derived class with virtual inheritance+class Dog : virtual public Animal {+public:+ Dog(const std::string& dogName) { name = dogName; }+ void makeSound() const override {+ std::cout << name << " says: Woof!" << std::endl;+ }+};++// Namespace example+namespace Utils {+ // Function template+ template<typename T>+ T max(T a, T b) {+ return (a > b) ? a : b;+ }++ // Lambda function stored in variable+ const auto printer = [](const std::string& msg) {+ std::cout << "Message: " << msg << std::endl;+ };+}++// Smart pointer and move semantics example+class Resource {+public:+ Resource(const std::string& data) : data_(data) {+ std::cout << "Resource constructed" << std::endl;+ }+ ~Resource() {+ std::cout << "Resource destroyed" << std::endl;+ }+ Resource(Resource&& other) noexcept : data_(std::move(other.data_)) {}+ std::string getData() const { return data_; }+private:+ std::string data_;+};++// Static member variable and function+class Counter {+public:+ static int getCount() { return count; }+ Counter() { ++count; }+ ~Counter() { --count; }+private:+ static int count;+};+int Counter::count = 0;++// Friend function example+class Box {+ friend std::ostream& operator<<(std::ostream& os, const Box& box);+public:+ Box(int w, int h) : width(w), height(h) {}+private:+ int width;+ int height;+};++std::ostream& operator<<(std::ostream& os, const Box& box) {+ return os << "Box(" << box.width << "x" << box.height << ")";+}++// Main function+int main() {+ // Smart pointer usage+ auto resource = std::make_unique<Resource>("Hello");+ std::cout << resource->getData() << std::endl;++ // Template class usage+ Container<int> numbers;+ numbers.add(1);+ numbers.add(2);++ // Polymorphism+ std::unique_ptr<Animal> dog = std::make_unique<Dog>("Rex");+ dog->makeSound();++ // Template function+ std::cout << "Max: " << Utils::max(10, 20) << std::endl;++ // Lambda function+ Utils::printer("Hello from lambda!");++ // Counter static example+ Counter c1, c2;+ std::cout << "Count: " << Counter::getCount() << std::endl;++ // Friend function+ Box box(10, 20);+ std::cout << box << std::endl;++ return 0;+}diff --git a/app/server/syntax/map_examples/csharp_example.cs b/app/server/syntax/map_examples/csharp_example.csnew file mode 100644index 00000000..286ea084--- /dev/null+++ b/app/server/syntax/map_examples/csharp_example.cs@@ -0,0 +1,119 @@+using System;+using System.Collections.Generic;+using System.Threading.Tasks;+using System.Linq;++// Namespace declaration+namespace ExampleApp+{+ // Interface definition+ public interface IProcessor<T>+ {+ Task<T> ProcessAsync(T input);+ bool Validate(T input);+ }++ // Enum definition+ public enum Status+ {+ Pending,+ Active,+ Completed,+ Failed+ }++ // Delegate declaration+ public delegate void StatusChangedEventHandler(Status oldStatus, Status newStatus);++ // Generic class implementing interface+ public class DataProcessor<T> : IProcessor<T> where T : class+ {+ // Event declaration+ public event StatusChangedEventHandler StatusChanged;++ // Auto-implemented property+ public Status CurrentStatus { get; private set; }++ // Static field+ private static readonly Dictionary<Type, int> _processedItems = new();++ // Constructor+ public DataProcessor()+ {+ CurrentStatus = Status.Pending;+ }++ // Async method implementation+ public async Task<T> ProcessAsync(T input)+ {+ var oldStatus = CurrentStatus;+ CurrentStatus = Status.Active;+ OnStatusChanged(oldStatus, CurrentStatus);++ await Task.Delay(100); // Simulate work++ if (_processedItems.ContainsKey(typeof(T)))+ _processedItems[typeof(T)]++;+ else+ _processedItems[typeof(T)] = 1;++ CurrentStatus = Status.Completed;+ OnStatusChanged(Status.Active, CurrentStatus);++ return input;+ }++ // Interface method implementation+ public bool Validate(T input) => input != null;++ // Protected virtual method+ protected virtual void OnStatusChanged(Status oldStatus, Status newStatus)+ {+ StatusChanged?.Invoke(oldStatus, newStatus);+ }++ // Static method+ public static int GetProcessedCount<TItem>() where TItem : class+ {+ return _processedItems.GetValueOrDefault(typeof(TItem));+ }+ }++ // Record type (C# 9.0+)+ public record Person(string Name, int Age)+ {+ // Property with validation+ public string Email { get; init; } = string.Empty;+ }++ // Extension method+ public static class StringExtensions+ {+ public static int WordCount(this string str)+ {+ return str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;+ }+ }++ // Main program class+ public class Program+ {+ public static async Task Main(string[] args)+ {+ var processor = new DataProcessor<Person>();+ processor.StatusChanged += (old, @new) =>+ Console.WriteLine($"Status changed from {old} to {@new}");++ var person = new Person("John Doe", 30) { Email = "[email protected]" };++ if (processor.Validate(person))+ {+ var result = await processor.ProcessAsync(person);+ Console.WriteLine($"Processed person: {result.Name}");+ Console.WriteLine($"Word count in name: {result.Name.WordCount()}");+ }++ Console.WriteLine($"Total processed persons: {DataProcessor<Person>.GetProcessedCount<Person>()}");+ }+ }+}diff --git a/app/server/syntax/map_examples/css_example.css b/app/server/syntax/map_examples/css_example.cssnew file mode 100644index 00000000..792875e8--- /dev/null+++ b/app/server/syntax/map_examples/css_example.css@@ -0,0 +1,143 @@+/* Global variables */+:root {+ --primary-color: #3498db;+ --secondary-color: #2ecc71;+ --text-color: #2c3e50;+ --spacing-unit: 1rem;+ --border-radius: 4px;+}++/* Reset and base styles */+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++body {+ font-family: 'Arial', sans-serif;+ line-height: 1.6;+ color: var(--text-color);+}++/* Layout containers */+.container {+ max-width: 1200px;+ margin: 0 auto;+ padding: var(--spacing-unit);+}++/* Grid system */+.grid {+ display: grid;+ grid-template-columns: repeat(12, 1fr);+ gap: var(--spacing-unit);+}++/* Flexbox components */+.flex-container {+ display: flex;+ justify-content: space-between;+ align-items: center;+}++/* Component styles */+.button {+ padding: calc(var(--spacing-unit) / 2) var(--spacing-unit);+ border-radius: var(--border-radius);+ border: none;+ cursor: pointer;+ transition: background-color 0.3s ease;+}++.button:hover {+ opacity: 0.9;+}++.button--primary {+ background-color: var(--primary-color);+ color: white;+}++.button--secondary {+ background-color: var(--secondary-color);+ color: white;+}++/* Card component */+.card {+ border-radius: var(--border-radius);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+ padding: var(--spacing-unit);+}++/* Media queries */+@media screen and (max-width: 768px) {+ .grid {+ grid-template-columns: repeat(6, 1fr);+ }+}++@media screen and (max-width: 480px) {+ .grid {+ grid-template-columns: 1fr;+ }++ .flex-container {+ flex-direction: column;+ gap: var(--spacing-unit);+ }+}++/* Animation keyframes */+@keyframes fadeIn {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++.fade-in {+ animation: fadeIn 0.3s ease-in;+}++/* Form styles */+.form-group {+ margin-bottom: var(--spacing-unit);+}++.form-input {+ width: 100%;+ padding: calc(var(--spacing-unit) / 2);+ border: 1px solid #ddd;+ border-radius: var(--border-radius);+}++/* Navigation */+.nav {+ background-color: var(--primary-color);+ padding: var(--spacing-unit);+}++.nav__list {+ list-style: none;+ display: flex;+ gap: var(--spacing-unit);+}++.nav__link {+ color: white;+ text-decoration: none;+}++/* Utility classes */+.text-center { text-align: center; }+.text-right { text-align: right; }+.text-left { text-align: left; }++.mt-1 { margin-top: var(--spacing-unit); }+.mb-1 { margin-bottom: var(--spacing-unit); }+.ml-1 { margin-left: var(--spacing-unit); }+.mr-1 { margin-right: var(--spacing-unit); }diff --git a/app/server/syntax/map_examples/cue_example.cue b/app/server/syntax/map_examples/cue_example.cuenew file mode 100644index 00000000..1b30a1c7--- /dev/null+++ b/app/server/syntax/map_examples/cue_example.cue@@ -0,0 +1,95 @@+// Package definition+package example++// Import statements+import (+ "strings"+ "time"+)++// Schema definitions+#Person: {+ name: string+ age: int & >=0 & <=120+ email?: string & =~"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"+ address?: #Address+}++#Address: {+ street: string+ city: string+ country: string+ zip: string & =~"^[0-9]{5}$"+}++// Default values and constraints+#DefaultPerson: #Person & {+ name: string | *"John Doe"+ age: int | *30+}++// List type definition+#Team: {+ name: string+ members: [...#Person]+ leader: #Person+}++// Computed fields+#Employee: #Person & {+ role: string+ salary: float+ taxRate: float++ // Computed field+ netSalary: salary * (1 - taxRate)+}++// Concrete values+exampleTeam: #Team & {+ name: "Engineering"+ members: [+ {+ name: "Alice Smith"+ age: 28+ email: "[email protected]"+ },+ {+ name: "Bob Jones"+ age: 35+ email: "[email protected]"+ }+ ]+ leader: {+ name: "Carol Wilson"+ age: 40+ email: "[email protected]"+ }+}++// Configuration with references and templates+#Config: {+ environment: "development" | "staging" | "production"+ database: {+ host: string+ port: int & >0 & <65536+ username: string+ password: string+ }+ features: [string]: bool+}++// Template usage+productionConfig: #Config & {+ environment: "production"+ database: {+ host: "db.example.com"+ port: 5432+ username: "admin"+ password: "secret"+ }+ features: {+ "feature1": true+ "feature2": false+ }+}diff --git a/app/server/syntax/map_examples/dockerfile_example b/app/server/syntax/map_examples/dockerfile_examplenew file mode 100644index 00000000..9b7ca690--- /dev/null+++ b/app/server/syntax/map_examples/dockerfile_example@@ -0,0 +1,67 @@+# Multi-stage build example+FROM golang:1.21-alpine AS builder++# Build arguments+ARG VERSION=1.0.0+ARG BUILD_DATE++# Set working directory+WORKDIR /app++# Copy only necessary files for dependency resolution+COPY go.mod go.sum ./++# Download dependencies+RUN go mod download++# Copy source code+COPY . .++# Build the application+RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-X main.Version=${VERSION} -X main.BuildDate=${BUILD_DATE}" -o /app/server++# Create final lightweight image+FROM alpine:latest++# Labels for metadata+LABEL maintainer="[email protected]" \+ version="${VERSION}" \+ description="Example Dockerfile with various syntax elements"++# Environment variables+ENV APP_ENV=production \+ PORT=8080++# Create non-root user+RUN addgroup -S appgroup && adduser -S appuser -G appgroup++# Install runtime dependencies+RUN apk add --no-cache \+ ca-certificates \+ tzdata++# Set working directory+WORKDIR /app++# Copy binary from builder stage+COPY --from=builder /app/server .++# Copy configuration files+COPY config/production.yaml /etc/app/config.yaml++# Create volume mount points+VOLUME ["/data", "/logs"]++# Expose ports+EXPOSE 8080 8443++# Switch to non-root user+USER appuser++# Health check+HEALTHCHECK --interval=30s --timeout=3s \+ CMD wget --quiet --tries=1 --spider http://localhost:${PORT}/health || exit 1++# Set entry point and default command+ENTRYPOINT ["/app/server"]+CMD ["--config", "/etc/app/config.yaml"]diff --git a/app/server/syntax/map_examples/elixir_example.ex b/app/server/syntax/map_examples/elixir_example.exnew file mode 100644index 00000000..9fdd58b2--- /dev/null+++ b/app/server/syntax/map_examples/elixir_example.ex@@ -0,0 +1,99 @@+defmodule ExampleApp do+ # Module attributes (constants)+ @default_timeout 5000+ @version "1.0.0"++ # Type specifications+ @type user :: %{+ id: integer,+ name: String.t(),+ email: String.t(),+ roles: [atom]+ }++ # Struct definition+ defstruct name: "", age: 0, email: nil++ # Behaviour definition+ @callback process(term) :: {:ok, term} | {:error, term}++ # Protocol implementation+ defimpl String.Chars, for: ExampleApp do+ def to_string(%{name: name}), do: "ExampleApp: #{name}"+ end++ # Public function with guards+ def calculate_age(birth_year) when is_integer(birth_year) do+ current_year = DateTime.utc_now().year+ current_year - birth_year+ end++ # Private function+ defp validate_email(email) do+ String.match?(email, ~r/^[^\s]+@[^\s]+\.[^\s]+$/)+ end++ # Function with pattern matching+ def handle_result({:ok, value}), do: "Success: #{value}"+ def handle_result({:error, reason}), do: "Error: #{reason}"+ def handle_result(_), do: "Unknown result"++ # Macro definition+ defmacro debug(expression) do+ quote do+ IO.puts "Debug: #{inspect(unquote(expression))}"+ end+ end++ # Using with for complex operations+ def create_user(params) do+ with {:ok, name} <- Map.fetch(params, "name"),+ {:ok, email} <- Map.fetch(params, "email"),+ true <- validate_email(email) do+ %ExampleApp{name: name, email: email}+ else+ :error -> {:error, "Missing required fields"}+ false -> {:error, "Invalid email format"}+ end+ end++ # GenServer implementation+ use GenServer++ def start_link(opts \\ []) do+ GenServer.start_link(__MODULE__, opts, name: __MODULE__)+ end++ @impl true+ def init(opts) do+ {:ok, opts}+ end++ @impl true+ def handle_call({:get_info}, _from, state) do+ {:reply, state, state}+ end++ @impl true+ def handle_cast({:update_info, new_info}, _state) do+ {:noreply, new_info}+ end++ # Using comprehensions+ def process_list(items) do+ for item <- items,+ is_binary(item),+ String.length(item) > 0,+ do: String.upcase(item)+ end++ # Exception definition+ defmodule CustomError do+ defexception message: "A custom error occurred"+ end++ # Function raising custom exception+ def raise_custom_error do+ raise CustomError, message: "Something went wrong"+ end+enddiff --git a/app/server/syntax/map_examples/elm_example.elm b/app/server/syntax/map_examples/elm_example.elmnew file mode 100644index 00000000..5fc69483--- /dev/null+++ b/app/server/syntax/map_examples/elm_example.elm@@ -0,0 +1,169 @@+module Example exposing (..)++import Browser+import Html exposing (..)+import Html.Attributes exposing (..)+import Html.Events exposing (..)+import Http+import Json.Decode as Decode exposing (Decoder)+import Json.Encode as Encode++-- MODEL++type alias Model =+ { users : List User+ , inputText : String+ , error : Maybe String+ }++type alias User =+ { id : Int+ , name : String+ , email : String+ }++init : () -> (Model, Cmd Msg)+init _ =+ ( { users = []+ , inputText = ""+ , error = Nothing+ }+ , fetchUsers+ )++-- UPDATE++type Msg+ = GotUsers (Result Http.Error (List User))+ | InputChanged String+ | AddUser+ | UserAdded (Result Http.Error User)++update : Msg -> Model -> (Model, Cmd Msg)+update msg model =+ case msg of+ GotUsers result ->+ case result of+ Ok users ->+ ( { model | users = users, error = Nothing }+ , Cmd.none+ )+ Err _ ->+ ( { model | error = Just "Failed to fetch users" }+ , Cmd.none+ )++ InputChanged text ->+ ( { model | inputText = text }+ , Cmd.none+ )++ AddUser ->+ ( model+ , addUser model.inputText+ )++ UserAdded result ->+ case result of+ Ok user ->+ ( { model+ | users = user :: model.users+ , inputText = ""+ , error = Nothing+ }+ , Cmd.none+ )+ Err _ ->+ ( { model | error = Just "Failed to add user" }+ , Cmd.none+ )++-- HTTP++fetchUsers : Cmd Msg+fetchUsers =+ Http.get+ { url = "/api/users"+ , expect = Http.expectJson GotUsers usersDecoder+ }++addUser : String -> Cmd Msg+addUser name =+ Http.post+ { url = "/api/users"+ , body = Http.jsonBody (userEncoder name)+ , expect = Http.expectJson UserAdded userDecoder+ }++-- JSON++userEncoder : String -> Encode.Value+userEncoder name =+ Encode.object+ [ ("name", Encode.string name)+ ]++userDecoder : Decoder User+userDecoder =+ Decode.map3 User+ (Decode.field "id" Decode.int)+ (Decode.field "name" Decode.string)+ (Decode.field "email" Decode.string)++usersDecoder : Decoder (List User)+usersDecoder =+ Decode.list userDecoder++-- VIEW++view : Model -> Html Msg+view model =+ div []+ [ h1 [] [ text "User Management" ]+ , viewError model.error+ , viewInput model.inputText+ , viewUsers model.users+ ]++viewError : Maybe String -> Html Msg+viewError maybeError =+ case maybeError of+ Just error ->+ div [ class "error" ] [ text error ]+ Nothing ->+ text ""++viewInput : String -> Html Msg+viewInput inputText =+ div []+ [ input+ [ value inputText+ , onInput InputChanged+ , placeholder "Enter user name"+ ] []+ , button [ onClick AddUser ] [ text "Add User" ]+ ]++viewUsers : List User -> Html Msg+viewUsers users =+ div []+ [ h2 [] [ text "Users" ]+ , ul [] (List.map viewUser users)+ ]++viewUser : User -> Html Msg+viewUser user =+ li []+ [ text (user.name ++ " (" ++ user.email ++ ")")+ ]++-- MAIN++main : Program () Model Msg+main =+ Browser.element+ { init = init+ , update = update+ , view = view+ , subscriptions = \_ -> Sub.none+ }diff --git a/app/server/syntax/map_examples/go_example.go b/app/server/syntax/map_examples/go_example.gonew file mode 100644index 00000000..b9ae30d0--- /dev/null+++ b/app/server/syntax/map_examples/go_example.go@@ -0,0 +1,165 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "log"+ "sync"+ "time"+)++// Interface definition+type DataProcessor interface {+ Process(ctx context.Context, data interface{}) error+ Validate(data interface{}) bool+}++// Custom error type+type ValidationError struct {+ Field string+ Message string+}++func (e *ValidationError) Error() string {+ return fmt.Sprintf("validation error on field %s: %s", e.Field, e.Message)+}++// Struct with embedded type and tags+type User struct {+ sync.Mutex+ ID int64 `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at,omitempty"`+}++// Type alias and constants+type UserID = int64++const (+ MaxRetries = 3+ DefaultLimit = 100+)++// Global variables+var (+ defaultTimeout = time.Second * 30+ processor DataProcessor+)++// Generic type+type Result[T any] struct {+ Data T+ Error error+ Retries int+}++// Implementation of DataProcessor+type UserProcessor struct {+ cache map[UserID]*User+ mu sync.RWMutex+}++func NewUserProcessor() *UserProcessor {+ return &UserProcessor{+ cache: make(map[UserID]*User),+ }+}++func (p *UserProcessor) Process(ctx context.Context, data interface{}) error {+ user, ok := data.(*User)+ if !ok {+ return fmt.Errorf("invalid data type: expected *User")+ }++ p.mu.Lock()+ defer p.mu.Unlock()++ p.cache[user.ID] = user+ return nil+}++func (p *UserProcessor) Validate(data interface{}) bool {+ user, ok := data.(*User)+ return ok && user.Name != "" && user.Email != ""+}++// Channel operations+func processUsers(ctx context.Context, users <-chan *User) <-chan *Result[*User] {+ results := make(chan *Result[*User])++ go func() {+ defer close(results)+ for user := range users {+ select {+ case <-ctx.Done():+ return+ case results <- &Result[*User]{Data: user}:+ }+ }+ }()++ return results+}++// Function with multiple return values and named returns+func createUser(name, email string) (user *User, err error) {+ defer func() {+ if r := recover(); r != nil {+ err = fmt.Errorf("panic recovered: %v", r)+ }+ }()++ user = &User{+ Name: name,+ Email: email,+ CreatedAt: time.Now(),+ }++ if !processor.Validate(user) {+ return nil, &ValidationError{Field: "user", Message: "invalid user data"}+ }++ return user, nil+}++func main() {+ ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)+ defer cancel()++ processor = NewUserProcessor()++ users := make(chan *User)+ results := processUsers(ctx, users)++ // Anonymous struct+ config := struct {+ Workers int+ Buffer int+ }{+ Workers: 3,+ Buffer: 10,+ }++ var wg sync.WaitGroup+ wg.Add(config.Workers)++ for i := 0; i < config.Workers; i++ {+ go func(id int) {+ defer wg.Done()+ for result := range results {+ if result.Error != nil {+ log.Printf("Worker %d: Error processing user: %v", id, result.Error)+ continue+ }+ log.Printf("Worker %d: Processed user: %+v", id, result.Data)+ }+ }(i)+ }++ // Cleanup+ close(users)+ wg.Wait()+}diff --git a/app/server/syntax/map_examples/groovy_example.groovy b/app/server/syntax/map_examples/groovy_example.groovynew file mode 100644index 00000000..d85fcc2b--- /dev/null+++ b/app/server/syntax/map_examples/groovy_example.groovy@@ -0,0 +1,161 @@+#!/usr/bin/env groovy++// Trait definition+trait Loggable {+ def log(String message) {+ println "[${new Date()}] $message"+ }+}++// Abstract class+abstract class Vehicle {+ String make+ String model+ Integer year++ abstract void start()+ abstract void stop()+}++// Class with trait implementation+class Car extends Vehicle implements Loggable {+ // Properties with type definitions+ private BigDecimal price+ protected Boolean running = false++ // Static fields+ static final String MANUFACTURER = "Generic Motors"+ static def carCount = 0++ // Constructor with default parameters+Car(String make = 'Unknown', String model = 'Generic', Integer year = 2024) {+ this.make = make+ this.model = model+ this.year = year+ carCount+++}++ // Getter with @Lazy annotation+ @Lazy+ String fullName = "$make $model ($year)"++ // Method implementation with closure parameter+ void start() {+ running = true+ log "Starting ${fullName}"+ withLock {+ // Some synchronized code+ println "Engine started"+ }+ }++ void stop() {+ running = false+ log "Stopping ${fullName}"+ }++ // Operator overloading+ def plus(Car other) {+ new Car(+make: "${this.make}-${other.make}",+model: "${this.model}-${other.model}",+year: Math.max(this.year, other.year)+ )+ }++ // Property with custom getter/setter+ private BigDecimal _price+ void setPrice(BigDecimal price) {+ if (price < 0) throw new IllegalArgumentException("Price cannot be negative")+ this._price = price+ }+ BigDecimal getPrice() { _price }+}++// Enum definition+enum Status {+ACTIVE('A'),+INACTIVE('I'),+PENDING('P')++ final String code++ private Status(String code) {+ this.code = code+ }++ String toString() { code }+}++// Category class+class StringExtensions {+ static String truncate(String self, Integer length) {+ self.size() <= length ? self : self[0..<length] + "..."+ }+}++// Builder pattern using closure+class EmailBuilder {+ private def email = [:]++ EmailBuilder to(String recipient) {+ email.to = recipient+ this+ }++ EmailBuilder from(String sender) {+ email.from = sender+ this+ }++ EmailBuilder subject(String subject) {+ email.subject = subject+ this+ }++ EmailBuilder body(@DelegatesTo(strategy=Closure.DELEGATE_FIRST) Closure body) {+ def builder = new StringBuilder()+ body.delegate = builder+ body.resolveStrategy = Closure.DELEGATE_FIRST+ body()+ email.body = builder.toString()+ this+ }++ Map build() {+ email.clone() as Map+ }+}++// Main script execution+def main() {+ use(StringExtensions) {+ def description = "This is a very long description that needs truncating"+ println description.truncate(20)+ }++ def car = new Car(make: "Tesla", model: "Model S")+ car.start()+def email = new EmailBuilder()+ .to("[email protected]")+ .from("[email protected]")+ .subject("Test Email")+ .body {+ append "Hello,\n"+ append "This is a test email.\n"+ append "Regards"+ }+ .build()+ .build()++ println email+}++if (this.metaClass.getMetaProperty('main')) {+ main()+}+ main()+}+}++diff --git a/app/server/syntax/map_examples/hcl_example.hcl b/app/server/syntax/map_examples/hcl_example.hclnew file mode 100644index 00000000..fe25246e--- /dev/null+++ b/app/server/syntax/map_examples/hcl_example.hcl@@ -0,0 +1,128 @@+# Variable definitions+variable "environment" {+ type = string+ description = "Deployment environment"+ default = "development"+ validation {+ condition = contains(["development", "staging", "production"], var.environment)+ error_message = "Environment must be development, staging, or production."+ }+}++# Local values+locals {+ common_tags = {+ Environment = var.environment+ Project = "example"+ ManagedBy = "terraform"+ }++ region_config = {+ us-east-1 = {+ instance_type = "t3.micro"+ az_count = 2+ }+ us-west-2 = {+ instance_type = "t3.small"+ az_count = 3+ }+ }+}++# Provider configuration+provider "aws" {+ region = "us-west-2"++ assume_role {+ role_arn = "arn:aws:iam::123456789012:role/terraform"+ }++ default_tags {+ tags = local.common_tags+ }+}++# Data source+data "aws_availability_zones" "available" {+ state = "available"+}++# Resource block with dynamic blocks+resource "aws_security_group" "example" {+ name_prefix = "example-sg"+ vpc_id = aws_vpc.main.id++ dynamic "ingress" {+ for_each = var.service_ports+ content {+ from_port = ingress.value+ to_port = ingress.value+ protocol = "tcp"+ cidr_blocks = ["0.0.0.0/0"]+ }+ }++ egress {+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ lifecycle {+ create_before_destroy = true+ }+}++# Module usage+module "vpc" {+ source = "terraform-aws-modules/vpc/aws"++ name = "example-vpc"+ cidr = "10.0.0.0/16"++ azs = data.aws_availability_zones.available.names+ private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]+ public_subnets = ["10.0.101.0/24", "10.0.102.0/24"]++ enable_nat_gateway = true+ single_nat_gateway = true++ tags = merge(+ local.common_tags,+ {+ Name = "example-vpc"+ }+ )+}++# Output values+output "vpc_id" {+ description = "The ID of the VPC"+ value = module.vpc.vpc_id+}++output "private_subnets" {+ description = "List of private subnet IDs"+ value = module.vpc.private_subnets+}++# Terraform settings block+terraform {+ required_version = ">= 1.0.0"++ required_providers {+ aws = {+ source = "hashicorp/aws"+ version = "~> 4.0"+ }+ }++ backend "s3" {+ bucket = "terraform-state-example"+ key = "example/terraform.tfstate"+ region = "us-west-2"+ encrypt = true+ dynamodb_table = "terraform-locks"+ }+}diff --git a/app/server/syntax/map_examples/html_example.html b/app/server/syntax/map_examples/html_example.htmlnew file mode 100644index 00000000..74a39b64--- /dev/null+++ b/app/server/syntax/map_examples/html_example.html@@ -0,0 +1,151 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <!-- Example HTML file demonstrating various HTML syntax elements -->+ <title>HTML Syntax Example</title>+ <link rel="stylesheet" href="styles.css">+ <script defer src="main.js"></script>+</head>++<body>+ <!-- Header section with navigation -->+ <header class="main-header" role="banner">+ <nav class="main-nav" aria-label="Main navigation">+ <ul class="nav-list">+ <li><a href="#home" class="nav-link active">Home</a></li>+ <li><a href="#about" class="nav-link">About</a></li>+ <li><a href="#contact" class="nav-link">Contact</a></li>+ </ul>+ </nav>+ </header>++ <!-- Main content area -->+ <main id="main-content" role="main">+ <!-- Hero section -->+ <section class="hero" aria-labelledby="hero-title">+ <h1 id="hero-title">Welcome to Our Site</h1>+ <p class="lead">This is an example of semantic HTML structure.</p>+ </section>++ <!-- Article with sections -->+ <article class="content-article">+ <header>+ <h2>Main Article</h2>+ <p class="article-meta">Published on <time datetime="2024-02-20">February 20, 2024</time></p>+ </header>++ <section class="article-section">+ <h3>Section One</h3>+ <p>This section demonstrates text content with <em>emphasis</em> and <strong>strong importance</strong>.</p>+ <figure>+ <img src="example.jpg" alt="Example image" width="600" height="400">+ <figcaption>An example image with caption</figcaption>+ </figure>+ </section>++ <section class="article-section">+ <h3>Interactive Elements</h3>+ <!-- Form example -->+ <form class="contact-form" action="/submit" method="POST">+ <fieldset>+ <legend>Contact Information</legend>++ <div class="form-group">+ <label for="name">Name:</label>+ <input type="text" id="name" name="name" required+ placeholder="Enter your name">+ </div>++ <div class="form-group">+ <label for="email">Email:</label>+ <input type="email" id="email" name="email" required+ placeholder="Enter your email">+ </div>++ <div class="form-group">+ <label for="message">Message:</label>+ <textarea id="message" name="message" rows="4"+ placeholder="Your message"></textarea>+ </div>++ <button type="submit" class="btn btn-primary">Send Message</button>+ </fieldset>+ </form>+ </section>++ <!-- Table example -->+ <section class="article-section">+ <h3>Data Table</h3>+ <table class="data-table">+ <caption>Monthly Sales Data</caption>+ <thead>+ <tr>+ <th scope="col">Month</th>+ <th scope="col">Sales</th>+ <th scope="col">Growth</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <th scope="row">January</th>+ <td>$10,000</td>+ <td>5%</td>+ </tr>+ <tr>+ <th scope="row">February</th>+ <td>$12,000</td>+ <td>20%</td>+ </tr>+ </tbody>+ <tfoot>+ <tr>+ <th scope="row">Total</th>+ <td>$22,000</td>+ <td>25%</td>+ </tr>+ </tfoot>+ </table>+ </section>+ </article>++ <!-- Aside content -->+ <aside class="sidebar" role="complementary">+ <h2>Related Information</h2>+ <div class="widget">+ <h3>Categories</h3>+ <ul class="category-list">+ <li><a href="#tech">Technology</a></li>+ <li><a href="#design">Design</a></li>+ <li><a href="#business">Business</a></li>+ </ul>+ </div>+ </aside>+ </main>++ <!-- Footer section -->+ <footer class="site-footer" role="contentinfo">+ <div class="footer-content">+ <p>© 2024 Example Site. All rights reserved.</p>+ <address>+ Contact us at: <a href="mailto:[email protected]">[email protected]</a>+ </address>+ </div>+ </footer>++ <!-- Dialog for modal content -->+ <dialog id="modal" class="modal">+ <header>+ <h2>Modal Title</h2>+ <button type="button" class="close-button" aria-label="Close modal">×</button>+ </header>+ <div class="modal-content">+ <p>This is an example of the dialog element for modal content.</p>+ </div>+ <footer>+ <button type="button" class="btn">Close</button>+ </footer>+ </dialog>+</body>+</html>diff --git a/app/server/syntax/map_examples/java_example.java b/app/server/syntax/map_examples/java_example.javanew file mode 100644index 00000000..4d4b5bff--- /dev/null+++ b/app/server/syntax/map_examples/java_example.java@@ -0,0 +1,180 @@+package example;++import java.util.*;+import java.util.concurrent.*;+import java.util.function.*;+import java.util.stream.*;+import java.time.*;++// Generic interface with type bounds+interface DataProcessor<T extends Comparable<T>> {+ CompletableFuture<T> processAsync(T input);+ boolean validate(T input);+}++// Enum with methods and fields+enum Status {+ PENDING("P"),+ ACTIVE("A"),+ COMPLETED("C"),+ FAILED("F");++ private final String code;++ Status(String code) {+ this.code = code;+ }++ public String getCode() {+ return code;+ }+}++// Abstract class with generic type+abstract class BaseEntity<ID> {+ protected ID id;+ protected LocalDateTime createdAt;+ protected LocalDateTime updatedAt;++ public abstract void validate();+}++// Record type (Java 16+)+record UserDTO(+ String name,+ String email,+ Set<String> roles+) {}++// Annotation definition+@interface Audited {+ String value() default "";+ boolean required() default true;+}++// Main class with various Java features+public class Example extends BaseEntity<UUID> implements DataProcessor<String> {+ // Static fields and initialization block+ private static final int MAX_RETRIES = 3;+ private static final Map<String, Integer> CACHE;++ static {+ CACHE = new ConcurrentHashMap<>();+ }++ // Instance fields with different access modifiers+ private final Queue<String> queue;+ protected Status status;+ @Audited+ public String name;++ // Constructor with builder pattern+ private Example(Builder builder) {+ this.queue = new LinkedBlockingQueue<>();+ this.status = Status.PENDING;+ this.name = builder.name;+ }++ // Builder static class+ public static class Builder {+ private String name;++ public Builder name(String name) {+ this.name = name;+ return this;+ }++ public Example build() {+ return new Example(this);+ }+ }++ // Interface implementation+ @Override+ public CompletableFuture<String> processAsync(String input) {+ return CompletableFuture.supplyAsync(() -> {+ try {+ queue.offer(input);+ return input.toUpperCase();+ } catch (Exception e) {+ throw new CompletionException(e);+ }+ });+ }++ @Override+ public boolean validate(String input) {+ return input != null && !input.isEmpty();+ }++ // Abstract method implementation+ @Override+ public void validate() {+ if (name == null || name.isEmpty()) {+ throw new IllegalStateException("Name is required");+ }+ }++ // Generic method with wildcards+ public <T extends Comparable<? super T>> List<T> sort(Collection<T> items) {+ return items.stream()+ .sorted()+ .collect(Collectors.toList());+ }++ // Method with functional interfaces+ public void processItems(+ List<String> items,+ Predicate<String> filter,+ Consumer<String> processor+ ) {+ items.stream()+ .filter(filter)+ .forEach(processor);+ }++ // Exception class+ public static class ProcessingException extends RuntimeException {+ public ProcessingException(String message) {+ super(message);+ }+ }++ // Main method demonstrating usage+ public static void main(String[] args) {+ var example = new Builder()+ .name("Test Example")+ .build();++ // Lambda and method reference usage+ List<String> items = Arrays.asList("a", "b", "c");+ example.processItems(+ items,+ String::isEmpty,+ System.out::println+ );++ // Stream API usage+ Map<Status, Long> statusCounts = items.stream()+ .map(s -> Status.PENDING)+ .collect(Collectors.groupingBy(+ status -> status,+ Collectors.counting()+ ));++ // CompletableFuture with exception handling+ example.processAsync("test")+ .thenApply(String::toLowerCase)+ .exceptionally(throwable -> {+ System.err.println("Error: " + throwable.getMessage());+ return "";+ });++ // Try-with-resources and Optional usage+ try (var scanner = new Scanner(System.in)) {+ Optional.of(scanner.nextLine())+ .filter(example::validate)+ .ifPresent(example::processAsync);+ }+ }+}diff --git a/app/server/syntax/map_examples/javascript_example.js b/app/server/syntax/map_examples/javascript_example.jsnew file mode 100644index 00000000..55dcea97--- /dev/null+++ b/app/server/syntax/map_examples/javascript_example.js@@ -0,0 +1,153 @@+// ES Module imports+import { EventEmitter } from 'events';+import { promisify } from 'util';++// Global constants+const MAX_RETRIES = 3;+const DEFAULT_TIMEOUT = 5000;++// Symbol for private properties+const privateState = Symbol('privateState');++// Class using ES6+ features+class DataProcessor extends EventEmitter {+ // Private class field+ #cache = new Map();++ // Static class field+ static version = '1.0.0';++ // Constructor with parameter destructuring+ constructor({ maxRetries = MAX_RETRIES, timeout = DEFAULT_TIMEOUT } = {}) {+ super();+ this[privateState] = { maxRetries, timeout };+ }++ // Async method with error handling+ async processData(data) {+ try {+ const result = await this.#validateAndTransform(data);+ this.emit('processed', result);+ return result;+ } catch (error) {+ this.emit('error', error);+ throw error;+ }+ }++ // Private method+ async #validateAndTransform(data) {+ if (!data) throw new Error('Data is required');+ return { ...data, timestamp: Date.now() };+ }++ // Generator method+ *iterateCache() {+ for (const [key, value] of this.#cache) {+ yield { key, value };+ }+ }+}+++// Decorator function (stage 3 proposal)+function deprecated(target, context) {+ if (context.kind === 'method') {+ const originalMethod = target;+ return function(...args) {+ console.warn(`Warning: ${context.name} is deprecated`);+ return originalMethod.apply(this, args);+ };+ }+}++// Proxy example+const handler = {+ get(target, prop) {+ return prop in target ? target[prop] : 'Property not found';+ }+};++const proxy = new Proxy({}, handler);++// Promise-based utility function+const delay = ms => new Promise(resolve => setTimeout(resolve, ms));++// Async generator function+async function* generateSequence(start, end) {+ for (let i = start; i <= end; i++) {+ await delay(100);+ yield i;+ }+}++// Higher-order function+const memoize = (fn) => {+ const cache = new Map();+ return (...args) => {+ const key = JSON.stringify(args);+ if (cache.has(key)) return cache.get(key);+ const result = fn.apply(this, args);+ cache.set(key, result);+ return result;+ };+};++// Custom error class+class ValidationError extends Error {+ constructor(message, field) {+ super(message);+ this.name = 'ValidationError';+ this.field = field;+ }+}++// Object with getter/setter+const config = {+ _theme: 'light',+ get theme() {+ return this._theme;+ },+ set theme(value) {+ if (!['light', 'dark'].includes(value)) {+ throw new ValidationError('Invalid theme', 'theme');+ }+ this._theme = value;+ }+};++// Array methods and destructuring+const processItems = (items) => {+ const [first, ...rest] = items;+ return rest+ .filter(item => item != null)+ .map(item => ({ ...item, processed: true }))+ .reduce((acc, curr) => {+ acc[curr.id] = curr;+ return acc;+ }, {});+};++// Async/await with Promise.all+const fetchData = async (urls) => {+ try {+ const responses = await Promise.all(+ urls.map(url => fetch(url).then(res => res.json()))+ );+ return responses;+ } catch (error) {+ console.error('Failed to fetch data:', error);+ throw error;+ }+};++// Export statement+export {+ DataProcessor,+ ValidationError,+ processItems,+ fetchData,+ delay,+ memoize,+ config+};diff --git a/app/server/syntax/map_examples/kotlin_example.kt b/app/server/syntax/map_examples/kotlin_example.ktnew file mode 100644index 00000000..4d7497c8--- /dev/null+++ b/app/server/syntax/map_examples/kotlin_example.kt@@ -0,0 +1,149 @@+// Package declaration+package example++// Imports+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.*+import java.time.LocalDateTime+import kotlin.properties.Delegates++// Interface with generic type parameter+interface DataProcessor<T> {+ suspend fun process(data: T): Result<T>+ fun validate(data: T): Boolean+}++// Sealed class for representing states+sealed class ProcessingState<out T> {+ object Loading : ProcessingState<Nothing>()+ data class Success<T>(val data: T) : ProcessingState<T>()+ data class Error(val exception: Throwable) : ProcessingState<Nothing>()+}++// Data class with default parameters+data class User(+ val id: String,+ val name: String,+ val email: String,+ val roles: Set<Role> = emptySet(),+ val createdAt: LocalDateTime = LocalDateTime.now()+)++// Enum class with properties and function+enum class Role(val permission: Int) {+ ADMIN(0xFF) {+ override fun toString() = "Administrator"+ },+ USER(0x0F) {+ override fun toString() = "Regular User"+ },+ GUEST(0x00) {+ override fun toString() = "Guest User"+ }+}++// Object declaration (Singleton)+object Configuration {+ const val API_VERSION = "1.0.0"+ val defaultTimeout = 5000L++ fun getConfig(key: String) = config[key]++ private val config = mutableMapOf<String, Any>()+}++// Class with companion object and delegation+class UserProcessor : DataProcessor<User> {+ // Companion object with factory method+ companion object {+ fun create(): UserProcessor = UserProcessor()+ }++ // Property delegation+ private var processingCount: Int by Delegates.observable(0) { _, old, new ->+ println("Processing count changed from $old to $new")+ }++ // Property with custom getter+ val isActive: Boolean+ get() = processingCount > 0++ // Suspending function implementation+ override suspend fun process(data: User): Result<User> = runCatching {+ processingCount+++ validateEmail(data.email)+ data+ }.also {+ processingCount--+ }++ // Regular function implementation+ override fun validate(data: User): Boolean =+ data.email.isNotBlank() && data.name.isNotBlank()++ // Extension function+ private fun String.isValidEmail(): Boolean =+ matches(Regex("^[A-Za-z0-9+_.-]+@(.+)$"))++ // Inline function with reified type parameter+ inline fun <reified T> logType() =+ println("Processing type: ${T::class.simpleName}")++ // Private function using extension function+ private fun validateEmail(email: String) {+ require(email.isValidEmail()) { "Invalid email format" }+ }+}++// Higher-order function with function type parameter+fun <T> withRetry(+ times: Int = 3,+ action: suspend () -> T+): suspend () -> T = {+ var lastException: Exception? = null+ repeat(times) { attempt ->+ try {+ return@withRetry action()+ } catch (e: Exception) {+ lastException = e+ println("Attempt ${attempt + 1} failed: ${e.message}")+ }+ }+ throw lastException ?: IllegalStateException("All attempts failed")+}++// Coroutine scope extension+fun CoroutineScope.processUsers(users: List<User>): Flow<ProcessingState<User>> = flow {+ val processor = UserProcessor.create()++ emit(ProcessingState.Loading)++ users.forEach { user ->+ processor.process(user)+ .onSuccess { emit(ProcessingState.Success(it)) }+ .onFailure { emit(ProcessingState.Error(it)) }+ }+}++// Extension property+val User.displayName: String+ get() = "$name (${email})"++// Main function demonstrating usage+suspend fun main() = coroutineScope {+ val users = listOf(+ User("1", "John Doe", "[email protected]"),+ User("2", "Jane Smith", "[email protected]", setOf(Role.ADMIN))+ )++ launch {+ processUsers(users)+ .collect { state ->+ when (state) {+ is ProcessingState.Loading -> println("Processing started")+ is ProcessingState.Success -> println("Processed: ${state.data.displayName}")+ is ProcessingState.Error -> println("Error: ${state.exception.message}")+ }+ }+ }+}diff --git a/app/server/syntax/map_examples/lua_example.lua b/app/server/syntax/map_examples/lua_example.luanew file mode 100644index 00000000..78d1ce02--- /dev/null+++ b/app/server/syntax/map_examples/lua_example.lua@@ -0,0 +1,157 @@+-- Module definition+local Example = {}++-- Constants+local MAX_RETRIES = 3+local DEFAULT_TIMEOUT = 5000++-- Private functions (local)+local function validateInput(input)+ if type(input) ~= "string" then+ error("Input must be a string")+ end+ return true+end++-- Metatable for creating classes+local function createClass(name)+ local cls = {}+ cls.__index = cls+ cls.__name = name++ -- Constructor+ function cls.new(...)+ local self = setmetatable({}, cls)+ if self.init then+ self:init(...)+ end+ return self+ end++ return cls+end++-- Class definition using metatables+local User = createClass("User")++function User:init(name, age)+ self.name = name+ self.age = age+ self.created_at = os.time()+end++function User:toString()+ return string.format("User(%s, %d)", self.name, self.age)+end++-- Table with custom metamethods+local DataStore = {+ data = {},+ __newindex = function(t, k, v)+ print("Setting value:", k, v)+ rawset(t.data, k, v)+ end,+ __index = function(t, k)+ return t.data[k]+ end+}+setmetatable(DataStore, DataStore)++-- Coroutine example+local function producer()+ return coroutine.create(function()+ for i = 1, 5 do+ coroutine.yield(i)+ end+ end)+end++-- Iterator function+local function range(from, to, step)+ step = step or 1+ local i = from - step+ return function()+ i = i + step+ if i <= to then+ return i+ end+ end+end++-- Module functions+function Example.process(input)+ assert(validateInput(input))++ local result = {+ original = input,+ processed = string.upper(input),+ timestamp = os.time()+ }++ return result+end++-- Function with multiple returns+function Example.divide(a, b)+ if b == 0 then+ return nil, "Division by zero"+ end+ return a / b+end++-- Closure example+function Example.counter(initial)+ local count = initial or 0+ return function()+ count = count + 1+ return count+ end+end++-- Table manipulation+function Example.merge(t1, t2)+ local result = {}+ for k, v in pairs(t1) do+ result[k] = v+ end+ for k, v in pairs(t2) do+ result[k] = v+ end+ return result+end++-- Pattern matching example+function Example.extractEmails(text)+ local emails = {}+ for email in string.gmatch(text, "[%w%.%-_]+@[%w%.%-_]+%.%w+") do+ table.insert(emails, email)+ end+ return emails+end++-- Event handling system+local EventEmitter = createClass("EventEmitter")++function EventEmitter:init()+ self.handlers = {}+end++function EventEmitter:on(event, handler)+ self.handlers[event] = self.handlers[event] or {}+ table.insert(self.handlers[event], handler)+end++function EventEmitter:emit(event, ...)+ if self.handlers[event] then+ for _, handler in ipairs(self.handlers[event]) do+ handler(...)+ end+ end+end++-- Add classes to module+Example.User = User+Example.EventEmitter = EventEmitter++-- Module return+return Examplediff --git a/app/server/syntax/map_examples/ocaml_example.ml b/app/server/syntax/map_examples/ocaml_example.mlnew file mode 100644index 00000000..5193bc94--- /dev/null+++ b/app/server/syntax/map_examples/ocaml_example.ml@@ -0,0 +1,164 @@+(* Module signature *)+module type DataProcessor = sig+ type 'a t+ val create : unit -> 'a t+ val process : 'a t -> 'a -> ('a, string) result+ val validate : 'a -> bool+end++(* Module implementation *)+module StringProcessor : DataProcessor with type 'a = string = struct+type 'a = string+ type t = {+ mutable processed_count: int;+ created_at: float;+ }++ let create () = {+ processed_count = 0;+ created_at = Unix.time ();+ }++ let process t input =+ t.processed_count <- t.processed_count + 1;+ if String.length input > 0 then+ Ok (String.uppercase_ascii input)+ else+ Error "Empty input"++ let validate input =+ String.length input > 0+end++(* Type definitions *)+type user = {+ id: int;+ name: string;+ email: string;+ created_at: float;+}++type 'a result =+ | Success of 'a+ | Error of string++(* Variant type *)+type message =+ | Text of string+ | Number of int+ | Tuple of string * int+ | Record of user++(* Functor definition *)+module type Comparable = sig+ type t+ val compare : t -> t -> int+end++module MakeSet (Item : Comparable) = struct+ type element = Item.t+ type t = element list++ let empty = []++ let rec add x = function+ | [] -> [x]+ | hd :: tl as l ->+ match Item.compare x hd with+ | 0 -> l+ | n when n < 0 -> x :: l+ | _ -> hd :: add x tl++ let member x set =+ List.exists (fun y -> Item.compare x y = 0) set+end++(* Exception definition *)+exception ValidationError of string++(* Higher-order function *)+let memoize f =+ let cache = Hashtbl.create 16 in+ fun x ->+ try Hashtbl.find cache x+ with Not_found ->+ let result = f x in+ Hashtbl.add cache x result;+ result++(* Object-oriented features *)+class virtual ['a] queue = object(self)+ val mutable items = []++ method virtual push : 'a -> unit+ method virtual pop : 'a option++ method size = List.length items++ method is_empty = items = []++ method protected get_items = items+ method protected set_items new_items = items <- new_items+end++class ['a] fifo_queue = object(self)+ inherit ['a] queue++ method push item =+ self#set_items (self#get_items @ [item])++ method pop =+ match self#get_items with+ | [] -> None+ | hd::tl ->+ self#set_items tl;+ Some hd+end++(* Module for handling JSON-like data *)+module Json = struct+ type t =+ | Null+ | Bool of bool+ | Number of float+ | String of string+ | Array of t list+ | Object of (string * t) list++ let rec to_string = function+ | Null -> "null"+ | Bool b -> string_of_bool b+ | Number n -> string_of_float n+ | String s -> "\"" ^ String.escaped s ^ "\""+ | Array items ->+ "[" ^ String.concat ", " (List.map to_string items) ^ "]"+ | Object pairs ->+ let pair_to_string (k, v) =+ "\"" ^ String.escaped k ^ "\": " ^ to_string v+ in+ "{" ^ String.concat ", " (List.map pair_to_string pairs) ^ "}"+end++(* Main execution *)+let () =+ let processor = StringProcessor.create () in+ let result = StringProcessor.process processor "hello world" in+ match result with+ | Ok processed -> Printf.printf "Processed: %s\n" processed+ | Error msg -> Printf.eprintf "Error: %s\n" msg;++ let queue = new fifo_queue in+ queue#push 1;+ queue#push 2;+ queue#push 3;++ let rec print_queue () =+ match queue#pop with+ | Some item ->+ Printf.printf "Item: %d\n" item;+ print_queue ()+ | None -> ()+ in+ print_queue ()++diff --git a/app/server/syntax/map_examples/php_example.php b/app/server/syntax/map_examples/php_example.phpnew file mode 100644index 00000000..111eb53d--- /dev/null+++ b/app/server/syntax/map_examples/php_example.php@@ -0,0 +1,216 @@+<?php++declare(strict_types=1);++namespace Example;++use DateTime;+use Exception;+use InvalidArgumentException;+use JsonSerializable;+use Psr\Log\LoggerInterface;++// Interface definition+interface DataProcessor+{+ public function process(mixed $data): mixed;+ public function validate(mixed $data): bool;+}++// Trait definition+trait Loggable+{+ protected ?LoggerInterface $logger = null;++ public function setLogger(LoggerInterface $logger): void+ {+ $this->logger = $logger;+ }++ protected function log(string $message, array $context = []): void+ {+ $this->logger?->info($message, $context);+ }+}++// Abstract class+abstract class Entity implements JsonSerializable+{+ protected DateTime $createdAt;+ protected ?DateTime $updatedAt = null;++ public function __construct()+ {+ $this->createdAt = new DateTime();+ }++ abstract public function validate(): bool;++ public function jsonSerialize(): mixed+ {+ return [+ 'createdAt' => $this->createdAt->format('c'),+ 'updatedAt' => $this->updatedAt?->format('c'),+ ];+ }+}++// Enum definition (PHP 8.1+)+enum Status: string+{+ case PENDING = 'pending';+ case ACTIVE = 'active';+ case COMPLETED = 'completed';+ case FAILED = 'failed';++ public function label(): string+ {+ return match($this) {+ self::PENDING => 'Pending',+ self::ACTIVE => 'Active',+ self::COMPLETED => 'Completed',+ self::FAILED => 'Failed',+ };+ }+}++// Class implementing interface and using trait+class User extends Entity implements DataProcessor+{+ use Loggable;++ private static int $instanceCount = 0;++ public function __construct(+ private string $name,+ private string $email,+ private Status $status = Status::PENDING,+ private array $metadata = []+ ) {+ parent::__construct();+ self::$instanceCount++;+ }++ public static function getInstanceCount(): int+ {+ return self::$instanceCount;+ }++ // Property getter with validation+ public function getEmail(): string+ {+ return $this->email;+ }++ // Property setter with validation+ public function setEmail(string $email): void+ {+ if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {+ throw new InvalidArgumentException('Invalid email format');+ }+ $this->email = $email;+ $this->updatedAt = new DateTime();+ }++ // Magic method implementation+ public function __get(string $name)+ {+ return $this->metadata[$name] ?? null;+ }++ public function __set(string $name, mixed $value): void+ {+ $this->metadata[$name] = $value;+ }++ // Interface method implementations+ public function process(mixed $data): mixed+ {+ if (!is_array($data)) {+ throw new InvalidArgumentException('Data must be an array');+ }++ $this->log('Processing user data', ['user' => $this->name]);++ foreach ($data as $key => $value) {+ $this->metadata[$key] = $value;+ }++ $this->status = Status::COMPLETED;+ return $this;+ }++ public function validate(mixed $data): bool+ {+ return is_array($data) && !empty($data);+ }++ // Abstract method implementation+ public function validate(): bool+ {+ return !empty($this->name) && !empty($this->email);+ }++ // Method using arrow functions (PHP 7.4+)+ public function getMetadataValues(): array+ {+ return array_map(+ fn($value) => is_array($value) ? json_encode($value) : (string)$value,+ $this->metadata+ );+ }++ // Implementation of JsonSerializable+ public function jsonSerialize(): mixed+ {+ return [+ ...parent::jsonSerialize(),+ 'name' => $this->name,+ 'email' => $this->email,+ 'status' => $this->status->value,+ 'metadata' => $this->metadata,+ ];+ }+}++// Custom exception+class ProcessingException extends Exception+{+ public function __construct(+ string $message = "",+ private ?string $errorCode = null,+ int $code = 0,+ ?Throwable $previous = null+ ) {+ parent::__construct($message, $code, $previous);+ }++ public function getErrorCode(): ?string+ {+ return $this->errorCode;+ }+}++// Anonymous class usage+$validator = new class {+ public function validateUser(User $user): bool+ {+ return $user->validate();+ }+};++// Example usage+try {+ $user = new User("John Doe", "[email protected]");+ $user->process(['role' => 'admin', 'preferences' => ['theme' => 'dark']]);++ // Using magic methods+ $user->customField = 'custom value';+ echo $user->customField;++ // JSON serialization+ echo json_encode($user, JSON_PRETTY_PRINT);++} catch (Exception $e) {+ echo "Error: " . $e->getMessage();+}diff --git a/app/server/syntax/map_examples/protobuf_example.proto b/app/server/syntax/map_examples/protobuf_example.protonew file mode 100644index 00000000..dd0839b6--- /dev/null+++ b/app/server/syntax/map_examples/protobuf_example.proto@@ -0,0 +1,116 @@+syntax = "proto3";++package example;++import "google/protobuf/timestamp.proto";+import "google/protobuf/empty.proto";+import "google/protobuf/wrappers.proto";++option go_package = "example/generated";+option java_package = "com.example.generated";+option java_multiple_files = true;++// Enum definition+enum Status {+ STATUS_UNSPECIFIED = 0;+ STATUS_PENDING = 1;+ STATUS_ACTIVE = 2;+ STATUS_COMPLETED = 3;+ STATUS_FAILED = 4;+}++// Message with nested messages and various field types+message User {+ // Nested message definition+ message Address {+ string street = 1;+ string city = 2;+ string state = 3;+ string country = 4;+ string postal_code = 5;+ }++ // Nested enum+ enum Role {+ ROLE_UNSPECIFIED = 0;+ ROLE_ADMIN = 1;+ ROLE_USER = 2;+ ROLE_GUEST = 3;+ }++ // Fields with different types and options+ string id = 1;+ string name = 2 [(validate.rules).string = {+ min_len: 1,+ max_len: 100+ }];+ string email = 3 [(validate.rules).string.email = true];+ repeated string phone_numbers = 4;+ Role role = 5;+ Status status = 6;+ Address primary_address = 7;+ repeated Address additional_addresses = 8;+ map<string, string> metadata = 9;+ google.protobuf.Timestamp created_at = 10;+ google.protobuf.Timestamp updated_at = 11;+ oneof verification {+ string phone_verification = 12;+ string email_verification = 13;+ }+}++// Message using various repeated and map fields+message UserList {+ repeated User users = 1;+ int32 total_count = 2;+ string next_page_token = 3;+}++// Request/Response messages+message CreateUserRequest {+ User user = 1;+}++message UpdateUserRequest {+ string user_id = 1;+ User user = 2;+ google.protobuf.FieldMask update_mask = 3;+}++message GetUserRequest {+ string user_id = 1;+}++message DeleteUserRequest {+ string user_id = 1;+}++message ListUsersRequest {+ int32 page_size = 1;+ string page_token = 2;+ string filter = 3;+}++// Service definition with various RPC patterns+service UserService {+ // Unary RPC+ rpc CreateUser(CreateUserRequest) returns (User);++ // Unary RPC with custom error responses+ rpc GetUser(GetUserRequest) returns (User);++ // Unary RPC with field mask+ rpc UpdateUser(UpdateUserRequest) returns (User);++ // Unary RPC returning empty response+ rpc DeleteUser(DeleteUserRequest) returns (google.protobuf.Empty);++ // Server streaming RPC+ rpc ListUsers(ListUsersRequest) returns (stream User);++ // Client streaming RPC+ rpc BatchCreateUsers(stream CreateUserRequest) returns (UserList);++ // Bidirectional streaming RPC+ rpc ProcessUsers(stream User) returns (stream User);+}diff --git a/app/server/syntax/map_examples/python_example.py b/app/server/syntax/map_examples/python_example.pynew file mode 100644index 00000000..1dcfe14e--- /dev/null+++ b/app/server/syntax/map_examples/python_example.py@@ -0,0 +1,148 @@+#!/usr/bin/env python3+from __future__ import annotations++import asyncio+import dataclasses+import enum+from abc import ABC, abstractmethod+from datetime import datetime+from functools import wraps+from typing import (+ Any, AsyncIterator, Callable, ClassVar, Dict, Generic,+ List, Optional, Protocol, TypeVar, Union+)++# Type variable definitions+T = TypeVar('T')+K = TypeVar('K')+V = TypeVar('V')++# Protocol definition+class Processable(Protocol):+ def process(self) -> None: ...+ def validate(self) -> bool: ...++# Enum definition+class Status(enum.Enum):+ PENDING = "pending"+ ACTIVE = "active"+ COMPLETED = "completed"+ FAILED = "failed"++ def __str__(self) -> str:+ return self.value++# Dataclass with frozen and slots options[email protected](frozen=True, slots=True)+class UserCredentials:+ username: str+ email: str+ created_at: datetime = dataclasses.field(default_factory=datetime.now)++# Abstract base class+class BaseProcessor(ABC, Generic[T]):+ def __init__(self) -> None:+ self._items: List[T] = []+ self._processed_count: int = 0++ @abstractmethod+ async def process_item(self, item: T) -> None:+ pass++ @property+ def processed_count(self) -> int:+ return self._processed_count++# Decorator definition+def log_execution(func: Callable) -> Callable:+ @wraps(func)+ async def wrapper(*args: Any, **kwargs: Any) -> Any:+ print(f"Executing {func.__name__}")+ try:+ result = await func(*args, **kwargs)+ print(f"Completed {func.__name__}")+ return result+ except Exception as e:+ print(f"Error in {func.__name__}: {e}")+ raise+ return wrapper++# Class implementing abstract base class and protocol+class DataProcessor(BaseProcessor[UserCredentials], Processable):+ # Class variable+ DEFAULT_BATCH_SIZE: ClassVar[int] = 100++ def __init__(self, batch_size: Optional[int] = None) -> None:+ super().__init__()+ self.batch_size = batch_size or self.DEFAULT_BATCH_SIZE+ self._status = Status.PENDING++ # Property with getter and setter+ @property+ def status(self) -> Status:+ return self._status++ @status.setter+ def status(self, value: Status) -> None:+ if not isinstance(value, Status):+ raise ValueError("Status must be a Status enum value")+ self._status = value++ # Context manager methods+ async def __aenter__(self) -> DataProcessor:+ self.status = Status.ACTIVE+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:+ self.status = Status.COMPLETED if exc_type is None else Status.FAILED++ # Generator method+ async def process_batch(self) -> AsyncIterator[List[UserCredentials]]:+ for i in range(0, len(self._items), self.batch_size):+ batch = self._items[i:i + self.batch_size]+ yield batch+ await asyncio.sleep(0.1)++ # Implementation of abstract method+ @log_execution+ async def process_item(self, item: UserCredentials) -> None:+ if not self.validate():+ raise ValueError("Processor is not in a valid state")+ self._items.append(item)+ self._processed_count += 1++ # Implementation of protocol method+ def process(self) -> None:+ if not self._items:+ raise ValueError("No items to process")+ self.status = Status.ACTIVE++ def validate(self) -> bool:+ return self.status != Status.FAILED++# Custom exception+class ProcessingError(Exception):+ def __init__(self, message: str, item: Any) -> None:+ self.item = item+ super().__init__(f"Error processing {item}: {message}")++# Async main function+async def main() -> None:+ async with DataProcessor(batch_size=10) as processor:+ # Create test data+ user = UserCredentials(+ username="test_user",+ email="[email protected]"+ )++ try:+ await processor.process_item(user)++ async for batch in processor.process_batch():+ print(f"Processing batch of {len(batch)} items")++ except ProcessingError as e:+ print(f"Processing failed: {e}")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/app/server/syntax/map_examples/ruby_example.rb b/app/server/syntax/map_examples/ruby_example.rbnew file mode 100644index 00000000..9c7802e1--- /dev/null+++ b/app/server/syntax/map_examples/ruby_example.rb@@ -0,0 +1,172 @@+#!/usr/bin/env ruby++# Module for mixing in common functionality+module Loggable+ def log(message)+ puts "[#{Time.now}] #{message}"+ end+end++# Module with class methods+module Utils+ class << self+ def generate_id+ SecureRandom.uuid+ end+ end+end++# Abstract base class+class BaseProcessor+ include Loggable++ # Class instance variable+ @processors = []++ class << self+ attr_reader :processors++ def register(processor)+ @processors << processor+ end+ end++ # Instance variables with attr accessors+ attr_reader :id, :created_at+ attr_accessor :status++ def initialize+ @id = Utils.generate_id+ @created_at = Time.now+ @status = :pending+ self.class.register(self)+ end++ # Abstract method+ def process+ raise NotImplementedError, "#{self.class} must implement process"+ end+end++# Custom exception class+class ProcessingError < StandardError+ attr_reader :item++ def initialize(message, item)+ @item = item+ super(message)+ end+end++# Struct definition+User = Struct.new(:name, :email, keyword_init: true) do+ def valid?+ name && email && email.include?('@')+ end+end++# Enum-like module using freeze+module Status+ PENDING = 'pending'.freeze+ ACTIVE = 'active'.freeze+ COMPLETED = 'completed'.freeze+ FAILED = 'failed'.freeze++ ALL = [PENDING, ACTIVE, COMPLETED, FAILED].freeze+end++# Class using inheritance and mixins+class DataProcessor < BaseProcessor+ # Constants+ MAX_RETRIES = 3+ DEFAULT_TIMEOUT = 5++ # Class variable+ @@instance_count = 0++ def self.instance_count+ @@instance_count+ end++ def initialize(options = {})+ super()+ @options = options+ @items = []+ @@instance_count += 1+ end++ # Method with keyword arguments and default value+ def add_item(item:, priority: :normal)+ validate_item(item)+ @items << [item, priority]+ end++ # Private methods+ private++ def validate_item(item)+ raise ArgumentError, "Invalid item" unless item.respond_to?(:valid?)+ raise ProcessingError.new("Invalid item", item) unless item.valid?+ end++ # Method using block+ def with_retry+ retries = 0+ begin+ yield+ rescue StandardError => e+ retries += 1+ retry if retries < MAX_RETRIES+ raise+ end+ end++ # Method using lambda+ def process_items+ sorter = ->(a, b) { a[1] <=> b[1] }+ @items.sort(&sorter).each do |item, _priority|+ process_item(item)+ end+ end++ protected++ def process_item(item)+ log("Processing item: #{item}")+ # Processing logic here+ end+end++# Singleton class+require 'singleton'+class Configuration+ include Singleton++ def initialize+ @settings = {}+ end++ def [](key)+ @settings[key]+ end++ def []=(key, value)+ @settings[key] = value+ end+end++# Example usage+if __FILE__ == $PROGRAM_NAME+ config = Configuration.instance+ config[:timeout] = 30++ processor = DataProcessor.new(timeout: config[:timeout])+ user = User.new(name: "John Doe", email: "[email protected]")++ begin+ processor.add_item(item: user, priority: :high)+ processor.process+ rescue ProcessingError => e+ puts "Failed to process #{e.item}: #{e.message}"+ end+enddiff --git a/app/server/syntax/map_examples/rust_example.rs b/app/server/syntax/map_examples/rust_example.rsnew file mode 100644index 00000000..e19cbd33--- /dev/null+++ b/app/server/syntax/map_examples/rust_example.rs@@ -0,0 +1,139 @@+use std::{+ collections::{HashMap, HashSet},+ sync::{Arc, Mutex},+ time::{Duration, SystemTime},+};++use tokio::sync::mpsc;+use serde::{Deserialize, Serialize};++// Type alias+type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;++// Constants+const MAX_RETRIES: u32 = 3;+const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);++// Custom error type+#[derive(Debug, thiserror::Error)]+pub enum ProcessError {+ #[error("Validation failed: {0}")]+ ValidationError(String),++ #[error("Processing failed: {0}")]+ ProcessingError(String),++ #[error(transparent)]+ Other(#[from] Box<dyn std::error::Error + Send + Sync>),+}++// Trait definition+#[async_trait::async_trait]+pub trait DataProcessor<T> {+ async fn process(&self, data: T) -> Result<T>;+ fn validate(&self, data: &T) -> bool;+}++// Struct with lifetime parameter and generic type+#[derive(Debug)]+pub struct ProcessorState<'a, T> {+ name: &'a str,+ data: T,+ created_at: SystemTime,+}++// Enum with different variants+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum Status {+ Pending,+ Active { started_at: SystemTime },+ Completed { result: String },+ Failed { error: String },+}++// Struct implementing trait+pub struct ItemProcessor {+ items: Arc<Mutex<HashSet<String>>>,+ status: Status,+ tx: mpsc::Sender<String>,+}++// Trait implementation+#[async_trait::async_trait]+impl DataProcessor<String> for ItemProcessor {+ async fn process(&self, data: String) -> Result<String> {+ if !self.validate(&data) {+ return Err(Box::new(ProcessError::ValidationError("Invalid data".into())));+ }+ Ok(data.to_uppercase())+ }++ fn validate(&self, data: &String) -> bool {+ !data.is_empty()+ }+}++// Struct with derive macros+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Config {+ pub name: String,+ pub max_items: usize,+ #[serde(default)]+ pub timeout: Option<Duration>,+}+++// Implementation with associated types+pub trait Storage {+ type Item;+ type Error;++ fn store(&mut self, item: Self::Item) -> std::result::Result<(), Self::Error>;+ fn retrieve(&self, id: &str) -> std::result::Result<Option<Self::Item>, Self::Error>;+}++// Struct implementing trait with associated types+pub struct MemoryStorage {+ data: HashMap<String, Vec<u8>>,+}++impl Storage for MemoryStorage {+ type Item = Vec<u8>;+ type Error = std::io::Error;++ fn store(&mut self, item: Self::Item) -> std::result::Result<(), Self::Error> {+ self.data.insert(String::from("default"), item);+ Ok(())+ }++ fn retrieve(&self, id: &str) -> std::result::Result<Option<Self::Item>, Self::Error> {+ Ok(self.data.get(id).cloned())+ }+}++// Async main function+#[tokio::main]+async fn main() -> Result<()> {+ let (tx, mut rx) = mpsc::channel(100);+ let mut processor = ItemProcessor::new(tx);++ // Spawn background task+ tokio::spawn(async move {+ while let Some(item) = rx.recv().await {+ println!("Received: {}", item);+ }+ });++ // Process items+ processor.add_item("test".into()).await?;++ let config = Config {+ name: "test".into(),+ max_items: 100,+ timeout: Some(DEFAULT_TIMEOUT),+ };++ println!("Config: {:?}", config);++ Ok(())+}diff --git a/app/server/syntax/map_examples/scala_example.scala b/app/server/syntax/map_examples/scala_example.scalanew file mode 100644index 00000000..3852ccce--- /dev/null+++ b/app/server/syntax/map_examples/scala_example.scala@@ -0,0 +1,179 @@+package example++import scala.concurrent.{Future, ExecutionContext}+import scala.util.{Try, Success, Failure}+import scala.collection.mutable+import scala.annotation.tailrec++// Type alias+type Result[T] = Either[String, T]++// Trait with type parameter+trait DataProcessor[T] {+ def process(data: T): Result[T]+ def validate(data: T): Boolean+}++// Case class with type parameters+case class ProcessingState[T](+ data: T,+ status: ProcessingState.Status,+ timestamp: Long = System.currentTimeMillis()+)++// Companion object with sealed trait+object ProcessingState {+ sealed trait Status+ case object Pending extends Status+ case object Active extends Status+ case object Completed extends Status+ case class Failed(error: String) extends Status+}++// Abstract class+abstract class BaseProcessor[T] extends DataProcessor[T] {+ protected val logger = new Logger(getClass.getName)++ // Abstract method+ protected def transform(data: T): T++ // Concrete implementation using abstract method+ override def process(data: T): Result[T] = {+ if (!validate(data)) {+ Left("Invalid data")+ } else {+ Try(transform(data)).toEither.left.map(_.getMessage)+ }+ }+}++// Class with type bounds+class NumberProcessor[T <: Number] extends BaseProcessor[T] {+ override def validate(data: T): Boolean = data != null++ protected def transform(data: T): T = data+}++// Case class with default and optional parameters+case class User(+ id: String,+ name: String,+ email: String,+ roles: Set[String] = Set.empty,+ metadata: Map[String, String] = Map.empty+)++// Object for utility functions+object Utils {+ def withRetry[T](times: Int)(f: => T): Try[T] = {+ @tailrec+ def attempt(remaining: Int, lastError: Option[Throwable]): Try[T] = {+ if (remaining == 0) {+ Failure(lastError.getOrElse(new RuntimeException("Max retries exceeded")))+ } else {+ Try(f) match {+ case success @ Success(_) => success+ case Failure(error) => attempt(remaining - 1, Some(error))+ }+ }+ }+ attempt(times, None)+ }+}++// Implicit class for extensions+object Implicits {+ implicit class StringOps(val s: String) extends AnyVal {+ def isValidEmail: Boolean = s.matches(".+@.+\\..+")+ }+}++// Trait with self type annotation+trait Logging {+ self: Logger =>++ def debug(message: => String): Unit = log("DEBUG", message)+ def info(message: => String): Unit = log("INFO", message)+ def error(message: => String): Unit = log("ERROR", message)+}++// Class using self type trait+class Logger(name: String) extends Logging {+ def log(level: String, message: => String): Unit = {+ println(s"[$level] $name: $message")+ }+}++// Class with type constructor and higher-kinded type+trait Monad[F[_]] {+ def pure[A](a: A): F[A]+ def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]++ def map[A, B](fa: F[A])(f: A => B): F[B] =+ flatMap(fa)(a => pure(f(a)))+}++// Implicit conversions+object Conversions {+ implicit def stringToUser(s: String): User = {+ val parts = s.split(":")+ User(parts(0), parts(1), parts(2))+ }+}++// Trait with path-dependent type+trait Container {+ type Content+ def content: Content+ def transform(f: Content => Content): Container+}++// Class implementing path-dependent type+class Box[T](initial: T) extends Container {+ type Content = T+ def content: T = initial+ def transform(f: T => T): Box[T] = new Box(f(initial))+}++// Main object with application+object Main extends App {+ import Implicits._+ import ExecutionContext.Implicits.global++ val processor = new NumberProcessor[java.lang.Integer]++ def processAsync[T](data: T)(implicit ec: ExecutionContext): Future[Result[T]] = {+ Future {+ Thread.sleep(100) // Simulate work+ Right(data)+ }+ }++ // Pattern matching+ def handleResult[T](result: Result[T]): Unit = result match {+ case Right(value) => println(s"Success: $value")+ case Left(error) => println(s"Error: $error")+ }++ // For comprehension+ val computation = for {+ a <- Future(1)+ b <- Future(2)+ c <- Future(a + b)+ } yield c++ // Partial function+ val handler: PartialFunction[Throwable, Unit] = {+ case e: IllegalArgumentException => println(s"Invalid argument: ${e.getMessage}")+ case e: Exception => println(s"Other error: ${e.getMessage}")+ }++ // Using implicit conversion+ val user: User = "1:John Doe:[email protected]"++ // Using type class+ val box = new Box(42)+ val transformed = box.transform(_ * 2)++ println(s"Transformed value: ${transformed.content}")+}diff --git a/app/server/syntax/map_examples/svelte_example.svelte b/app/server/syntax/map_examples/svelte_example.sveltenew file mode 100644index 00000000..7c3868d5--- /dev/null+++ b/app/server/syntax/map_examples/svelte_example.svelte@@ -0,0 +1,183 @@+<script lang="ts">+ import { onMount, onDestroy } from 'svelte';+ import { writable, derived } from 'svelte/store';+ import type { Writable } from 'svelte/store';++ // Props with TypeScript types+ export let title: string;+ export let initialCount: number = 0;++ // Reactive declarations+ $: doubled = count * 2;+ $: {+ if (count > 10) {+ console.log('Count is getting high!');+ }+ }++ // Local state+ let count: number = initialCount;+ let inputValue: string = '';+ let mounted: boolean = false;++ // Stores+ const items: Writable<string[]> = writable([]);+ const filteredItems = derived(items, $items =>+ $items.filter(item => item.includes(inputValue))+ );++ // Event handlers+ function handleClick() {+ count += 1;+ }++ function addItem() {+ if (inputValue.trim()) {+ items.update(items => [...items, inputValue.trim()]);+ inputValue = '';+ }+ }++ function removeItem(index: number) {+ items.update(items => items.filter((_, i) => i !== index));+ }++ // Lifecycle+ onMount(() => {+ mounted = true;+ return () => {+ mounted = false;+ };+ });++ onDestroy(() => {+ console.log('Component destroyed');+ });+</script>++<!-- Markup section -->+<div class="container">+ <h1>{title}</h1>++ <!-- Event binding and reactive values -->+ <div class="counter">+ <button on:click={handleClick}>+ Count: {count}+ </button>+ <p>Doubled: {doubled}</p>+ </div>++ <!-- Form with two-way binding -->+ <div class="form">+ <input+ type="text"+ bind:value={inputValue}+ placeholder="Add item"+ on:keydown={e => e.key === 'Enter' && addItem()}+ />+ <button on:click={addItem}>Add</button>+ </div>++ <!-- Conditional rendering -->+ {#if $items.length > 0}+ <!-- List with store subscription -->+ <ul>+ {#each $filteredItems as item, index (item)}+ <li class="item">+ {item}+ <button on:click={() => removeItem(index)}>×</button>+ </li>+ {/each}+ </ul>+ {:else}+ <p>No items added yet</p>+ {/if}++ <!-- Slots for content projection -->+ <div class="content">+ <slot name="header">+ <h2>Default Header</h2>+ </slot>++ <slot>+ <p>Default content</p>+ </slot>++ <slot name="footer" />+ </div>+</div>++<style>+ .container {+ padding: 1rem;+ max-width: 600px;+ margin: 0 auto;+ }++ .counter {+ margin: 1rem 0;+ }++ .form {+ display: flex;+ gap: 0.5rem;+ margin-bottom: 1rem;+ }++ input {+ flex: 1;+ padding: 0.5rem;+ border: 1px solid #ccc;+ border-radius: 4px;+ }++ button {+ padding: 0.5rem 1rem;+ background: #4CAF50;+ color: white;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ }++ button:hover {+ background: #45a049;+ }++ ul {+ list-style: none;+ padding: 0;+ }++ .item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.5rem;+ margin: 0.25rem 0;+ background: #f5f5f5;+ border-radius: 4px;+ }++ .item button {+ background: #ff4444;+ padding: 0.25rem 0.5rem;+ }++ .item button:hover {+ background: #cc0000;+ }++ .content {+ margin-top: 2rem;+ padding: 1rem;+ border: 1px solid #ddd;+ border-radius: 4px;+ }++ /* Scoped styles - only apply to this component */+ :global(.theme-dark) .container {+ background: #333;+ color: #fff;+ }+</style>diff --git a/app/server/syntax/map_examples/swift_example.swift b/app/server/syntax/map_examples/swift_example.swiftnew file mode 100644index 00000000..e348df6c--- /dev/null+++ b/app/server/syntax/map_examples/swift_example.swift@@ -0,0 +1,181 @@+import Foundation++// Protocol definitions+protocol DataProcessor {+ associatedtype Input+ associatedtype Output++ func process(_ input: Input) async throws -> Output+ func validate(_ input: Input) -> Bool+}++// Error type+enum ProcessingError: LocalizedError {+ case invalidInput(String)+ case processingFailed(String)++ var errorDescription: String? {+ switch self {+ case .invalidInput(let reason): return "Invalid input: \(reason)"+ case .processingFailed(let reason): return "Processing failed: \(reason)"+ }+ }+}++// Property wrapper+@propertyWrapper+struct Validated<T> {+ private var value: T+ private let validator: (T) -> Bool++ var wrappedValue: T {+ get { value }+ set {+ guard validator(newValue) else {+ fatalError("Invalid value")+ }+ value = newValue+ }+ }++ init(wrappedValue: T, validator: @escaping (T) -> Bool) {+ guard validator(wrappedValue) else {+ fatalError("Invalid initial value")+ }+ self.value = wrappedValue+ self.validator = validator+ }+}++// Actor for thread-safe state management+actor ProcessingState {+ private(set) var processedCount: Int = 0+ private var status: Status = .pending++ enum Status {+ case pending+ case processing+ case completed+ case failed(Error)+ }++ func incrementCount() {+ processedCount += 1+ }++ func updateStatus(_ newStatus: Status) {+ status = newStatus+ }+}++// Generic struct with where clause+struct Queue<Element> where Element: Sendable {+ private var elements: [Element] = []+ private let lock = NSLock()++ mutating func enqueue(_ element: Element) {+ lock.lock()+ defer { lock.unlock() }+ elements.append(element)+ }++ mutating func dequeue() -> Element? {+ lock.lock()+ defer { lock.unlock() }+ return elements.isEmpty ? nil : elements.removeFirst()+ }+}++// Class inheritance and protocol conformance+class StringProcessor: DataProcessor {+ typealias Input = String+ typealias Output = String++ private let state = ProcessingState()++ @Validated(validator: { !$0.isEmpty })+ private var currentInput: String = "default"++ func process(_ input: String) async throws -> String {+ guard validate(input) else {+ throw ProcessingError.invalidInput("String is empty")+ }++ await state.updateStatus(.processing)++ // Simulate processing+ try await Task.sleep(nanoseconds: 1_000_000_000)+ let result = input.uppercased()++ await state.incrementCount()+ await state.updateStatus(.completed)++ return result+ }++ func validate(_ input: String) -> Bool {+ !input.isEmpty+ }+}++// Extension with async sequence+extension StringProcessor: AsyncSequence, AsyncIteratorProtocol {+ typealias Element = String++ func makeAsyncIterator() -> StringProcessor {+ self+ }++ func next() async throws -> String? {+ try await process(currentInput)+ }+}++// Result builders+@resultBuilder+struct ArrayBuilder<T> {+ static func buildBlock(_ components: T...) -> [T] {+ components+ }+}++// Function using result builder+func makeArray<T>(@ArrayBuilder<T> content: () -> [T]) -> [T] {+ content()+}++// Async main function demonstrating usage+@main+struct Example {+ static func main() async throws {+ let processor = StringProcessor()+ var queue = Queue<String>()++ // Using result builder+ let inputs = makeArray {+ "Hello"+ "World"+ "Swift"+ }++ // Process inputs+ for input in inputs {+ queue.enqueue(input)+ }++ // Process queue+ while let input = queue.dequeue() {+ do {+ let result = try await processor.process(input)+ print("Processed: \(result)")+ } catch {+ print("Error: \(error.localizedDescription)")+ }+ }++ // Using async sequence+ for try await result in processor.prefix(3) {+ print("Async sequence result: \(result)")+ }+ }+}diff --git a/app/server/syntax/map_examples/toml_example.toml b/app/server/syntax/map_examples/toml_example.tomlnew file mode 100644index 00000000..dad34630--- /dev/null+++ b/app/server/syntax/map_examples/toml_example.toml@@ -0,0 +1,107 @@+# This is a TOML example file demonstrating various TOML syntax elements++# Basic key/value pairs+title = "TOML Example"+version = "1.0.0"+enabled = true++# String with special characters+description = """+A multi-line string that can contain "quotes"+and other special characters like \n or \t+"""++# Date and time+created = 1979-05-27T07:32:00Z+updated = 1979-05-27T00:32:00-07:00++# Numbers+integer = 42+float = 3.14159+scientific = 1e+12+hex = 0xDEADBEEF+octal = 0o755+binary = 0b11010110++# Arrays+colors = ["red", "yellow", "green"]+numbers = [1, 2, 3]+nested_arrays = [[1, 2], [3, 4, 5]]+mixed_array = [[1, 2], ["a", "b", "c"]]++# Array of tables+[[fruits]]+name = "apple"+color = "red"+season = "fall"++[[fruits]]+name = "banana"+color = "yellow"+season = "summer"++# Tables+[server]+host = "example.com"+port = 8080+enabled = true++[server.options]+timeout = 30+max_connections = 100++[database]+url = "postgresql://localhost:5432/mydb"+max_connections = 100++[database.replica]+enabled = true+hosts = [+ "replica1.example.com",+ "replica2.example.com"+]++# Nested tables+[owner]+name = "John Doe"+[owner.preferences]+theme = "dark"+notifications = true+[owner.preferences.display]+color_scheme = "monokai"+font_size = 12++# Table with inline tables+[endpoints]+status = { url = "/status", method = "GET" }+health = { url = "/health", method = "GET", timeout = 5 }++# Complex types+[types]+primitive_array = [ "red", "yellow", "green" ]+array_of_integers = [ 1, 2, 3 ]+array_of_floats = [ 1.1, 2.2, 3.3 ]+array_of_dates = [ 1979-05-27T07:32:00Z, 1979-05-28T07:32:00Z ]+array_of_tables = [+ { x = 1, y = 2, z = 3 },+ { x = 7, y = 8, z = 9 },+ { x = 2, y = 4, z = 8 }+]++# Example configuration+[app]+name = "MyApp"+environment = "production"++[app.logging]+level = "info"+format = "json"+output = "stdout"++[app.features]+experimental = false+beta_features = ["feature1", "feature2"]++[app.limits]+requests_per_second = 1000+concurrent_connections = 50diff --git a/app/server/syntax/map_examples/tsx_example.tsx b/app/server/syntax/map_examples/tsx_example.tsxnew file mode 100644index 00000000..84c481c8--- /dev/null+++ b/app/server/syntax/map_examples/tsx_example.tsx@@ -0,0 +1,200 @@+import React, { useState, useEffect, useCallback, useRef } from 'react';+import type { FC, ReactNode, FormEvent } from 'react';++// Type definitions+interface User {+ id: string;+ name: string;+ email: string;+ role: 'admin' | 'user';+}++type ValidationResult = {+ valid: boolean;+ errors: string[];+};++// Props interface with generic type+interface DataListProps<T> {+ items: T[];+ renderItem: (item: T) => ReactNode;+ onItemSelect?: (item: T) => void;+}++// Custom hook with TypeScript+function useDebounce<T>(value: T, delay: number): T {+ const [debouncedValue, setDebouncedValue] = useState<T>(value);++ useEffect(() => {+ const timer = setTimeout(() => {+ setDebouncedValue(value);+ }, delay);++ return () => {+ clearTimeout(timer);+ };+ }, [value, delay]);++ return debouncedValue;+}++// Higher-order component with TypeScript+function withLoading<P extends object>(+ WrappedComponent: React.ComponentType<P>+): FC<P & { loading?: boolean }> {+ return ({ loading = false, ...props }) => (+ <div className="wrapper">+ {loading ? (+ <div className="loading-spinner" />+ ) : (+ <WrappedComponent {...(props as P)} />+ )}+ </div>+ );+}++// Form component with controlled inputs+const UserForm: FC<{ onSubmit: (user: Partial<User>) => void }> = ({ onSubmit }) => {+ const [formData, setFormData] = useState<Partial<User>>({+ name: '',+ email: '',+ role: 'user'+ });++ const handleSubmit = (e: FormEvent) => {+ e.preventDefault();+ onSubmit(formData);+ };++ return (+ <form onSubmit={handleSubmit} className="user-form">+ <div className="form-group">+ <label htmlFor="name">Name:</label>+ <input+ type="text"+ id="name"+ value={formData.name}+ onChange={e => setFormData(prev => ({+ ...prev,+ name: e.target.value+ }))}+ required+ />+ </div>++ <div className="form-group">+ <label htmlFor="email">Email:</label>+ <input+ type="email"+ id="email"+ value={formData.email}+ onChange={e => setFormData(prev => ({+ ...prev,+ email: e.target.value+ }))}+ required+ />+ </div>++ <div className="form-group">+ <label htmlFor="role">Role:</label>+ <select+ id="role"+ value={formData.role}+ onChange={e => setFormData(prev => ({+ ...prev,+ role: e.target.value as User['role']+ }))}+ >+ <option value="user">User</option>+ <option value="admin">Admin</option>+ </select>+ </div>++ <button type="submit">Submit</button>+ </form>+ );+};++// Generic list component+const DataList = <T extends { id: string }>({+ items,+ renderItem,+ onItemSelect+}: DataListProps<T>): JSX.Element => {+ return (+ <ul className="data-list">+ {items.map(item => (+ <li+ key={item.id}+ onClick={() => onItemSelect?.(item)}+ role="button"+ tabIndex={0}+ >+ {renderItem(item)}+ </li>+ ))}+ </ul>+ );+};++// Main app component using all features+const App: FC = () => {+ const [users, setUsers] = useState<User[]>([]);+ const [searchTerm, setSearchTerm] = useState('');+ const debouncedSearch = useDebounce(searchTerm, 300);+ const formRef = useRef<HTMLFormElement>(null);++ const handleUserSubmit = useCallback((userData: Partial<User>) => {+ const newUser: User = {+ id: crypto.randomUUID(),+ ...userData as Omit<User, 'id'>+ };+ setUsers(prev => [...prev, newUser]);+ }, []);++ const filteredUsers = users.filter(user =>+ user.name.toLowerCase().includes(debouncedSearch.toLowerCase())+ );++ return (+ <div className="app">+ <header className="app-header">+ <h1>User Management</h1>+ <input+ type="search"+ placeholder="Search users..."+ value={searchTerm}+ onChange={e => setSearchTerm(e.target.value)}+ className="search-input"+ />+ </header>++ <main>+ <section className="user-form-section">+ <h2>Add New User</h2>+ <UserForm onSubmit={handleUserSubmit} />+ </section>++ <section className="user-list-section">+ <h2>Users</h2>+ <DataList+ items={filteredUsers}+ renderItem={user => (+ <div className="user-item">+ <strong>{user.name}</strong>+ <span>{user.email}</span>+ <badge className={`role-badge ${user.role}`}>+ {user.role}+ </badge>+ </div>+ )}+ onItemSelect={user => console.log('Selected user:', user)}+ />+ </section>+ </main>+ </div>+ );+};++export default App;diff --git a/app/server/syntax/map_examples/typescript_example.ts b/app/server/syntax/map_examples/typescript_example.tsnew file mode 100644index 00000000..9e2cfab9--- /dev/null+++ b/app/server/syntax/map_examples/typescript_example.ts@@ -0,0 +1,194 @@+// Type imports+import type { Request, Response, NextFunction } from 'express';++// Interface definitions+interface DataProcessor<T> {+ process(data: T): Promise<T>;+ validate(data: T): boolean;+}++// Type aliases+type Result<T> = {+ data: T;+ error?: string;+ metadata: Record<string, unknown>;+};++// Enum with string values+enum Status {+ PENDING = 'pending',+ ACTIVE = 'active',+ COMPLETED = 'completed',+ FAILED = 'failed'+}++// Union type+type ValidationResult =+ | { valid: true; data: unknown }+ | { valid: false; errors: string[] };++// Intersection type+type AdminUser = User & {+ permissions: string[];+ role: 'admin';+};++// Mapped type+type Readonly<T> = {+ readonly [P in keyof T]: T[P];+};++// Utility type+type Partial<T> = {+ [P in keyof T]?: T[P];+};++// Class with decorators++// Decorator factory+function validate(target: any, propertyKey: string, descriptor: PropertyDescriptor) {+ const originalMethod = descriptor.value;+ descriptor.value = function(...args: any[]) {+ if (this.validate(args[0])) {+ return originalMethod.apply(this, args);+ }+ throw new Error('Validation failed');+ };+ return descriptor;+}++@logger+class User {+ @required+ private name: string;++ private email: string;++ @format('YYYY-MM-DD')+ private createdAt: Date;++ constructor(name: string, email: string) {+ this.name = name;+ this.email = email;+ this.createdAt = new Date();+ }++ // Method decorator+ @validate+ public updateEmail(newEmail: string): void {+ this.email = newEmail;+ }++ // Getter with type guard+ public get isAdmin(): this is AdminUser {+ return 'role' in this && (this as AdminUser).role === 'admin';+ }+}+++// Abstract class+abstract class BaseProcessor<T> implements DataProcessor<T> {+ protected status: Status = Status.PENDING;++ abstract process(data: T): Promise<T>;++ validate(data: T): boolean {+ return data !== null && data !== undefined;+ }+}++// Generic class extending abstract class+class StringProcessor extends BaseProcessor<string> {+ async process(data: string): Promise<string> {+ this.status = Status.ACTIVE;+ const result = await this.transform(data);+ this.status = Status.COMPLETED;+ return result;+ }++ private async transform(data: string): Promise<string> {+ return data.toUpperCase();+ }+}++// Function overloads+function process(data: string): Promise<string>;+function process(data: number): Promise<number>;+function process(data: string | number): Promise<string | number> {+ return Promise.resolve(data);+}++// Generic function with constraints+async function validateData<T extends { id: string }>(+ data: T+): Promise<ValidationResult> {+ if (!data.id) {+ return { valid: false, errors: ['ID is required'] };+ }+ return { valid: true, data };+}++// Higher-order function+function withRetry<T>(+ fn: () => Promise<T>,+ retries: number = 3+): () => Promise<T> {+ return async () => {+ let lastError: Error | undefined;++ for (let i = 0; i < retries; i++) {+ try {+ return await fn();+ } catch (error) {+ lastError = error as Error;+ }+ }++ throw lastError;+ };+}++// Middleware function type+type Middleware = (+ req: Request,+ res: Response,+ next: NextFunction+) => Promise<void>;++// Utility functions with type inference+const createUser = <T extends User>(data: Partial<T>): T => {+ return { ...data } as T;+};++// Async generator function+async function* generateSequence(+ start: number,+ end: number+): AsyncGenerator<number> {+ for (let i = start; i <= end; i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ yield i;+ }+}++// Example usage+async function main() {+ const processor = new StringProcessor();+ const result = await processor.process('hello');++ const user = createUser<AdminUser>({+ name: 'Admin',+ email: '[email protected]',+ permissions: ['read', 'write'],+ role: 'admin'+ });++ const retryableProcess = withRetry(async () => {+ return await processor.process('retry me');+ });++ for await (const num of generateSequence(1, 5)) {+ console.log(num);+ }+}diff --git a/app/server/syntax/map_examples/yaml_example.yaml b/app/server/syntax/map_examples/yaml_example.yamlnew file mode 100644index 00000000..a486d07c--- /dev/null+++ b/app/server/syntax/map_examples/yaml_example.yaml@@ -0,0 +1,129 @@++# Document metadata+# Example YAML file demonstrating various syntax elements+---+name: YAML Example+version: 1.0.0+description: Example YAML file demonstrating various syntax elements+updated_at: 2024-02-20T15:00:00Z++# Scalar types+strings:+ simple: Hello World+ quoted: "Hello \"quoted\" World"+ literal: |+ This is a literal block+ that preserves newlines+ and can contain special chars: *&[]+ folded: >+ This is a folded block+ that will be rendered+ as a single line++numbers:+ integer: 42+ float: 3.14159+ scientific: 1.23e+4+ infinity: .inf+ not_a_number: .nan++dates:+ simple: 2024-02-20+ datetime: 2024-02-20T15:00:00Z+ canonical: 2024-02-20T15:00:00.000Z++booleans:+ true_values: [true, True, TRUE, yes, Yes, YES, on, On, ON]+ false_values: [false, False, FALSE, no, No, NO, off, Off, OFF]++# Complex types+arrays:+ - simple+ - items+ - [nested, array]+ -+ - deeply+ - nested+ - array++# Mapping types+object:+ key1: value1+ key2: value2+ nested:+ key3: value3+ key4: value4++# Anchors and aliases+definitions: &defaults+ timeout: 30+ retries: 3+ enabled: true++production:+ <<: *defaults # Merge defaults+ environment: production+ host: prod.example.com++staging:+ <<: *defaults+ environment: staging+ host: staging.example.com+ timeout: 60 # Override default++# Complex mapping+services:+ - name: web+ image: nginx:latest+ ports:+ - "80:80"+ - "443:443"+ environment:+ - NODE_ENV=production+ - DEBUG=false+ volumes:+ - type: bind+ source: /var/www+ target: /usr/share/nginx/html+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost"]+ interval: 30s+ timeout: 10s+ retries: 3++ - name: database+ image: postgres:13+ environment:+ POSTGRES_USER: admin+ POSTGRES_PASSWORD: !vault |+ $ANSIBLE_VAULT;1.1;AES256+ 31613262363135363132666363366363+ volumes:+ - data:/var/lib/postgresql/data++# Sets+unique_values: !!set+ ? item1+ ? item2+ ? item3++# Binary data+certificate: !!binary |+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOf...++# Custom tags+!!python/object:datetime.datetime+ year: 2024+ month: 2+ day: 20+ hour: 15+ minute: 0+ second: 0++# Explicit typing+explicit_strings: !!str 42+explicit_int: !!int "42"+explicit_float: !!float "3.14159"+explicit_bool: !!bool "yes"++