/*
*  Lexer post-processor functionality for the LibreSignage
*  markup transpiler.
*/

var ldefs = require('./lexer_defs.js');
var lexeme = require('./lexeme.js')

module.exports.lexer_post = function(lexemes) {
	/*
	*  Main lexer post-processing function.
	*
	*  This function processes the lexemes array using
	*  the post-processing functions defined in ldefs.post.
	*  Each post-processing function is used called separately
	*  to modify the lexemes array in some way. This file also
	*  contains a couple of generic post-processing functions
	*  that can be used in the ldefs.post configuration object.
	*
	*  This function returns the resulting lexemes array.
	*/
	let ret = lexemes.slice();
	for (let p of ldefs.post) {
		ret = p.post(ret, p.type);
	}
	return ret;
}

module.exports.lexer_post_suppress = function(lexemes, type) {
	/*
	*  Suppress all lexemes of type 'type' in 'lexemes'.
	*/
	let ret = [];
	for (let l of lexemes) {
		if (l.type != type) {
			ret.push(l);
		}
	}
	return ret;
}

module.exports.lexer_post_cat = function(lexemes, type) {
	/*
	*  Concatenate all lexemes of type 'type' in 'lexemes'.
	*/
	let buf = null;
	let ret = [];
	for (let l of lexemes) {
		if (l.type == type) {
			if (!buf) {
				buf = l.clone();
			} else {
				buf.raw += l.raw;
			}
		} else {
			if (buf) {
				ret.push(buf);
				buf = null;
			}
			ret.push(l);
		}
	}
	return ret;
}
