@vlocode/apex
Version:
Salesforce APEX Parser and Grammar
77 lines • 3.05 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parser = void 0;
const antlr4ng_1 = require("antlr4ng");
const typeRefCollector_1 = require("./visitors/typeRefCollector");
const compilationUnitVisitor_1 = require("./visitors/compilationUnitVisitor");
const streams_1 = require("./streams");
const grammar_1 = require("./grammar");
/**
* APEX Source code parser and lexer. Provides methods to parse APEX source
* code into an abstract syntax tree (AST) and to get all referenced types in the source code.
*
* @example
* ```typescript
* // cu will hold an abstract representation of the code structure of the source files
* // multiple source files can be parsed at once by concatenating them
* const cu = new Parser('public class MyClass { } public class OtherClass { }').getCodeStructure();
* // refs will hold an array of ll external references: [ 'MyClass', 'BaseClass' ];
* const refs = new Parser('public class MyClass extends BaseClass { private MyOtherClass other; }').getReferencedTypes();
* ```
*/
class Parser {
input;
lexer;
parser;
cu;
constructor(input) {
this.input = input;
}
/**
* Parse a piece of Apex code into an abstract representation of the code structure of an APEX source files.
* Returns a {@link ApexCompilationUnit} object that contains all classes and interfaces defined in the source text. The
* source text can be a single file or multiple files concatenated or an array of source texts.
* @param code Apex code to parse as a string or buffer (or an array of strings or buffers)
* @returns An {@link ApexCompilationUnit} describing the code structure
*/
getCodeStructure() {
return this.parseAsCompilationUnit().accept(new compilationUnitVisitor_1.CompilationUnitVisitor());
}
/**
* Get all referenced types in the specified code
* @param code Apex code to parse
* @param options Options to control which types are returned
* @returns An array of unique `ApexTypeRef` objects
*/
getReferencedTypes(options) {
return this.parseAsCompilationUnit().accept(new typeRefCollector_1.TypeRefCollector(options));
}
parseAsCompilationUnit() {
if (!this.cu) {
this.cu = this.getParser().compilationUnit();
}
return this.cu;
}
getParser() {
if (!this.parser) {
const tokens = new antlr4ng_1.CommonTokenStream(this.getLexer());
this.parser = new grammar_1.ApexParser(tokens);
}
this.parser.reset();
return this.parser;
}
getLexer() {
if (!this.lexer) {
this.lexer = new grammar_1.ApexLexer(this.createInputStream());
}
return this.lexer;
}
createInputStream() {
if (typeof this.input === 'string') {
return antlr4ng_1.CharStream.fromString(this.input);
}
return new streams_1.BufferStream(this.input);
}
}
exports.Parser = Parser;
//# sourceMappingURL=parser.js.map