@stordata/grammars
Version:
A collection of ANTLR grammars used at Stordata. This project exists so that we can package the grammars (and various utilities) as a CommonJS module. The `antlr4` Javascript runtime is only available as an ES module at the time of writing.
65 lines (47 loc) • 1.42 kB
JavaScript
import CSVVisitor from '../../generated/src/grammars/CSVVisitor.js';
export default class CSVParserVisitor extends CSVVisitor {
constructor() {
super();
this.lines = [];
this.headers = [];
this.delimiter = undefined;
}
visitAll(ctx) {
super.visitAll(ctx);
return {
lines: this.lines,
headers: this.headers,
delimiter: this.delimiter
};
}
visitHeaders(ctx) {
super.visitHeaders(ctx);
this.headers = this.lines.shift();
}
visitLine(ctx) {
this.line = [];
super.visitLine(ctx);
this.lines.push(this.line);
}
visitColumn(ctx) {
let text = ctx.getText().trim();
const isQuoted = text.startsWith('"') && text.endsWith('"');
if (isQuoted) {
text = text.slice(1, -1).replaceAll('""', '"');
}
const index = ctx.parentCtx.children.indexOf(ctx);
if (index === 0) { // First column is always the start of a new line
this.line.push(text);
} else {
const delimiter = ctx.parentCtx.children[index - 1].getText();
if (!this.delimiter) { // This is the very first delimiter found in the file
this.delimiter = delimiter;
}
if (delimiter !== this.delimiter) { // This column was split erroneously, merge it with the previous one
this.line[this.line.length - 1] += delimiter + ctx.getText();
} else {
this.line.push(text);
}
}
}
}