shrimp/src/parser/tests/functions.test.ts
2025-10-24 14:04:50 -07:00

151 lines
3.2 KiB
TypeScript

import { expect, describe, test } from 'bun:test'
import '../shrimp.grammar' // Importing this so changes cause it to retest!
describe('calling functions', () => {
test('call with no args', () => {
expect('tail').toMatchTree(`
FunctionCallOrIdentifier
Identifier tail
`)
})
test('call with arg', () => {
expect('tail path').toMatchTree(`
FunctionCall
Identifier tail
PositionalArg
Identifier path
`)
})
test('call with arg and named arg', () => {
expect('tail path lines=30').toMatchTree(`
FunctionCall
Identifier tail
PositionalArg
Identifier path
NamedArg
NamedArgPrefix lines=
Number 30
`)
})
test('command with arg that is also a command', () => {
expect('tail tail').toMatchTree(`
FunctionCall
Identifier tail
PositionalArg
Identifier tail
`)
expect('tai').toMatchTree(`
FunctionCallOrIdentifier
Identifier tai
`)
})
test('Incomplete namedArg', () => {
expect('tail lines=').toMatchTree(`
FunctionCall
Identifier tail
NamedArg
NamedArgPrefix lines=
`)
})
})
describe('Do', () => {
test('parses function no parameters', () => {
expect('do: 1 end').toMatchTree(`
FunctionDef
keyword do
Params
colon :
Number 1
keyword end`)
})
test('parses function with single parameter', () => {
expect('do x: x + 1 end').toMatchTree(`
FunctionDef
keyword do
Params
AssignableIdentifier x
colon :
BinOp
Identifier x
Plus +
Number 1
keyword end`)
})
test('parses function with multiple parameters', () => {
expect('do x y: x * y end').toMatchTree(`
FunctionDef
keyword do
Params
AssignableIdentifier x
AssignableIdentifier y
colon :
BinOp
Identifier x
Star *
Identifier y
keyword end`)
})
test('parses multiline function with multiple statements', () => {
expect(`do x y:
x * y
x + 9
end`).toMatchTree(`
FunctionDef
keyword do
Params
AssignableIdentifier x
AssignableIdentifier y
colon :
BinOp
Identifier x
Star *
Identifier y
BinOp
Identifier x
Plus +
Number 9
keyword end`)
})
test('does not parse identifiers that start with fn', () => {
expect('fnnn = do x: x end').toMatchTree(`
Assign
AssignableIdentifier fnnn
Eq =
FunctionDef
keyword do
Params
AssignableIdentifier x
colon :
FunctionCallOrIdentifier
Identifier x
keyword end`)
})
test('does not parse identifiers that start with end', () => {
expect('enddd = do x: x end').toMatchTree(`
Assign
AssignableIdentifier enddd
Eq =
FunctionDef
keyword do
Params
AssignableIdentifier x
colon :
FunctionCallOrIdentifier
Identifier x
keyword end`)
})
})