Skip to content

Commit 4e22467

Browse files
committed
add assertions
1 parent 04d004e commit 4e22467

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

packages/compiler/test/test-cstReader.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,29 @@ test('withChildren, tupleArity, forEachTuple, and isPresent', async t => {
178178
});
179179
});
180180

181+
test('type-specific helpers assert on the wrong handle kind', async t => {
182+
const g = await compileAndLoad('G { Start = ("a" "b"?)* }');
183+
g.match('ab').use(mr => {
184+
const reader = createReader(mr);
185+
let list;
186+
reader.forEachChild(reader.root, child => {
187+
list = child;
188+
});
189+
190+
let terminal;
191+
let opt;
192+
reader.forEachTuple(list, (a, b) => {
193+
terminal = a;
194+
opt = b;
195+
});
196+
197+
t.throws(() => reader.ruleId(list), {message: 'Not a nonterminal'});
198+
t.throws(() => reader.tupleArity(reader.root), {message: 'Not a list'});
199+
t.throws(() => reader.isPresent(terminal), {message: 'Not an opt'});
200+
t.true(reader.isPresent(opt));
201+
});
202+
});
203+
181204
// --- unparse via walk ---
182205

183206
test('unparse: simple terminals', async t => {

packages/runtime/src/cstReader.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
MatchRecordType,
99
rawMatchRecordType,
1010
} from './miniohm.ts';
11+
import {assert} from './assert.ts';
1112

1213
import type {MatchContext, SucceededMatchResult} from './miniohm.ts';
1314

@@ -156,16 +157,19 @@ export class CstReader {
156157

157158
/** Rule ID for a nonterminal node. */
158159
ruleId(handle: number): number {
160+
assert(this.type(handle) === CstNodeType.NONTERMINAL, 'Not a nonterminal');
159161
return this.details(handle);
160162
}
161163

162164
/** Children per tuple for a list node. */
163165
tupleArity(handle: number): number {
166+
assert(this.type(handle) === CstNodeType.LIST, 'Not a list');
164167
return this.details(handle);
165168
}
166169

167170
/** Whether an optional node has a child. */
168171
isPresent(handle: number): boolean {
172+
assert(this.type(handle) === CstNodeType.OPT, 'Not an opt');
169173
return this.childCount(handle) > 0;
170174
}
171175

0 commit comments

Comments
 (0)