import * as nodes from "./nodes.js"; import { getDecoder } from "./decoding.js"; import { Location } from "./location.js"; import { Source } from "./source.js"; const MAJOR_VERSION = 2; const MINOR_VERSION = 1; const PATCH_VERSION = 0; /* The DataView getFloat64 function takes an optional second argument that * specifies whether the number is little-endian or big-endian. It does not * appear to have a native endian mode, so we need to determine the endianness * of the system at runtime. */ const LITTLE_ENDIAN = (() => { let uint32 = new Uint32Array([0x11223344]); let uint8 = new Uint8Array(uint32.buffer); if (uint8[0] === 0x44) { return true; } else if (uint8[0] === 0x11) { return false; } else { throw new Error("Mixed endianness"); } })(); class SerializationBuffer { constructor(array) { this.array = array; this.index = 0; this.encoding = "utf-8"; this.source = null; } readByte() { const result = this.array[this.index]; this.index += 1; return result; } readBytes(length) { const result = this.array.slice(this.index, this.index + length); this.index += length; return result; } readString(length, flags) { return this.decodeString(this.readBytes(length), flags).value; } /* Read a 32-bit unsigned integer in little-endian format. */ readUint32() { const result = this.scanUint32(this.index); this.index += 4; return result; } scanUint32(offset) { const bytes = this.array.slice(offset, offset + 4); return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); } /** * Read a signed integer that was written in zigzag encoding, where the low * bit carries the sign. Both operators here are 32-bit, which is what makes * this correct for zigzag values above 2^31, where readVarInt overflows and * returns the bit pattern as a negative number. */ readVarSInt() { const value = this.readVarInt(); return (value >>> 1) ^ -(value & 1); } readVarInt() { let result = 0; let shift = 0; while (true) { const byte = this.readByte(); result |= (byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) === 0) { break; } } return result >>> 0; } readLocation() { const startOffset = this.readVarInt(); const length = this.readVarInt(); return new Location(this.source, startOffset, length); } readOptionalLocation() { if (this.readByte() != 0) { return this.readLocation(); } else { return null; } } readStringField(flags) { if (flags === undefined) flags = 0; return this.decodeString(this.readBytes(this.readVarInt()), flags); } scanConstant(constantPoolOffset, constantIndex) { const offset = constantPoolOffset + constantIndex * 8; const startOffset = this.scanUint32(offset); const length = this.scanUint32(offset + 4); return getDecoder(this.encoding, { fatal: true }).decode(this.array.slice(startOffset, startOffset + length)); } readDouble() { const view = new DataView(new ArrayBuffer(8)); for (let index = 0; index < 8; index++) { view.setUint8(index, this.readByte()); } return view.getFloat64(0, LITTLE_ENDIAN); } decodeString(bytes, flags) { let value, encoding, validEncoding; if ((flags & nodes.StringFlags.FORCED_BINARY_ENCODING) !== 0) { encoding = "ascii-8bit"; } else if ((flags & nodes.StringFlags.FORCED_UTF8_ENCODING) !== 0) { encoding = "utf-8"; } else { encoding = this.encoding.toLowerCase(); } const decoder = getDecoder(encoding, { fatal: true }); try { value = decoder.decode(bytes); validEncoding = true; } catch (error) { /* A fatal decoder reports bytes that are not valid in its encoding by * throwing a TypeError, and that is the whole of what it throws, so the * string is read back as binary and flagged. */ if (error instanceof TypeError) { value = getDecoder("ascii-8bit").decode(bytes); validEncoding = false; } else { throw error; } } return { value, encoding, validEncoding }; } } /** * A comment in the source code. * * @typedef {{ type: number, location: Location }} Comment */ /** * A magic comment in the source code. * * @typedef {{ startLocation: Location, endLocation: Location }} MagicComment */ /** * An error in the source code. * * @typedef {{ type: string, message: string, location: Location, level: string }} ParseError */ /** * A warning in the source code. * * @typedef {{ type: string, message: string, location: Location, level: string }} ParseWarning */ /** * The result of parsing the source code. * * @typedef {{ value: ProgramNode, comments: Comment[], magicComments: MagicComment[], errors: ParseError[], warnings: ParseWarning[] }} ParseResult */ /** * The result of calling parse. */ export class ParseResult { /** * @type {nodes.ProgramNode} */ value; /** * @type {Comment[]} */ comments; /** * @type {MagicComment[]} */ magicComments; /** * @type {Location | null} */ dataLoc; /** * @type {ParseError[]} */ errors; /** * @type {ParseWarning[]} */ warnings; /** * @type {boolean} */ continuable; /** * @param {nodes.ProgramNode} value * @param {Comment[]} comments * @param {MagicComment[]} magicComments * @param {Location | null} dataLoc * @param {ParseError[]} errors * @param {ParseWarning[]} warnings * @param {boolean} continuable */ constructor(value, comments, magicComments, dataLoc, errors, warnings, continuable) { this.value = value; this.comments = comments; this.magicComments = magicComments; this.dataLoc = dataLoc; this.errors = errors; this.warnings = warnings; this.continuable = continuable; } } const errorLevels = ["syntax", "argument", "load", "stack", "encoding_compatibility"]; const errorTypes = [ <%- errors.each do |error| -%> "<%= error.name.downcase %>", <%- end -%> ]; const warningLevels = ["default", "verbose"]; const warningTypes = [ <%- warnings.each do |warning| -%> "<%= warning.name.downcase %>", <%- end -%> ]; /** * Accept two Uint8Arrays, one for the source and one for the serialized format. * Return the AST corresponding to the serialized form. * * @param {Uint8Array} source * @param {Uint8Array} array * @returns {ParseResult} * @throws {Error} */ export function deserialize(source, array) { const buffer = new SerializationBuffer(array); if (buffer.readString(5) !== "PRISM") { throw new Error("Invalid serialization"); } if ((buffer.readByte() != MAJOR_VERSION) || (buffer.readByte() != MINOR_VERSION) || (buffer.readByte() != PATCH_VERSION)) { throw new Error("Invalid serialization"); } if (buffer.readByte() != 0) { throw new Error("Invalid serialization (location fields must be included but are not)"); } // Read the file's encoding. buffer.encoding = buffer.readString(buffer.readVarInt()); // Read the line that the source starts on along with the byte offset of the // start of each line, which together let locations resolve lines and columns. const startLine = buffer.readVarSInt(); // Skip the 8-byte hash of the source, which this library does not expose. buffer.readBytes(8); const lineOffsets = Array.from({ length: buffer.readVarInt() }, () => buffer.readVarInt()); buffer.source = new Source(source, buffer.encoding, startLine, lineOffsets); const comments = Array.from({ length: buffer.readVarInt() }, () => ({ type: buffer.readVarInt(), location: buffer.readLocation() })); // Skip the comments attached to each node, which this library does not // expose. Each entry is a node id followed by the indices of its comments. for (let count = buffer.readVarInt(); count > 0; count--) { buffer.readVarInt(); for (let length = buffer.readVarInt(); length > 0; length--) { buffer.readVarInt(); } } const magicComments = Array.from({ length: buffer.readVarInt() }, () => ({ startLocation: buffer.readLocation(), endLocation: buffer.readLocation() })); const dataLoc = buffer.readOptionalLocation(); const errors = Array.from({ length: buffer.readVarInt() }, () => ({ type: errorTypes[buffer.readVarInt()], message: buffer.readString(buffer.readVarInt()), location: buffer.readLocation(), level: errorLevels[buffer.readByte()] })); const warnings = Array.from({ length: buffer.readVarInt() }, () => ({ type: warningTypes[buffer.readVarInt()], message: buffer.readString(buffer.readVarInt()), location: buffer.readLocation(), level: warningLevels[buffer.readByte()] })); const continuable = buffer.readByte() !== 0; const constantPoolOffset = buffer.readUint32(); const constants = Array.from({ length: buffer.readVarInt() }, () => null); return new ParseResult(readNodes(constantPoolOffset), comments, magicComments, dataLoc, errors, warnings, continuable); /* Read the nodes that are serialized before the given offset and return the * root. Nodes are serialized in post-order, so the children of each node are * the topmost values on the stack, in field order, by the time its record is * read. */ function readNodes(finish) { const stack = []; while (buffer.index < finish) { const type = buffer.readByte(); switch (type) { case 0: stack.push(null); break; case <%= Prism::Template::LAZY_MARKER %>: buffer.readUint32(); buffer.readUint32(); break; <%- local = ->(field) { field.name == "arguments" ? "arguments_" : field.name.gsub(/_([a-z])/) { $1.upcase } } -%> <%- nodes.each.with_index(1) do |node, index| -%> case <%= index %>: { const nodeID = buffer.readVarInt(); const location = buffer.readLocation(); const flags = buffer.readVarInt(); <%- node.fields.each do |field| -%> <%- case field -%> <%- when Prism::Template::NodeField, Prism::Template::OptionalNodeField -%> <%- when Prism::Template::NodeListField -%> const <%= local[field] %>Size = buffer.readVarInt(); <%- else -%> const <%= local[field] %> = <%= case field when Prism::Template::StringField then "buffer.readStringField(flags)" when Prism::Template::ConstantField then "readRequiredConstant()" when Prism::Template::OptionalConstantField then "readOptionalConstant()" when Prism::Template::ConstantListField then "Array.from({ length: buffer.readVarInt() }, readRequiredConstant)" when Prism::Template::LocationField then "buffer.readLocation()" when Prism::Template::OptionalLocationField then "buffer.readOptionalLocation()" when Prism::Template::UInt8Field then "buffer.readByte()" when Prism::Template::UInt32Field then "buffer.readVarInt()" when Prism::Template::IntegerField then "readInteger()" when Prism::Template::DoubleField then "buffer.readDouble()" else raise end %>; <%- end -%> <%- end -%> <%- node.child_fields.reverse_each do |field| -%> <%- if field.is_a?(Prism::Template::NodeListField) -%> const <%= local[field] %> = stack.splice(stack.length - <%= local[field] %>Size, <%= local[field] %>Size); <%- else -%> const <%= local[field] %> = stack.pop(); <%- end -%> <%- end -%> stack.push(new nodes.<%= node.name %>(<%= ["nodeID", "location", "flags", *node.fields.map { |field| local[field] }].join(", ") %>)); break; } <%- end -%> default: throw new Error(`Unknown node type: ${type}`); } } if (buffer.index !== finish || stack.length !== 1) { throw new Error("Expected the serialized nodes to end at the constant pool with exactly one root"); } return stack[0]; } function scanConstant(constantIndex) { if (constants[constantIndex] === null) { constants[constantIndex] = buffer.scanConstant(constantPoolOffset, constantIndex); } return constants[constantIndex]; } function readRequiredConstant() { return scanConstant(buffer.readVarInt() - 1); } function readOptionalConstant() { const index = buffer.readVarInt(); if (index === 0) { return null; } else { return scanConstant(index - 1); } } function readInteger() { const negative = buffer.readByte() != 0; const length = buffer.readVarInt(); if (length == 0) return 0; const firstWord = buffer.readVarInt(); if (length == 1) { if (negative && firstWord >= 0x80000000) { return -BigInt(firstWord); } else if (negative) { return -firstWord; } else { return firstWord; } } let result = BigInt(firstWord); for (let index = 1; index < length; index++) { result |= (BigInt(buffer.readVarInt()) << BigInt(index * 32)); } return negative ? -result : result; } }