UNPKG

antlr-ng

Version:

Next generation ANTLR Tool

76 lines (75 loc) 3.13 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { ATNSerializer } from "antlr4ng"; import { SerializedATN } from "./SerializedATN.js"; class SerializedJavaATN extends SerializedATN { static { __name(this, "SerializedJavaATN"); } /** Only valid if there's a single segment. */ serializedAsString; segments; constructor(factory, atn) { super(factory); let data = ATNSerializer.getSerialized(atn); data = this.encodeIntsWith16BitWords(data); const size = data.length; const target = factory.getGenerator().target; const segmentLimit = target.getSerializedATNSegmentLimit(); this.segments = new Array(Math.trunc((size + segmentLimit - 1) / segmentLimit)); let segmentIndex = 0; for (let i = 0; i < size; i += segmentLimit) { const segmentSize = Math.min(i + segmentLimit, size) - i; const segment = new Array(segmentSize); this.segments[segmentIndex++] = segment; for (let j = 0; j < segmentSize; j++) { segment[j] = target.encodeInt16AsCharEscape(data[i + j]); } } this.serializedAsString = this.segments[0]; } getSegments() { return this.segments; } /** * Given a list of integers representing a serialized ATN, encode values too large to fit into 15 bits * as two 16-bit values. We use the high bit (0x8000_0000) to indicate values requiring two 16-bit words. * If the high bit is set, we grab the next value and combine them to get a 31-bit value. The possible * input int values are [-1,0x7FFF_FFFF]. * * | compression/encoding | uint16 count | type | * | -------------------------------------------- | ------------ | --------------- | * | 0xxxxxxx xxxxxxxx | 1 | uint (15 bit) | * | 1xxxxxxx xxxxxxxx yyyyyyyy yyyyyyyy | 2 | uint (16+ bits) | * | 11111111 11111111 11111111 11111111 | 2 | int value -1 | * * This is only used (other than for testing) by {@link org.antlr.v4.codegen.model.SerializedJavaATN} * to encode ints as char values for the java target, but it is convenient to combine it with the * #decodeIntsEncodedAs16BitWords that follows as they are a pair (I did not want to introduce a new class * into the runtime). Used only for Java Target. */ encodeIntsWith16BitWords(data) { const data16 = new Array(Math.ceil(data.length * 1.5)); let index = 0; for (let i = 0; i < data.length; i++) { let v = data[i]; if (v === -1) { data16[index++] = 65535; data16[index++] = 65535; } else if (v <= 32767) { data16[index++] = v; } else { if (v >= 2147483647) { throw new Error(`Serialized ATN data element[${i}] = ${v} doesn't fit in 31 bits`); } v = v & 2147483647; data16[index++] = v >> 16 | 32768; data16[index++] = v & 65535; } } return data16.slice(0, index); } } export { SerializedJavaATN };