Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation available on the TS target for ANTLR...). The errors cannot find module antlr4ts and

Property 'exitRule' does not exist on type...
continue to plague me. Any guidance or support in resolving this predicament would be immensely appreciated.

I have diligently followed the steps outlined on the GitHub page, adhering closely to their instructions, only to encounter issues at a critical juncture.

The grammar is relatively simple, starting with the parser rule r(). The lexer/parser files are located in the primary directory (following antlr4ts execution). Despite generating some js files within an /output/ directory, I have attempted to streamline the project to its core components (even excluding an index.html; relying solely on tsconfig.json, package.json,, the grammar, and the generated grammar files).

One of the encountered errors:

Cannot find module 'antlr4ts'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "output",
    "target": "es6",
    "lib": ["es6", "dom"]
  },
  "include": ["./*"],
  "exclude": ["node_modules"]
}

package.json:

{
  "name": "naturaldeductionthesistypescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "antlr4ts": "antlr4ts -listener MyGrammar.g4",
    "compile-typescript": "tsc"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "antlr4ts": "^0.5.0-alpha.4"
  },
  "devDependencies": {
    "antlr4ts-cli": "^0.5.0-alpha.4",
    "typescript": "^3.5.3"
  }
}

main.ts

import { ANTLRInputStream, CommonTokenStream } from 'antlr4ts';
import { MyGrammarLexer } from 'MyGrammarLexer';
import { MyGrammarParser } from 'MyGrammarParser';

// Create the lexer and parser
let inputStream = new ANTLRInputStream("text");
let lexer = new MyGrammarLexer(inputStream);
let tokenStream = new CommonTokenStream(lexer);
let parser = new MyGrammarParser(tokenStream);

// Parse the input, where `compilationUnit` is whatever entry point you defined
let tree = parser.r();

Grammar

grammar MyGrammar;
r   : 'hello' ID;
ID  : [a-z]+ ;
WS  : [ \t\r\n]+ -> skip ;

Answer №1

It's interesting that you're encountering so many issues with that. Personally, I've incorporated the TS runtime into numerous projects without facing similar challenges. For a detailed example, take a look at this repository: antlr4-c3.

You can view the configuration files there and observe how I integrate the runtime. Below are the config files:

tsconfig.json:

{
    "compilerOptions": {
        "declaration": true,
        "module": "commonjs",
        "target": "es6",
        "outDir": "out",
        "removeComments": true,
        "noImplicitAny": true,
        "sourceMap": true,
        "inlineSources": true,
        "isolatedModules": false,
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true,
        "strictNullChecks": true
    },
    "compileOnSave": true,
    "include": [
        "src/**/*.ts", "test/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        ".vscode-test"
    ]
}

A snippet of code from my unit tests is as follows:

...

    import {
        ANTLRErrorListener, CharStreams, CommonToken, CommonTokenStream, RecognitionException, Recognizer, Token,
    } from "antlr4ts";
    import { Override } from "antlr4ts/Decorators";
    import { TerminalNode } from "antlr4ts/tree/TerminalNode";

...

            const inputStream = CharStreams.fromString("var c = a + b");
            const lexer = new ExprLexer(inputStream);
            const tokenStream = new CommonTokenStream(lexer);

            const parser = new ExprParser(tokenStream);
            const errorListener = new ErrorListener();
            parser.addErrorListener(errorListener);
            parser.expression();
            expect(errorListener.errorCount, "Test 1").equals(0);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming a React component into a TypeScript Element results in an automatic 'any' type assignment due to the inability to index an expression of type 'string | number'

I am currently in the process of migrating a React component to TypeScript, but I have encountered an issue that I am struggling to resolve. I am consistently receiving an error related to accessing variantStyles[variant][color], and I cannot pinpoint the ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

Unable to connect information to list item

I'm struggling to figure out why I am unable to bind this data into the li element. When I check the console, I can see the data under calendar.Days and within that are the individual day values. Any assistance would be highly appreciated. Code @Comp ...

Explicit declaration of default parameters

Check out the helpful solution In regard to the following code snippet, type C = { a: string, b: number } function f({ a, b } = {a:"", b:0}): void { // ... } Can you explain the syntax for explicitly typing the default parameter? ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Transforming Bootstrap using Typescript styled components

I have been working on customizing the Navbar in my React app using Typescript's styled components. However, I am facing difficulties in restyling the default styles from Bootstrap that I have copied. Here is an example of the React Bootstrap Navbar c ...

Options for importing TypeScript in WebStorm

Using WebStorm for auto-importing TypeScript classes has been a great help to tidy up my code and make it more organized. However, I have noticed that the imports are always formatted in a single line like this: import { Component, EventEmitter, Input, O ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

"Disabling a FormControl within a FormArray in Angular 4: A Step-by-

I've come up with a code snippet below that I thought would disable the FormControl in a FormArray. some.component.html <form [formGroup]="testForm"> <div *ngFor="let num of countArr"> <input type="text" formNameArray="arr ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Is it possible to modify the number format of an input field while in Antd's table-row-edit mode?

I am currently utilizing the Table Component of Ant Design v2.x and unfortunately, I cannot conduct an upgrade. My concern lies with the inconsistent formatting of numbers in row-edit mode. In Display mode, I have German formatting (which is desired), but ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

ngIf failing to pick up on variable updates

Utilizing the greensock animation library to animate various components has presented a problem during the variable update within the onComplete function linked to a *ngIf. Strangely, Angular fails to recognize the variable update within the callback. Des ...