Stop getting generic AI suggestions. This comprehensive guide provides copy-paste ready .antigravity rules files optimized for every major programming language, ensuring Gemini 3 generates code that matches your language's best practices.
Generic AI prompts produce generic code. Language-specific rules ensure:
# TypeScript Full-Stack Project
## Language Configuration
- TypeScript 5.3+ with strict mode
- ESNext target with ES modules
- Node.js 20+ runtime
## Type System Rules
- Always use explicit return types for functions
- Prefer `interface` for object shapes, `type` for unions/primitives
- Use branded types for IDs: `type UserId = string & { __brand: 'UserId' }`
- Never use `any` - use `unknown` with type guards
- Use `satisfies` for type validation without widening
- Prefer `const` assertions for literal types
## Code Style
- Use `const` by default, `let` only when reassignment needed
- Destructure in function parameters when >2 properties
- Use optional chaining: `obj?.prop?.nested`
- Use nullish coalescing: `value ?? defaultValue`
- Prefer `Array.prototype` methods over loops
## Error Handling
- Use discriminated unions for expected errors:
```typescript
type Result<T, E> = { success: true; data: T } | { success: false; error: E }
describe/it pattern*.test.ts or *.spec.ts
### React / Next.js Specific
```markdown
# React / Next.js Project
## Framework Version
- Next.js 14+ with App Router (NO Pages Router)
- React 18 with Server Components
## Component Rules
- Functional components only (no class components)
- Named exports: `export function ComponentName()`
- Props interface: `interface ComponentNameProps {}`
- Use Server Components by default
- Add 'use client' only when needed:
- useState, useEffect, event handlers
- Browser-only APIs
- Third-party client libraries
## Hooks
- Custom hooks start with `use`
- Extract logic when component > 50 lines
- useCallback for functions passed as props
- useMemo only when profiler shows need
## State Management
- Server state: TanStack Query
- Client state: Zustand (no Redux)
- Form state: React Hook Form + Zod
- URL state: nuqs or searchParams
## Data Fetching
- Fetch in Server Components (preferred)
- Server Actions for mutations
- TanStack Query for client-side caching
## File Naming
- Components: PascalCase.tsx
- Hooks: use-hook-name.ts (kebab-case with use- prefix)
- Utilities: kebab-case.ts
- Types: types.ts or component.types.ts
# Python Project
## Version & Environment
- Python 3.11+ required
- Use virtual environments (venv or poetry)
- Type hints on all functions
## Code Style
- Follow PEP 8 strictly
- Max line length: 88 (Black formatter)
- Use pathlib over os.path
- f-strings for string formatting
- Use walrus operator where it improves readability
## Type Hints
```python
# Function signatures always typed
def process_data(items: list[dict[str, Any]]) -> DataFrame:
...
# Use generics for containers
from typing import TypeVar, Generic
T = TypeVar('T')
# Use Protocol for structural typing
from typing import Protocol
class Serializable(Protocol):
def to_dict(self) -> dict: ...
Use absolute imports, not relative.
### FastAPI Backend
```markdown
# FastAPI Backend
## Framework Configuration
- FastAPI 0.100+
- Pydantic v2 for validation
- SQLAlchemy 2.0 async
- Alembic for migrations
## API Design
- RESTful conventions
- Versioned routes: `/api/v1/`
- snake_case for JSON fields
- ISO 8601 for datetime
## Endpoint Pattern
```python
@router.get("/users/{user_id}", response_model=UserResponse)
async def get_user(
user_id: UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> UserResponse:
"""Get user by ID."""
user = await user_service.get_by_id(db, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
## Go (Golang) Rules
```markdown
# Go Project
## Version
- Go 1.21+
- Use Go modules
## Code Style
- Follow Effective Go guidelines
- gofmt/goimports for formatting
- golangci-lint for linting
## Naming Conventions
- Exported: PascalCase
- Unexported: camelCase
- Interfaces: -er suffix (Reader, Writer)
- Acronyms: consistent case (HTTP not Http)
## Package Design
- Small, focused packages
- No circular dependencies
- Package name = directory name (singular)
## Error Handling
```go
// Return errors, don't panic
func ProcessData(data []byte) (Result, error) {
if len(data) == 0 {
return Result{}, fmt.Errorf("empty data: %w", ErrInvalidInput)
}
// ...
}
// Check errors immediately
result, err := ProcessData(data)
if err != nil {
return fmt.Errorf("processing failed: %w", err)
}
/cmd # Main applications
/internal # Private packages
/pkg # Public packages
/api # API definitions
/configs # Configuration files
*_test.go
## Rust Rules
```markdown
# Rust Project
## Edition & Toolchain
- Rust 2021 edition
- Stable toolchain
- cargo fmt and clippy
## Code Style
- Follow Rust API Guidelines
- Max line length: 100
- Use rustfmt defaults
## Type System
- Prefer strong typing over stringly-typed code
- Use newtypes for domain concepts
- Implement From/Into for conversions
- Use Result<T, E> for fallible operations
## Error Handling
```rust
// Define custom error types
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
#[error("Validation error: {0}")]
Validation(String),
}
// Use ? operator for propagation
fn process() -> Result<Output, AppError> {
let data = fetch_data()?;
validate(&data)?;
Ok(transform(data))
}
src/
āāā lib.rs # Library root
āāā main.rs # Binary entry
āāā config.rs # Configuration
āāā error.rs # Error types
āāā domain/ # Business logic
āāā infra/ # Infrastructure
āāā api/ # HTTP/API layer
## Java Rules
```markdown
# Java Project
## Version & Build
- Java 21+ (LTS)
- Maven or Gradle
- Spring Boot 3.2+ for web apps
## Code Style
- Google Java Style Guide
- Max line length: 100
- Checkstyle for enforcement
## Naming Conventions
- Classes: PascalCase
- Methods/Variables: camelCase
- Constants: SCREAMING_SNAKE_CASE
- Packages: lowercase.with.dots
## Modern Java Features
- Use records for DTOs
- Use sealed interfaces for ADTs
- Pattern matching in switch
- var for local variables with obvious types
- Stream API over loops
## Patterns
```java
// Records for immutable data
public record UserDto(
UUID id,
String email,
LocalDateTime createdAt
) {}
// Sealed interfaces for variants
public sealed interface PaymentResult
permits PaymentSuccess, PaymentFailure {
}
// Pattern matching
return switch (result) {
case PaymentSuccess s -> handleSuccess(s);
case PaymentFailure f -> handleFailure(f);
};
## C# / .NET Rules
```markdown
# C# / .NET Project
## Version
- .NET 8+
- C# 12
- Nullable reference types enabled
## Code Style
- Microsoft C# Coding Conventions
- editorconfig for settings
- dotnet format for enforcement
## Naming
- Public members: PascalCase
- Private fields: _camelCase
- Local variables: camelCase
- Interfaces: IInterface
## Modern C# Features
- Primary constructors
- Collection expressions
- Pattern matching
- Records for DTOs
- Required properties
## Patterns
```csharp
// Primary constructor
public class UserService(IUserRepository repository, ILogger<UserService> logger)
{
public async Task<User?> GetByIdAsync(Guid id)
{
logger.LogInformation("Fetching user {UserId}", id);
return await repository.FindByIdAsync(id);
}
}
// Record types
public record UserDto(Guid Id, string Email, DateTime CreatedAt);
// Pattern matching
return user switch
{
{ IsAdmin: true } => HandleAdmin(user),
{ IsVerified: false } => HandleUnverified(user),
_ => HandleRegular(user)
};
## Kotlin Rules
```markdown
# Kotlin Project
## Version & Platform
- Kotlin 1.9+
- JVM 21 target
- Kotlin Coroutines for async
## Code Style
- Kotlin Coding Conventions
- ktlint for formatting
- detekt for static analysis
## Kotlin Idioms
- Data classes for DTOs
- Sealed classes for variants
- Extension functions for utilities
- Scope functions (let, run, with, apply, also)
- Null safety: no !!
## Patterns
```kotlin
// Data class
data class User(
val id: UUID,
val email: String,
val createdAt: Instant
)
// Sealed class hierarchy
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val message: String) : Result<Nothing>()
}
// Extension function
fun String.toSlug(): String =
lowercase().replace(" ", "-").replace(Regex("[^a-z0-9-]"), "")
// Coroutines
suspend fun fetchUser(id: UUID): User = withContext(Dispatchers.IO) {
repository.findById(id) ?: throw UserNotFoundException(id)
}
## Swift Rules
```markdown
# Swift Project
## Version
- Swift 5.9+
- iOS 17+ / macOS 14+
- Swift Concurrency (async/await)
## Code Style
- Swift API Design Guidelines
- SwiftLint for enforcement
- SwiftFormat for formatting
## Naming
- Types: PascalCase
- Everything else: camelCase
- Protocols: -able, -ible, or noun
- Boolean: is/has/should prefix
## Modern Swift
- Structured concurrency
- Actors for shared mutable state
- Result type for errors
- Property wrappers
- Macros where appropriate
## Patterns
```swift
// Actor for thread-safe state
actor UserCache {
private var cache: [UUID: User] = [:]
func get(_ id: UUID) -> User? { cache[id] }
func set(_ user: User) { cache[user.id] = user }
}
// Structured concurrency
func fetchAllUsers() async throws -> [User] {
try await withThrowingTaskGroup(of: User.self) { group in
for id in userIds {
group.addTask { try await fetchUser(id) }
}
return try await group.reduce(into: []) { $0.append($1) }
}
}
// Result builder
@ViewBuilder
func content(for state: ViewState) -> some View {
switch state {
case .loading: ProgressView()
case .loaded(let data): DataView(data: data)
case .error(let error): ErrorView(error: error)
}
}
## Using Multiple Languages
For polyglot projects, combine rules:
```markdown
# Full-Stack Project Rules
## Frontend (TypeScript/React)
[Include TypeScript rules above]
## Backend (Python/FastAPI)
[Include Python rules above]
## Shared Conventions
- JSON field naming: snake_case (Python convention)
- Date format: ISO 8601
- ID format: UUID v4
- Error format: { "error": string, "code": string }
## When Writing Frontend Code
- Follow TypeScript rules section
- Import types from @/types/api.ts
## When Writing Backend Code
- Follow Python rules section
- Generate OpenAPI schema for frontend types
| Language | Key Rules |
|---|---|
| TypeScript | Strict mode, explicit returns, no any |
| Python | Type hints, PEP 8, Google docstrings |
| Go | Effective Go, error wrapping, small packages |
| Rust | Result<T,E>, ownership, clippy clean |
| Java | Records, sealed interfaces, Spring conventions |
| C# | Nullable enabled, primary constructors, records |
| Kotlin | Data classes, sealed classes, coroutines |
| Swift | Actors, structured concurrency, SwiftUI |
Language-specific .antigravity rules transform Gemini 3 from a generic code generator into an expert in your language of choice. Copy the rules for your stack, customize as needed, and enjoy idiomatic, production-ready AI-generated code.
Browse our complete prompt library for more language-specific templates, or explore MCP servers to connect your language's tooling directly to Antigravity.
Last updated: December 2024 Missing your language? Request it in the comments!