Apex language

From forcedotcom/apex-language-support · View interactive version

Apex language is an AI agent skill from the GitHub repository forcedotcom/apex-language-support. Understand Apex language rules, ANTLR grammar structure, and how to implement parser listeners for language server features. Use when working on Apex parser implementation, creating validators, implementing listeners, or referencing parser grammar rules.

How to use this skill

Skill file

Apex Language Support

Hard Rule: Semantic Facts Come Only from Semantic Infrastructure

Never scan raw Apex source text with regular expressions or other text

heuristics to infer or recover semantic facts. This prohibition includes

synthesizing symbols, declarations, types, references, scopes, member

ownership, completion candidates, definition targets, and dependency or

missing-artifact names.

Use grammar-derived parser contexts, tree walkers, symbol tables, resolved

references/xref data, or a prior stable semantic snapshot. Raw document text

may be supplied to the lexer/parser and used for document transport or

position/range mechanics, but it must not be independently interpreted as a

semantic fallback. If semantic state is unavailable, incomplete, or stale,

preserve that uncertainty: wait, retry, or return an incomplete result. Never

invent semantic state from source text.

ANTLR Grammar Reference

The Apex parser uses ANTLR grammar files that are not bundled in the module. Reference them from GitHub:

Grammar Files Location:

Key Grammar Rules:

When implementing listeners or validators, reference the grammar to understand:

Core Apex Language Rules

No Import Statements

Apex has no import statements—never generate or expect them. The compiler resolves types by:

  1. Searching the current namespace
  2. Then the global namespace
  3. Then other installed namespaces

Fully qualified names (<namespace>.<TypeName>) are used only when a name conflict exists; otherwise, use the unqualified name.

Important: A namespace and a type in that namespace can share the same name (e.g., Acme.Acme) and this is valid. Namespace is determined by org/package metadata, not declared in code.

Modifiers and Keywords

Final and Virtual:

Example:

// Correct: Normal class (final by default)
public class MyClass { }

// Incorrect: Cannot use 'final' keyword on classes
public final class MyClass { }  // Syntax error!

// Correct: Virtual class (can be extended)
public virtual class MyClass { }

// Correct: Final variable
public final Integer count = 5;

File Types and Entry Points

Test Artifacts

The Apex language grammar only allows a single top-level type within the same file. When creating test artifacts:

Parser Listener Pattern

BaseApexParserListener

All custom listeners extend BaseApexParserListener<T>:

import { BaseApexParserListener } from './BaseApexParserListener';
import { ClassDeclarationContext } from '@apexdevtools/apex-parser';

export class MyListener extends BaseApexParserListener<MyResultType> {
  enterClassDeclaration(ctx: ClassDeclarationContext): void {
    // Handle class declaration entry
  }

  exitClassDeclaration(ctx: ClassDeclarationContext): void {
    // Handle class declaration exit
  }

  // Override getResult() to return your result
  getResult(): MyResultType {
    return this.result;
  }
}

Listener Methods

Listener methods correspond to parser rules:

Common Context Types:

Using Listeners with CompilerService

import { CompilerService } from '@salesforce/apex-lsp-parser-ast';
import { MyListener } from './MyListener';

const compiler = new CompilerService();
const listener = new MyListener();
const result = compiler.compile(fileContent, fileName, listener);

// Access result
const myResult = result.result;
const errors = result.errors;
const warnings = result.warnings;

Leveraging Parser Rules

Understanding Rule Contexts

Each parser rule generates a context class with:

Example:

enterMethodDeclaration(ctx: MethodDeclarationContext): void {
  // Access method name
  const methodName = ctx.id()?.text;
  
  // Access return type
  const returnType = ctx.typeRef()?.text;
  
  // Access modifiers
  const modifiers = ctx.modifier();
  
  // Access location for errors
  const location = {
    start: ctx.start.line,
    end: ctx.stop?.line,
  };
}

Finding Available Rules

To discover available parser rules:

  1. Check the grammar file: BaseApexParser.g4
  2. Look for rule names (e.g., methodDeclaration, classDeclaration)
  3. Generated context types follow pattern: {RuleName}Context
  4. Import from @apexdevtools/apex-parser

Common Patterns

Scope Tracking:

export class ScopeTrackingListener extends BaseApexParserListener<SymbolTable> {
  private scopeStack: ApexSymbol[] = [];

  enterClassDeclaration(ctx: ClassDeclarationContext): void {
    const classSymbol = this.createClassSymbol(ctx);
    const blockSymbol = this.createBlockSymbol('class', ctx);
    this.scopeStack.push(blockSymbol);
  }

  exitClassDeclaration(): void {
    this.scopeStack.pop();
  }

  getCurrentScope(): ApexSymbol {
    return this.scopeStack[this.scopeStack.length - 1];
  }
}

Error Reporting:

enterMethodDeclaration(ctx: MethodDeclarationContext): void {
  if (this.errorListener) {
    this.errorListener.addError({
      message: 'Custom error message',
      line: ctx.start.line,
      column: ctx.start.charPositionInLine,
    });
  }
}

Validation Patterns

TIER 1 (Immediate) Validators

Fast, same-file validations that run on every keystroke (<500ms):

TIER 2 (Thorough) Validators

Comprehensive validations that may require cross-file analysis:

Error Codes and Messages

When working with semantics and validation, error codes and messages must be aligned with the Salesforce org compiler.

Error Messages Reference:

Workflow for Adding New Error Codes:

  1. Check for existing error code: First, search messages_en_US.properties to see if an appropriate error code already exists
  1. If a new error code is needed: Ask the user for permission before proceeding
  1. Choose the source catalog: After receiving permission, add compiler-aligned

messages to the legacy Java compiler source first and refresh at the next major release. Add

Apex-LS-specific diagnostics to messages_apex_ls.properties.

```properties

my.new.error.code=Error message text with {0} placeholder

```

  1. Regenerate TypeScript files: Run npm run precompile in packages/apex-parser-ast
  1. Use in validators: Import and use the generated constants

```typescript

import { ErrorCodes } from '../generated/ErrorCodes';

// Use ErrorCodes.MY_NEW_ERROR_CODE in your validator

```

Critical: When implementing validators that require error reporting, if you determine that a new error code needs to be created, you must ask the user for permission before proceeding. Do not create new error codes without explicit user approval.

Major-release diagnostic refresh

  1. Checkout the target legacy Java compiler release.
  2. Copy its messages_en_US.properties unchanged into the baseline path.
  3. Curate relevant Java FullCompileTester snippets into

test/fixtures/validation/**/*.cls; retain their expected diagnostic contract.

  1. Keep Apex-LS-specific diagnostics in messages_apex_ls.properties.
  2. Run npm run precompile, formatter/parity fixtures, and npm run check:error-codes.

Fixtures are curated legacy Java cases, not ad hoc replacements. Convert supported

parser-owned cases to .cls fixtures and assert code, message, severity, and

parser-owned range through the Apex-LS harness. Mark unsupported compiler-only

cases deferred; never emulate them with raw-source semantic inference.

Generated TypeScript preserves Java MessageFormat: {n} selects argument n,

repeated placeholders repeat that argument, and '' is one literal apostrophe.

Pass logical arguments in catalog order; never duplicate or reorder values for

printf-style formatting.

When to Consult This File:

Example Error Codes:

Important: Always consult messages_en_US.properties when:

  1. Adding new validation logic that needs error reporting
  2. Choosing which error code to use for a validation failure
  3. Ensuring consistency with Salesforce compiler error messages
  4. Adding a new error code: Update .properties file, then run npm run precompile to regenerate TS files

Validator Implementation

Validators can use listeners to traverse parse trees:

import { BaseApexParserListener } from '../../../parser/listeners/BaseApexParserListener';

class MyValidatorListener extends BaseApexParserListener<void> {
  enterMethodDeclaration(ctx: MethodDeclarationContext): void {
    // Validate method
    if (ctx.parameterList()?.parameter().length > 32) {
      this.addError('Too many parameters');
    }
  }
}

Additional Resources

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.