Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expression body parser #162

Merged
merged 4 commits into from
Aug 13, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class SourceMap {

toString(): string { return `[${this.start}, ${this.end}]` }
covers(offset: number): boolean { return this.start.offset <= offset && this.end.offset >= offset }
includes(other: SourceMap): boolean { return this.start.offset <= other.start.offset && this.end.offset >= other.end.offset }
}

export class Annotation {
Expand Down
20 changes: 14 additions & 6 deletions src/parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Parsimmon, { alt as alt_parser, index, lazy, makeSuccess, notFollowedBy, of, Parser, regex, seq, seqObj, string, whitespace, any, Index } from 'parsimmon'
import Parsimmon, { alt as alt_parser, index, lazy, makeSuccess, notFollowedBy, of, Parser, regex, seq, seqObj, string, whitespace, any, Index, newline } from 'parsimmon'
import unraw from 'unraw'
import { BaseProblem, SourceIndex, Assignment as AssignmentNode, Body as BodyNode, Catch as CatchNode, Class as ClassNode, Describe as DescribeNode, Entity as EntityNode, Expression as ExpressionNode, Field as FieldNode, If as IfNode, Import as ImportNode, Literal as LiteralNode, Method as MethodNode, Mixin as MixinNode, Name, NamedArgument as NamedArgumentNode, New as NewNode, Node, Package as PackageNode, Parameter as ParameterNode, Program as ProgramNode, Reference as ReferenceNode, Return as ReturnNode, Self as SelfNode, Send as SendNode, Sentence as SentenceNode, Singleton as SingletonNode, Super as SuperNode, Test as TestNode, Throw as ThrowNode, Try as TryNode, Variable as VariableNode, SourceMap, Closure as ClosureNode, ParameterizedType as ParameterizedTypeNode, Level, LiteralValue, Annotation } from './model'
import { List, mapObject, discriminate, is } from './extensions'
Expand Down Expand Up @@ -58,7 +58,7 @@ const error = (code: string) => (...safewords: string[]) => {
alt(
skippableContext,
comment,
notFollowedBy(alt(key('}'), ...breakpoints)).then(any),
notFollowedBy(alt(key('}'), newline, ...breakpoints)).then(any),
)
)

Expand Down Expand Up @@ -178,6 +178,17 @@ export const Body: Parser<BodyNode> = node(BodyNode)(() =>
obj({ sentences: alt(Sentence.skip(__), sentenceError).many() }).wrap(key('{'), key('}')).map(recover)
)

export const ExpressionBody: Parser<BodyNode> = node(BodyNode)(() => {
return obj(
{
sentences: alt(Expression.skip(__).map(value => {
return new ReturnNode({ value })
}), sentenceError).times(1),
}
).wrap(_, _).map(recover)
})


const inlineableBody: Parser<BodyNode> = Body.or(
node(BodyNode)(() => obj({ sentences: Sentence.times(1) })).map(body =>
body.copy({
Expand Down Expand Up @@ -315,10 +326,7 @@ export const Method: Parser<MethodNode> = node(MethodNode)(() =>
name: key('method').then(alt(name, operator(ALL_OPERATORS))),
parameters,
body: alt(
key('=').then(Expression.map(value => new BodyNode({
sentences: [new ReturnNode({ value })],
sourceMap: value.sourceMap,
}))),
key('=').then(ExpressionBody),

key('native'),

Expand Down
2 changes: 1 addition & 1 deletion src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,7 @@ const validationsByKind = (node: Node): Record<string, Validation<any>> => match
export default (target: Node): List<Problem> => target.reduce<Problem[]>((found, node) => {
return [
...found,
...node.problems?.map(({ code }) => ({ code, level: 'error', node, values: [], source: node.sourceMap } as const) ) ?? [],
...node.problems?.map(({ code, sourceMap, level, values }) => ({ code, level, node, values, sourceMap: sourceMap ?? node.sourceMap } as Problem) ) ?? [],
...entries(validationsByKind(node))
.map(([code, validation]) => validation(node, code)!)
.filter(result => result !== null),
Expand Down
2 changes: 1 addition & 1 deletion test/game.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('Wollok Game', () => {
describe('actions', () => {

let environment: Environment
let interpreter: Interpreter
let interpreter: Interpreter


before(async () => {
Expand Down
10 changes: 5 additions & 5 deletions test/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ describe('Wollok Validations', () => {
}))
const environment = buildEnvironment(files)

const matchesExpectation = (problem: Problem, expected: Annotation) => {
const matchesExpectation = (problem: Problem, annotatedNode: Node, expected: Annotation) => {
const code = expected.args.get('code')!
return problem.code === code && problem.sourceMap?.toString() === problem.node.sourceMap?.toString()
return problem.code === code && annotatedNode.sourceMap?.includes(problem.sourceMap!)
}

const errorLocation = (node: Node | Problem): string => `${node.sourceMap}`
Expand Down Expand Up @@ -53,11 +53,11 @@ describe('Wollok Validations', () => {

if (!code) fail('Missing required "code" argument in @Expect annotation')

const errors = problems.filter(problem => !matchesExpectation(problem, expectedProblem))
const errors = problems.filter(problem => !matchesExpectation(problem, node, expectedProblem))
if (notEmpty(errors))
fail(`File contains errors: ${errors.map((_error) => _error.code + ' at ' + errorLocation(_error)).join(', ')}`)

const effectiveProblem = problems.find(problem => matchesExpectation(problem, expectedProblem))
const effectiveProblem = problems.find(problem => matchesExpectation(problem, node, expectedProblem))
if (!effectiveProblem)
fail(`Missing expected ${code} ${level ?? 'problem'} at ${errorLocation(node)}`)

Expand All @@ -67,7 +67,7 @@ describe('Wollok Validations', () => {
}

for (const problem of problems) {
if (!expectedProblems.some(expectedProblem => matchesExpectation(problem, expectedProblem)))
if (!expectedProblems.some(expectedProblem => matchesExpectation(problem, node, expectedProblem)))
fail(`Unexpected ${problem.code} ${problem.level} at ${errorLocation(node)}`)
}
})
Expand Down