Skip to content

Commit

Permalink
Implement delete statement for container entries
Browse files Browse the repository at this point in the history
ref #337
  • Loading branch information
frostburn committed Jun 4, 2024
1 parent 552ce60 commit 552fdf7
Show file tree
Hide file tree
Showing 5 changed files with 271 additions and 1 deletion.
14 changes: 14 additions & 0 deletions documentation/advanced-dsl.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,20 @@ or `{a: 5, b: 10, c: 15}`.

The `r` at the end of real literals just means that they're not cents or associated with the octave in any way. Real cent literals like `600rc` have the same size as their radical counterparts but `linear(2 * 600rc)` won't simplify to `2` like `linear(2 * 600.0)` does.

## Deleting container contents
Record or array entries can be removed using the `delete` keyword. Access using individual keys, arrays of indices, boolean arrays and slices are valid targets for removal. The specified entries are popped from the array and subsequent entries are shifted back similar to how `del` works in Python.

```ocaml
"Sieve of Eratosthenes using boolean indexing with delete"
const primes = [2..100]
let i = -1
while (++i < length(primes))
delete primes[primes > primes[i] vand vnot primes mod primes[i]]
primes
```

Deleting a non-existent entry throws an error unless the access was nullish i.e. `delete arr~[idx]`.

## Blocks
Blocks start with a curly bracket `{`, have their own instance of a current scale `$` and end with `}`. The current scale is unrolled onto the parent scale at the end of the block.

Expand Down
6 changes: 6 additions & 0 deletions src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ export type ImportAllStatement = {
module: string;
};

export type DeleteStatement = {
type: 'DeleteStatement';
entry: AccessExpression | ArraySlice;
};

export type ExpressionStatement = {
type: 'ExpressionStatement';
expression: Expression;
Expand All @@ -263,6 +268,7 @@ export type Statement =
| PitchDeclaration
| UpDeclaration
| LiftDeclaration
| DeleteStatement
| BlockStatement
| WhileStatement
| IfStatement
Expand Down
12 changes: 11 additions & 1 deletion src/grammars/sonic-weave.pegjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
'const',
'continue',
'defer',
'delete',
'dot',
'drop',
'ed',
Expand Down Expand Up @@ -71,7 +72,6 @@
'case',
'debugger',
'default',
'delete',
'immutable',
'match',
'yield',
Expand Down Expand Up @@ -158,6 +158,7 @@ CatchToken = @'catch' !IdentifierPart
ConstToken = @'const' !IdentifierPart
ContinueToken = @'continue' !IdentifierPart
DeferToken = @'defer' !IdentifierPart
DeleteToken = @'delete' !IdentifierPart
DotToken = @'dot' !IdentifierPart
DropToken = @'drop' !IdentifierPart
EdToken = @'ed' !IdentifierPart
Expand Down Expand Up @@ -230,6 +231,7 @@ Statement
/ IterationStatement
/ TryStatement
/ DeferStatement
/ DeleteStatement
/ ModuleDeclaration
/ ExportConstantStatement
/ ExportFunctionStatement
Expand Down Expand Up @@ -357,6 +359,14 @@ LiftDeclaration
};
}

DeleteStatement
= DeleteToken _ entry: (TrueAccessExpression / ArraySlice) EOS {
return {
type: 'DeleteStatement',
entry,
};
}

Parameter
= identifier: Identifier defaultValue: (_ '=' _ @Expression)? {
return {
Expand Down
70 changes: 70 additions & 0 deletions src/parser/__tests__/source.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1903,4 +1903,74 @@ describe('SonicWeave parser', () => {
'6/3 "bob" white',
]);
});

it('can delete record entries', () => {
const scale = expand(`{
const foo = {bar: 1, baz: 2}
delete foo['bar']
foo
}`);
expect(scale).toEqual(['2 "baz"']);
});

it('can delete array elements', () => {
const scale = expand(`{
const foo = primeRange(5)
delete foo[2]
foo
}`);
expect(scale).toEqual(['2', '3', '7', '11']);
});

it('can delete multiple array elements (boolean)', () => {
const scale = expand(`{
const primes = [2..30]
let i = -1
while (++i < length(primes))
delete primes[primes > primes[i] vand vnot primes mod primes[i]]
primes
}`);
expect(scale).toEqual([
'2',
'3',
'5',
'7',
'11',
'13',
'17',
'19',
'23',
'29',
]);
});

it('can delete multiple array elements (indices)', () => {
const scale = expand(`{
const foo = primeRange(6)
delete foo[[1, 3]]
foo
}`);
expect(scale).toEqual(['2', '5', '11', '13']);
});

it('can delete multiple array elements (slice)', () => {
const scale = expand(`{
const foo = primeRange(7)
delete foo[1,3..]
foo
}`);
expect(scale).toEqual(['2', '5', '11', '17']);
});

it('throws for out-of-bounds delete', () => {
expect(() => parseSource('delete [1, 2][3]')).toThrow(
'Index out of range.'
);
});

it("doesn't throw for out-of-bounds nullish delete", () => {
expect(() => parseSource('delete [1, 2]~[3]')).not.toThrow(
'Index out of range.'
);
});
});
170 changes: 170 additions & 0 deletions src/parser/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
ImportStatement,
ImportAllStatement,
MosDeclaration,
DeleteStatement,
} from '../ast';
import {
ExpressionVisitor,
Expand All @@ -51,6 +52,7 @@ import {
containerToArray,
} from './expression';
import {Tardigrade} from './mos';
import {hasOwn} from '../utils';

/**
* An interrupt representing a return, break or continue statement.
Expand Down Expand Up @@ -316,12 +318,180 @@ export class StatementVisitor {
return this.visitImportAllStatement(node);
case 'MosDeclaration':
return this.visitMosDeclaration(node);
case 'DeleteStatement':
return this.visitDeleteStatement(node);
case 'EmptyStatement':
return;
}
node satisfies never;
}

protected visitDeleteStatement(node: DeleteStatement) {
const subVisitor = this.createExpressionVisitor();
const entry = node.entry;
const object = arrayRecordOrString(subVisitor.visit(entry.object));
if (typeof object === 'string') {
throw new Error('Strings are immutable.');
}
if (entry.type === 'AccessExpression') {
if (!Array.isArray(object)) {
const key = subVisitor.visit(entry.key);
if (!(typeof key === 'string')) {
throw new Error('Record keys must be strings.');
}
if (!hasOwn(object, key) && !entry.nullish) {
throw new Error(`Key error: "${key}".`);
}
delete object[key];
return undefined;
}
let index = subVisitor.visit(entry.key);
if (Array.isArray(index)) {
const toDelete = new Set<number>();
index = index.flat(Infinity);
for (let i = 0; i < index.length; ++i) {
const idx = index[i];
if (!(typeof idx === 'boolean' || idx instanceof Interval)) {
throw new Error(
'Only booleans and intervals can be used as indices.'
);
}
if (idx === true) {
if (i >= object.length) {
if (!entry.nullish) {
throw new Error('Indexing boolean out of range.');
}
} else {
toDelete.add(i);
}
continue;
} else if (idx === false) {
continue;
}
let j = idx.toInteger();
if (j < 0) {
j += object.length;
}
if (j < 0 || j >= object.length) {
if (!entry.nullish) {
throw new Error('Index out of range.');
}
} else {
toDelete.add(j);
}
}
// Delete elements from largest to smallest.
for (const i of Array.from(toDelete).sort((a, b) => b - a)) {
object.splice(i, 1);
}
return undefined;
}
if (!(index instanceof Interval)) {
throw new Error('Array delete access with a non-integer.');
}
let i = index.toInteger();
if (i < 0) {
i += object.length;
}
if (i < 0 || i >= object.length) {
if (entry.nullish) {
return undefined;
}
throw new Error('Index out of range.');
}
object.splice(i, 1);
return undefined;
}

entry.type satisfies 'ArraySlice';
if (!Array.isArray(object)) {
throw new Error('Array slice delete on non-array.');
}
if (
entry.start === null &&
entry.second === null &&
entry.penultimate === false &&
entry.end === null
) {
object.length = 0;
return undefined;
}

// TODO: Refactor bounds calculation to be shared with ExpressionVisitor.visitArraySlice.
let start = 0;
let step = 1;
const pu = entry.penultimate;
let end = -1;

if (entry.start) {
const interval = subVisitor.visit(entry.start);
if (!(interval instanceof Interval)) {
throw new Error('Slice indices must consist of intervals.');
}
start = interval.toInteger();
}

if (entry.end) {
const interval = subVisitor.visit(entry.end);
if (!(interval instanceof Interval)) {
throw new Error('Slice indices must consist of intervals.');
}
end = interval.toInteger();
}

if (entry.second) {
const second = subVisitor.visit(entry.second);
if (!(second instanceof Interval)) {
throw new Error('Slice indices must consist of intervals.');
}
step = second.toInteger() - start;
}

if (start < 0) {
start += object.length;
}
if (end < 0) {
end += object.length;
}

const toDelete = new Set<number>();

if (step > 0) {
start = Math.max(0, start);
if ((pu ? start >= end : start > end) || start >= object.length) {
return undefined;
}
end = Math.min(object.length - 1, end);

toDelete.add(start);
let next = start + step;
while (pu ? next < end : next <= end) {
toDelete.add(next);
next += step;
}
} else if (step < 0) {
start = Math.min(object.length - 1, start);
if ((pu ? start <= end : start < end) || start < 0) {
return undefined;
}
end = Math.max(0, end);

toDelete.add(start);
let next = start + step;
while (pu ? next > end : next >= end) {
toDelete.add(next);
next += step;
}
} else {
throw new Error('Slice step must not be zero.');
}
// Delete elements from largest to smallest.
for (const i of Array.from(toDelete).sort((a, b) => b - a)) {
object.splice(i, 1);
}
return undefined;
}

protected visitMosDeclaration(node: MosDeclaration) {
if (!this.rootContext) {
throw new Error('Root context is required.');
Expand Down

0 comments on commit 552fdf7

Please sign in to comment.