Skip to content

Commit

Permalink
making API for javascripty
Browse files Browse the repository at this point in the history
  • Loading branch information
chanind committed Dec 31, 2023
1 parent 846f2fa commit ef07eef
Show file tree
Hide file tree
Showing 23 changed files with 199 additions and 218 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"functional/immutable-data": "off",
"functional/prefer-immutable-types": "off",
"functional/no-throw-statements": "off",
"functional/no-mixed-types": "off",
"functional/functional-parameters": "off",
"functional/prefer-type-literal": "off",
"no-constant-condition": "off",
Expand Down
2 changes: 1 addition & 1 deletion src/graph.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { Graph, Triple, Instance, Edge, Attribute } from './lib/graph';
export { Graph, Instance, Edge, Attribute } from './lib/graph';
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
export { parse, iterparse, parseTriples } from './lib/_parse';
export { format, formatTriples } from './lib/_format';
export { parse, iterparse, parseTriples } from './lib/parse';
export { format, formatTriples } from './lib/format';
export { interpret, configure } from './lib/layout';
export { Tree } from './lib/tree';
export { Graph, Triple } from './lib/graph';
export { Graph } from './lib/graph';
export { Triple } from './lib/types';
export {
PENMANCodec,
decode,
Expand Down
7 changes: 5 additions & 2 deletions src/lib/_lexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ export class TokenIterator {
this._next = null;
}
this._last = current;
if (current == null) {
throw new Error('Unexpected end of input');
}
return current;
}

Expand Down Expand Up @@ -155,7 +158,7 @@ export class TokenIterator {
}

error(message: string, token?: Token): DecodeError {
let line: string | null = null;
let line: string | undefined;
let lineno: number;
let offset: number;
if (token == null) {
Expand Down Expand Up @@ -226,7 +229,7 @@ const _lex = function* (
`capturing group:\n${regex.source}`,
);
}
const token: Token = [typ, val, i, m.index, line];
const token: Token = [typ, val, i, m.index ?? 0, line];
debug(`${token}`);
yield token;
}
Expand Down
25 changes: 11 additions & 14 deletions src/lib/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
* Serialization of PENMAN graphs.
*/

import { format, formatTriples } from './_format';
import { iterparse, parse, parseTriples } from './_parse';
import { format, formatTriples } from './format';
import { Graph } from './graph';
import * as layout from './layout';
import { Model } from './model';
import { iterparse, parse, parseTriples } from './parse';
import { Tree } from './tree';
import { BasicTriple, Node, Variable } from './types';
import { Node, Triple, Variable } from './types';

// "Utility" types; not Penman-specific

Expand All @@ -18,11 +18,8 @@ import { BasicTriple, Node, Variable } from './types';
export class PENMANCodec {
model: Model;

constructor(model: Model | null = null) {
if (model === null) {
model = new Model();
}
this.model = model;
constructor(model?: Model) {
this.model = model ?? new Model();
}

/**
Expand All @@ -31,7 +28,7 @@ export class PENMANCodec {
* @param s - A string containing a single PENMAN-serialized graph.
* @returns The `Graph` object described by `s`.
* @example
* import { PENMANCodec } from 'penman-js/codec';
* import { PENMANCodec } from 'penman-js';
*
* const codec = new PENMANCodec();
* const graph = codec.decode('(b / bark-01 :ARG0 (d / dog))');
Expand All @@ -40,7 +37,7 @@ export class PENMANCodec {
*/
decode(s: string): Graph {
const tree = parse(s);
return layout.interpret(tree, this.model);
return layout.interpret(tree, { model: this.model });
}

/**
Expand All @@ -51,7 +48,7 @@ export class PENMANCodec {
*/
*iterdecode(lines: string | string[]): IterableIterator<Graph> {
for (const tree of iterparse(lines)) {
yield layout.interpret(tree, this.model);
yield layout.interpret(tree, { model: this.model });
}
}

Expand All @@ -78,7 +75,7 @@ export class PENMANCodec {
/**
* Parse a triple conjunction from *s*.
*/
parseTriples(s: string): BasicTriple[] {
parseTriples(s: string): Triple[] {
return parseTriples(s);
}

Expand All @@ -104,7 +101,7 @@ export class PENMANCodec {
indent: number | null | undefined = -1,
compact = false,
): string {
const tree = layout.configure(g, top, this.model);
const tree = layout.configure(g, { top, model: this.model });
return this.format(tree, indent, compact);
}

Expand Down Expand Up @@ -137,7 +134,7 @@ export class PENMANCodec {
* // Expected output:
* // 'instance(a, alpha) ^\\nARG0(a, b) ^\\ninstance(b, beta)'
*/
formatTriples(triples: BasicTriple[], indent = true): string {
formatTriples(triples: Triple[], indent = true): string {
return formatTriples(triples, indent);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const type = (constant_string: string | null | undefined): Type => {
export const evaluate = (
constantString: string | null | undefined,
): Constant => {
let value: Constant = constantString;
let value: Constant = constantString ?? null;
if (constantString == null || constantString === '') {
value = null;
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/epigraph.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Base classes for epigraphical markers. */

import { BasicTriple } from './types';
import { Triple } from './types';
import { ArrayKeysMap } from './utils';

export class Epidatum {
Expand All @@ -16,4 +16,4 @@ export class Epidatum {

export type Epidata = Epidatum[];

export class EpidataMap extends ArrayKeysMap<BasicTriple, Epidata> {}
export class EpidataMap extends ArrayKeysMap<Triple, Epidata> {}
21 changes: 5 additions & 16 deletions src/lib/exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,14 @@ export class LayoutError extends PenmanError {}
* @noInheritDoc
*/
export class DecodeError extends PenmanError {
message: string;
filename: string;
lineno: number;
offset: number;
text: string;

constructor(
message: string = null,
filename: string = null,
lineno: number = null,
offset: number = null,
text: string = null,
message: string,
public filename?: string,
public lineno?: number,
public offset?: number,
public text?: string,
) {
super(message);
this.message = message;
this.filename = filename;
this.lineno = lineno;
this.offset = offset;
this.text = text;
}

toString(): string {
Expand Down
6 changes: 3 additions & 3 deletions src/lib/format.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test from 'ava';

import { format, formatTriples } from './_format';
import { BasicTriple, Node } from './types';
import { format, formatTriples } from './format';
import { Node, Triple } from './types';

test('format', (t) => {
const input: Node = [
Expand All @@ -16,7 +16,7 @@ test('format', (t) => {
});

test('format_triples', (t) => {
const triples: BasicTriple[] = [
const triples: Triple[] = [
['b', 'instance', 'bark-01'],
['b', 'ARG0', 'd'],
['d', 'instance', 'dog'],
Expand Down
11 changes: 4 additions & 7 deletions src/lib/_format.ts → src/lib/format.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isAtomic, Tree } from './tree';
import { BasicTriple, Branch, Node } from './types';
import { Branch, Node, Triple } from './types';
import { lstrip } from './utils';

/**
Expand Down Expand Up @@ -51,10 +51,7 @@ export const format = (
* // ARG0(b, d) ^
* // instance(d, dog)
*/
export const formatTriples = (
triples: BasicTriple[],
indent = true,
): string => {
export const formatTriples = (triples: Triple[], indent = true): string => {
const delim = indent ? ' ^\n' : ' ^ ';
// need to remove initial : on roles for triples
const conjunction = triples.map(
Expand All @@ -76,7 +73,7 @@ const _formatNode = (
if (!variable) {
return '()'; // empty node
}
if (!edges.length) {
if (!edges?.length) {
return `(${variable})`; // var-only node
}
// determine appropriate joiner based on value of indent
Expand Down Expand Up @@ -118,7 +115,7 @@ const _formatNode = (
*/
const _formatEdge = (
edge: Branch,
indent: number | null,
indent: number | null | undefined,
column: number,
vars: Set<string>,
): string => {
Expand Down
22 changes: 5 additions & 17 deletions src/lib/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,11 @@ import isEqual from 'lodash.isequal';

import { EpidataMap } from './epigraph';
import { GraphError } from './exceptions';
import type {
BasicTriple,
Constant,
Role,
Target,
Triples,
Variable,
} from './types';
import type { Constant, Role, Triple, Triples, Variable } from './types';
import { defaultdictPlusEqual } from './utils';

export const CONCEPT_ROLE = ':instance';

/**
* Represents a relation between nodes or between a node and a constant.
*/
export type Triple = [source: Variable, role: Role, target: Target];

/**
* A relation indicating the concept of a node.
*/
Expand Down Expand Up @@ -77,7 +65,7 @@ export class Graph {
*/
constructor(
public triples: Triples = [],
top: Variable = null,
top: Variable | null = null,
public epidata: EpidataMap = new EpidataMap(),
public metadata: Record<string, string> = {},
) {
Expand Down Expand Up @@ -189,10 +177,10 @@ export class Graph {
}
const possible_sources = this.triples.map((t) => t[0]);
const possible_targets = this.triples.map((t) => t[2]);
const possible_variables = new Set(
const possibleVariables = new Set(
possible_targets.concat(possible_sources),
);
if (!possible_variables.has(this._top)) {
if (!possibleVariables.has(this._top)) {
this._top = null;
}
return this;
Expand Down Expand Up @@ -271,7 +259,7 @@ export class Graph {
source: Variable | null = null,
role: Role | null = null,
target: Constant | null = null,
): BasicTriple[] {
): Triple[] {
// TODO: check for undefined OR null
if (source == null && role == null && target == null) {
return this.triples.slice();
Expand Down
18 changes: 9 additions & 9 deletions src/lib/layout.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ test('interpret', (t) => {
),
);
t.true(
interpret(t2, amrModel()).equals(
interpret(t2, { model: amrModel() }).equals(
new Graph(
[
['a', ':instance', 'A'],
Expand All @@ -62,7 +62,7 @@ test('rearrange', (t) => {
:ARG1 (d / delta))
:ARG0-of d
:ARG1 (e / epsilon))`);
rearrange(t1, model.originalOrder);
rearrange(t1, { key: model.originalOrder });
t.is(
codec.format(t1),
`(a / alpha
Expand All @@ -73,7 +73,7 @@ test('rearrange', (t) => {
:ARG1 (e / epsilon))`,
);

rearrange(t1, model.canonicalOrder.bind(model));
rearrange(t1, { key: model.canonicalOrder.bind(model) });
t.is(
codec.format(t1),
`(a / alpha
Expand All @@ -87,7 +87,7 @@ test('rearrange', (t) => {
test('configure', (t) => {
const g = codec.decode('(a / A)');
t.deepEqual(configure(g), new Tree(['a', [['/', 'A']]]));
t.throws(() => configure(g, 'A'), { instanceOf: LayoutError });
t.throws(() => configure(g, { top: 'A' }), { instanceOf: LayoutError });

const g1 = codec.decode('(a / A :consist-of (b / B))');
t.deepEqual(
Expand All @@ -101,7 +101,7 @@ test('configure', (t) => {
]),
);
t.deepEqual(
configure(g1, 'b'),
configure(g1, { top: 'b' }),
new Tree([
'b',
[
Expand All @@ -114,7 +114,7 @@ test('configure', (t) => {
const amrCodec = new PENMANCodec(amrModel());
const g2 = amrCodec.decode('(a / A :consist-of (b / B))');
t.deepEqual(
configure(g2, undefined, amrModel()),
configure(g2, { model: amrModel() }),
new Tree([
'a',
[
Expand All @@ -124,7 +124,7 @@ test('configure', (t) => {
]),
);
t.deepEqual(
configure(g2, 'b', amrModel()),
configure(g2, { top: 'b', model: amrModel() }),
new Tree([
'b',
[
Expand Down Expand Up @@ -222,7 +222,7 @@ test('reconfigure', (t) => {
// canonical order reconfiguration can also shift things like
// inverted arguments
t.deepEqual(
reconfigure(g, undefined, undefined, model.canonicalOrder.bind(model)),
reconfigure(g, { key: model.canonicalOrder.bind(model) }),
new Tree([
'a',
[
Expand Down Expand Up @@ -343,7 +343,7 @@ test('issue 92', (t) => {
]),
);
t.deepEqual(
configure(g, 'b'),
configure(g, { top: 'b' }),
new Tree([
'b',
[
Expand Down
Loading

0 comments on commit ef07eef

Please sign in to comment.