forked from azimuttapp/azimutt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserde.ts
36 lines (30 loc) · 1.26 KB
/
serde.ts
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
import {Database} from "../database";
// every serde should implement this interface
export interface Serde {
name: string
parse(content: string): ParserResult<Database>
generate(db: Database): string
}
export type ParserPosition = [number, number] // [start, end]
export type ParserError = {
name: string,
message: string,
position?: { offset: ParserPosition, line: ParserPosition, column: ParserPosition }
}
export class ParserResult<T> {
private constructor(public result?: T, public errors?: ParserError[], public warnings?: ParserError[]) {
Object.freeze(this)
}
public static success<U>(result: U): ParserResult<U> {
return new ParserResult<U>(result)
}
public static failure<U>(errors: ParserError[], warnings?: ParserError[]): ParserResult<U> {
return new ParserResult<U>(undefined, errors, warnings)
}
public map<U>(f: (t: T) => U): ParserResult<U> {
return new ParserResult<U>(this.result !== undefined ? f(this.result) : undefined, this.errors, this.warnings)
}
public fold<U>(onSuccess: (t: T) => U, onFailure: (e: ParserError[]) => U): U {
return this.result !== undefined ? onSuccess(this.result) : onFailure((this.errors || []).concat(this.warnings || []))
}
}