import { BaseRegExpVisitor as e } from "../../../../@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js";
import "../../../../@chevrotain/regexp-to-ast/lib/src/api.js";
import { PRINT_ERROR as t } from "../../../../@chevrotain/utils/lib/src/print.js";
import { getRegExpAst as n } from "./reg_exp_parser.js";
import { canMatchCharCode as r, failedOptimizationPrefixMsg as i, getOptimizedStartCodesIndices as a } from "./reg_exp.js";
import { Lexer as o, LexerDefinitionErrorType as s } from "./lexer_public.js";
//#region ../../node_modules/chevrotain/lib/src/scan/lexer.js
var c = "PATTERN", l = "defaultMode", u = "modes";
function d(e, n) {
	n = Object.assign({
		safeMode: !1,
		positionTracking: "full",
		lineTerminatorCharacters: ["\r", "\n"],
		tracer: (e, t) => t()
	}, n);
	let s = n.tracer;
	s("initCharCodeToOptimizedIndexMap", () => {
		H();
	});
	let l;
	s("Reject Lexer.NA", () => {
		l = e.filter((e) => e[c] !== o.NA);
	});
	let u = !1, d;
	s("Transform Patterns", () => {
		u = !1, d = l.map((e) => {
			let t = e[c];
			/* istanbul ignore else */
			if (t instanceof RegExp) {
				let e = t.source;
				return e.length === 1 && e !== "^" && e !== "$" && e !== "." && !t.ignoreCase ? e : e.length === 2 && e[0] === "\\" && ![
					"d",
					"D",
					"s",
					"S",
					"t",
					"r",
					"n",
					"t",
					"0",
					"c",
					"b",
					"B",
					"f",
					"v",
					"w",
					"W"
				].includes(e[1]) ? e[1] : k(t);
			} else if (typeof t == "function") return u = !0, { exec: t };
			else if (typeof t == "object") return u = !0, t;
			else if (typeof t == "string") {
				if (t.length === 1) return t;
				{
					let e = t.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
					return k(new RegExp(e));
				}
			} else throw Error("non exhaustive match");
		});
	});
	let f, p, m, h, g;
	s("misc mapping", () => {
		f = l.map((e) => e.tokenTypeIdx), p = l.map((e) => {
			let t = e.GROUP;
			if (t !== o.SKIPPED) {
				if (typeof t == "string") return t;
				if (t === void 0) return !1;
				throw Error("non exhaustive match");
			}
		}), m = l.map((e) => {
			let t = e.LONGER_ALT;
			if (t) return Array.isArray(t) ? t.map((e) => l.indexOf(e)) : [l.indexOf(t)];
		}), h = l.map((e) => e.PUSH_MODE), g = l.map((e) => Object.hasOwn(e, "POP_MODE"));
	});
	let _;
	s("Line Terminator Handling", () => {
		let e = R(n.lineTerminatorCharacters);
		_ = l.map((e) => !1), n.positionTracking !== "onlyOffset" && (_ = l.map((t) => Object.hasOwn(t, "LINE_BREAKS") ? !!t.LINE_BREAKS : I(t, e) === !1 && r(e, t.PATTERN)));
	});
	let v, y, b, x;
	s("Misc Mapping #2", () => {
		v = l.map(N), y = d.map(P), b = l.reduce((e, t) => {
			let n = t.GROUP;
			return typeof n == "string" && n !== o.SKIPPED && (e[n] = []), e;
		}, {}), x = d.map((e, t) => ({
			pattern: d[t],
			longerAlt: m[t],
			canLineTerminator: _[t],
			isCustom: v[t],
			short: y[t],
			group: p[t],
			push: h[t],
			pop: g[t],
			tokenTypeIdx: f[t],
			tokenType: l[t]
		}));
	});
	let S = !0, C = [];
	return n.safeMode || s("First Char Optimization", () => {
		C = l.reduce((e, r, o) => {
			if (typeof r.PATTERN == "string") z(e, V(r.PATTERN.charCodeAt(0)), x[o]);
			else if (Array.isArray(r.START_CHARS_HINT)) {
				let t;
				r.START_CHARS_HINT.forEach((n) => {
					let r = V(typeof n == "string" ? n.charCodeAt(0) : n);
					/* istanbul ignore else */
					t !== r && (t = r, z(e, r, x[o]));
				});
			} else if (r.PATTERN instanceof RegExp) if (r.PATTERN.unicode) S = !1, n.ensureOptimizations && t(`${i}\tUnable to analyze < ${r.PATTERN.toString()} > pattern.\n	The regexp unicode flag is not currently supported by the regexp-to-ast library.
	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);
			else {
				let t = a(r.PATTERN, n.ensureOptimizations);
				t.length === 0 && (S = !1), t.forEach((t) => {
					z(e, t, x[o]);
				});
			}
			else n.ensureOptimizations && t(`${i}\tTokenType: <${r.name}> is using a custom token pattern without providing <start_chars_hint> parameter.\n	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`), S = !1;
			return e;
		}, []);
	}), {
		emptyGroups: b,
		patternIdxToConfig: x,
		charCodeToPatternIdxToConfig: C,
		hasCustom: u,
		canBeOptimized: S
	};
}
function f(e, t) {
	let n = [], r = m(e);
	n = n.concat(r.errors);
	let i = h(r.valid), a = i.valid;
	return n = n.concat(i.errors), n = n.concat(p(a)), n = n.concat(C(a)), n = n.concat(w(a, t)), n = n.concat(T(a)), n;
}
function p(e) {
	let t = [], n = e.filter((e) => e[c] instanceof RegExp);
	return t = t.concat(_(n)), t = t.concat(b(n)), t = t.concat(x(n)), t = t.concat(S(n)), t = t.concat(v(n)), t;
}
function m(e) {
	let t = e.filter((e) => !Object.hasOwn(e, c));
	return {
		errors: t.map((e) => ({
			message: "Token Type: ->" + e.name + "<- missing static 'PATTERN' property",
			type: s.MISSING_PATTERN,
			tokenTypes: [e]
		})),
		valid: e.filter((e) => !t.includes(e))
	};
}
function h(e) {
	let t = e.filter((e) => {
		let t = e[c];
		return !(t instanceof RegExp) && typeof t != "function" && !Object.hasOwn(t, "exec") && typeof t != "string";
	});
	return {
		errors: t.map((e) => ({
			message: "Token Type: ->" + e.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
			type: s.INVALID_PATTERN,
			tokenTypes: [e]
		})),
		valid: e.filter((e) => !t.includes(e))
	};
}
var g = /[^\\][$]/;
function _(t) {
	class r extends e {
		constructor() {
			super(...arguments), this.found = !1;
		}
		visitEndAnchor(e) {
			this.found = !0;
		}
	}
	return t.filter((e) => {
		let t = e.PATTERN;
		try {
			let e = n(t), i = new r();
			return i.visit(e), i.found;
		} catch {
			/* istanbul ignore next - cannot ensure an error in regexp-to-ast*/
			return g.test(t.source);
		}
	}).map((e) => ({
		message: "Unexpected RegExp Anchor Error:\n	Token Type: ->" + e.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n	See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",
		type: s.EOI_ANCHOR_FOUND,
		tokenTypes: [e]
	}));
}
function v(e) {
	return e.filter((e) => e.PATTERN.test("")).map((e) => ({
		message: "Token Type: ->" + e.name + "<- static 'PATTERN' must not match an empty string",
		type: s.EMPTY_MATCH_PATTERN,
		tokenTypes: [e]
	}));
}
var y = /[^\\[][\^]|^\^/;
function b(t) {
	class r extends e {
		constructor() {
			super(...arguments), this.found = !1;
		}
		visitStartAnchor(e) {
			this.found = !0;
		}
	}
	return t.filter((e) => {
		let t = e.PATTERN;
		try {
			let e = n(t), i = new r();
			return i.visit(e), i.found;
		} catch {
			/* istanbul ignore next - cannot ensure an error in regexp-to-ast*/
			return y.test(t.source);
		}
	}).map((e) => ({
		message: "Unexpected RegExp Anchor Error:\n	Token Type: ->" + e.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",
		type: s.SOI_ANCHOR_FOUND,
		tokenTypes: [e]
	}));
}
function x(e) {
	return e.filter((e) => {
		let t = e[c];
		return t instanceof RegExp && (t.multiline || t.global);
	}).map((e) => ({
		message: "Token Type: ->" + e.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
		type: s.UNSUPPORTED_FLAGS_FOUND,
		tokenTypes: [e]
	}));
}
function S(e) {
	let t = [], n = e.map((n) => e.reduce((e, r) => n.PATTERN.source === r.PATTERN.source && !t.includes(r) && r.PATTERN !== o.NA ? (t.push(r), e.push(r), e) : e, []));
	return n = n.filter(Boolean), n.filter((e) => e.length > 1).map((e) => {
		let t = e.map((e) => e.name);
		return {
			message: `The same RegExp pattern ->${e[0].PATTERN}<-has been used in all of the following Token Types: ${t.join(", ")} <-`,
			type: s.DUPLICATE_PATTERNS_FOUND,
			tokenTypes: e
		};
	});
}
function C(e) {
	return e.filter((e) => {
		if (!Object.hasOwn(e, "GROUP")) return !1;
		let t = e.GROUP;
		return t !== o.SKIPPED && t !== o.NA && typeof t != "string";
	}).map((e) => ({
		message: "Token Type: ->" + e.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
		type: s.INVALID_GROUP_TYPE_FOUND,
		tokenTypes: [e]
	}));
}
function w(e, t) {
	return e.filter((e) => e.PUSH_MODE !== void 0 && !t.includes(e.PUSH_MODE)).map((e) => ({
		message: `Token Type: ->${e.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${e.PUSH_MODE}<-which does not exist`,
		type: s.PUSH_MODE_DOES_NOT_EXIST,
		tokenTypes: [e]
	}));
}
function T(e) {
	let t = [], n = e.reduce((e, t, n) => {
		let r = t.PATTERN;
		return r === o.NA || (typeof r == "string" ? e.push({
			str: r,
			idx: n,
			tokenType: t
		}) : r instanceof RegExp && D(r) && e.push({
			str: r.source,
			idx: n,
			tokenType: t
		})), e;
	}, []);
	return e.forEach((e, r) => {
		n.forEach(({ str: n, idx: i, tokenType: a }) => {
			if (r < i && E(n, e.PATTERN)) {
				let n = `Token: ->${a.name}<- can never be matched.\nBecause it appears AFTER the Token Type ->${e.name}<-in the lexer's definition.\nSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;
				t.push({
					message: n,
					type: s.UNREACHABLE_PATTERN,
					tokenTypes: [e, a]
				});
			}
		});
	}), t;
}
function E(e, t) {
	if (t instanceof RegExp) {
		if (O(t)) return !1;
		let n = t.exec(e);
		return n !== null && n.index === 0;
	} else if (typeof t == "function") return t(e, 0, [], {});
	else if (Object.hasOwn(t, "exec")) return t.exec(e, 0, [], {});
	else if (typeof t == "string") return t === e;
	else throw Error("non exhaustive match");
}
function D(e) {
	return [
		".",
		"\\",
		"[",
		"]",
		"|",
		"^",
		"$",
		"(",
		")",
		"?",
		"*",
		"+",
		"{"
	].find((t) => e.source.indexOf(t) !== -1) === void 0;
}
function O(e) {
	return /(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(e.source);
}
function k(e) {
	let t = e.ignoreCase ? "iy" : "y";
	return RegExp(`${e.source}`, t);
}
function A(e, t, n) {
	let r = [];
	return Object.hasOwn(e, "defaultMode") || r.push({
		message: "A MultiMode Lexer cannot be initialized without a <" + l + "> property in its definition\n",
		type: s.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
	}), Object.hasOwn(e, "modes") || r.push({
		message: "A MultiMode Lexer cannot be initialized without a <" + u + "> property in its definition\n",
		type: s.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
	}), Object.hasOwn(e, "modes") && Object.hasOwn(e, "defaultMode") && !Object.hasOwn(e.modes, e.defaultMode) && r.push({
		message: `A MultiMode Lexer cannot be initialized with a ${l}: <${e.defaultMode}>which does not exist\n`,
		type: s.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
	}), Object.hasOwn(e, "modes") && Object.keys(e.modes).forEach((t) => {
		let n = e.modes[t];
		n.forEach((e, i) => {
			e === void 0 ? r.push({
				message: `A Lexer cannot be initialized using an undefined Token Type. Mode:<${t}> at index: <${i}>\n`,
				type: s.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
			}) : Object.hasOwn(e, "LONGER_ALT") && (Array.isArray(e.LONGER_ALT) ? e.LONGER_ALT : [e.LONGER_ALT]).forEach((i) => {
				i !== void 0 && !n.includes(i) && r.push({
					message: `A MultiMode Lexer cannot be initialized with a longer_alt <${i.name}> on token <${e.name}> outside of mode <${t}>\n`,
					type: s.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE
				});
			});
		});
	}), r;
}
function j(e, t, n) {
	let i = [], a = !1, l = Object.values(e.modes || {}).flat().filter(Boolean).filter((e) => e[c] !== o.NA), u = R(n);
	return t && l.forEach((e) => {
		let t = I(e, u);
		if (t !== !1) {
			let n = {
				message: L(e, t),
				type: t.issue,
				tokenType: e
			};
			i.push(n);
		} else Object.hasOwn(e, "LINE_BREAKS") ? e.LINE_BREAKS === !0 && (a = !0) : r(u, e.PATTERN) && (a = !0);
	}), t && !a && i.push({
		message: "Warning: No LINE_BREAKS Found.\n	This Lexer has been defined to track line and column information,\n	But none of the Token Types can be identified as matching a line terminator.\n	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n	for details.",
		type: s.NO_LINE_BREAKS_FLAGS
	}), i;
}
function M(e) {
	let t = {};
	return Object.keys(e).forEach((n) => {
		let r = e[n];
		/* istanbul ignore else */
		if (Array.isArray(r)) t[n] = [];
		else throw Error("non exhaustive match");
	}), t;
}
function N(e) {
	let t = e.PATTERN;
	/* istanbul ignore else */
	if (t instanceof RegExp) return !1;
	if (typeof t == "function" || Object.hasOwn(t, "exec")) return !0;
	if (typeof t == "string") return !1;
	throw Error("non exhaustive match");
}
function P(e) {
	return typeof e == "string" && e.length === 1 ? e.charCodeAt(0) : !1;
}
var F = {
	test: function(e) {
		let t = e.length;
		for (let n = this.lastIndex; n < t; n++) {
			let t = e.charCodeAt(n);
			if (t === 10) return this.lastIndex = n + 1, !0;
			if (t === 13) return e.charCodeAt(n + 1) === 10 ? this.lastIndex = n + 2 : this.lastIndex = n + 1, !0;
		}
		return !1;
	},
	lastIndex: 0
};
function I(e, t) {
	if (Object.hasOwn(e, "LINE_BREAKS")) return !1;
	if (e.PATTERN instanceof RegExp) {
		try {
			r(t, e.PATTERN);
		} catch (e) {
			/* istanbul ignore next - to test this we would have to mock <canMatchCharCode> to throw an error */
			return {
				issue: s.IDENTIFY_TERMINATOR,
				errMsg: e.message
			};
		}
		return !1;
	} else if (typeof e.PATTERN == "string") return !1;
	else if (N(e)) return { issue: s.CUSTOM_LINE_BREAK };
	else throw Error("non exhaustive match");
}
function L(e, t) {
	/* istanbul ignore else */
	if (t.issue === s.IDENTIFY_TERMINATOR) return `Warning: unable to identify line terminator usage in pattern.
\tThe problem is in the <${e.name}> Token Type\n\t Root cause: ${t.errMsg}.\n	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;
	if (t.issue === s.CUSTOM_LINE_BREAK) return `Warning: A Custom Token Pattern should specify the <line_breaks> option.
\tThe problem is in the <${e.name}> Token Type\n	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;
	throw Error("non exhaustive match");
}
function R(e) {
	return e.map((e) => typeof e == "string" ? e.charCodeAt(0) : e);
}
function z(e, t, n) {
	e[t] === void 0 ? e[t] = [n] : e[t].push(n);
}
var B = [];
function V(e) {
	return e < 256 ? e : B[e];
}
function H() {
	if (B.length === 0) {
		B = Array(65536);
		for (let e = 0; e < 65536; e++) B[e] = e > 255 ? 255 + ~~(e / 255) : e;
	}
}
//#endregion
export { l as DEFAULT_MODE, F as LineTerminatorOptimizedTester, d as analyzeTokenTypes, V as charCodeToOptimizedIndex, M as cloneEmptyGroups, A as performRuntimeChecks, j as performWarningRuntimeChecks, f as validatePatterns };
