All files / src/context context.ts

96% Statements 24/25
83.33% Branches 5/6
80% Functions 4/5
96% Lines 24/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68      1x 1x 1x     1x                   627x 627x 627x 627x 627x 627x 627x           7035x 6397x       7035x   7035x 241x 241x 241x   7035x     7035x     7035x 7035x         7019x                       1x  
import { Source } from './source';
import { Location } from './location';
 
export enum ContentModel {
	TEXT = 1,
	SCRIPT,
}
 
export class Context {
	state: number;
	string: string;
	filename: string;
	line: number;
	column: number;
	contentModel: ContentModel;
	scriptEnd: string;
 
	constructor(source: Source){
		this.state = undefined;
		this.string = source.data;
		this.filename = source.filename;
		this.line = 1;
		this.column = 1;
		this.contentModel = ContentModel.TEXT;
		this.scriptEnd = undefined;
	}
 
	consume(n: number|Array<string>, state?: number){
		/* if "n" is an regex match the first value is the full matched
		 * string so consume that many characters. */
		if (typeof n !== 'number'){
			n = n[0].length; /* regex match */
		}
 
		/* poor mans line counter :( */
		let consumed = this.string.slice(0, n);
		let offset;
		while ((offset = consumed.indexOf('\n')) >= 0){
			this.line++;
			this.column = 1;
			consumed = consumed.substr(offset + 1);
		}
		this.column += consumed.length;
 
		/* remove N chars */
		this.string = this.string.substr(n);
 
		/* change state */
		Eif (typeof state !== 'undefined'){
			this.state = state;
		}
	}
 
	getLocation(): Location {
		return {
			filename: this.filename,
			line: this.line,
			column: this.column,
		};
	}
 
	getLocationString(): string {
		return `${this.filename}:${this.line}:${this.column}`;
	}
}
 
export default Context;