Skip to content

Commit

Permalink
refactor: better method names (#661)
Browse files Browse the repository at this point in the history
### Summary of Changes

I've dropped the lengthy `OrUndefined` and `OrEmpty` suffixes from
methods of the `NodeMapper` and the functions to access node properties.
Instead, they now have a `stream` prefix if they return a stream or a
`get` prefix/no prefix otherwise. This better aligns with the name
convention of API elements provided by `langium`.
  • Loading branch information
lars-reimann authored Oct 22, 2023
1 parent 45ca2a5 commit 0157377
Show file tree
Hide file tree
Showing 59 changed files with 369 additions and 394 deletions.
46 changes: 21 additions & 25 deletions src/cli/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ import chalk from 'chalk';
import { createSafeDsServices, SafeDsServices } from '../language/safe-ds-module.js';
import { NodeFileSystem } from 'langium/node';
import {
abstractResultsOrEmpty,
assigneesOrEmpty,
blockLambdaResultsOrEmpty,
importedDeclarationsOrEmpty,
importsOrEmpty,
getAbstractResults,
getAssignees,
streamBlockLambdaResults,
getImportedDeclarations,
getImports,
isRequiredParameter,
moduleMembersOrEmpty,
statementsOrEmpty,
getModuleMembers,
getStatements,
} from '../language/helpers/nodeProperties.js';
import { IdManager } from '../language/helpers/idManager.js';
import { isInStubFile } from '../language/helpers/fileExtensions.js';
Expand Down Expand Up @@ -150,10 +150,10 @@ const formatGeneratedFileName = function (baseName: string): string {

const generateModule = function (services: SafeDsServices, module: SdsModule): string {
const importSet = new Map<String, ImportData>();
const segments = moduleMembersOrEmpty(module)
const segments = getModuleMembers(module)
.filter(isSdsSegment)
.map((segment) => generateSegment(services, segment, importSet));
const pipelines = moduleMembersOrEmpty(module)
const pipelines = getModuleMembers(module)
.filter(isSdsPipeline)
.map((pipeline) => generatePipeline(services, pipeline, importSet));
const imports = generateImports(Array.from(importSet.values()));
Expand All @@ -167,7 +167,7 @@ const generateModule = function (services: SafeDsServices, module: SdsModule): s
}
if (segments.length > 0) {
output.push(
expandToStringWithNL`# Steps ------------------------------------------------------------------------\n\n${segments.join(
expandToStringWithNL`# Segments ---------------------------------------------------------------------\n\n${segments.join(
'\n\n',
)}`,
);
Expand Down Expand Up @@ -266,7 +266,7 @@ const generateQualifiedImport = function (importStmt: ImportData): string {

const generateBlock = function (block: SdsBlock, frame: GenerationInfoFrame): string {
// TODO filter withEffect
let statements = statementsOrEmpty(block);
let statements = getStatements(block);
if (statements.length === 0) {
return 'pass';
}
Expand All @@ -291,12 +291,10 @@ const generateStatement = function (statement: SdsStatement, frame: GenerationIn

const generateAssignment = function (assignment: SdsAssignment, frame: GenerationInfoFrame): string {
const requiredAssignees = isSdsCall(assignment.expression)
? abstractResultsOrEmpty(
frame.getServices().helpers.NodeMapper.callToCallableOrUndefined(assignment.expression),
).length
? getAbstractResults(frame.getServices().helpers.NodeMapper.callToCallable(assignment.expression)).length
: /* c8 ignore next */
1;
const assignees = assigneesOrEmpty(assignment);
const assignees = getAssignees(assignment);
if (assignees.some((value) => !isSdsWildcard(value))) {
const actualAssignees = assignees.map(generateAssignee);
if (requiredAssignees === actualAssignees.length) {
Expand Down Expand Up @@ -327,12 +325,10 @@ const generateAssignee = function (assignee: SdsAssignee): string {
};

const generateBlockLambda = function (blockLambda: SdsBlockLambda, frame: GenerationInfoFrame): string {
const lambdaResult = blockLambdaResultsOrEmpty(blockLambda);
const results = streamBlockLambdaResults(blockLambda);
let lambdaBlock = generateBlock(blockLambda.body, frame);
if (lambdaResult.length !== 0 && lambdaBlock !== 'pass') {
lambdaBlock += `\nreturn ${lambdaResult
.map((result) => `${BLOCK_LAMBDA_RESULT_PREFIX}${result.name}`)
.join(', ')}`;
if (!results.isEmpty()) {
lambdaBlock += `\nreturn ${results.map((result) => `${BLOCK_LAMBDA_RESULT_PREFIX}${result.name}`).join(', ')}`;
}
return expandToString`def ${frame.getUniqueLambdaBlockName(blockLambda)}(${generateParameters(
blockLambda.parameterList,
Expand Down Expand Up @@ -431,7 +427,7 @@ const generateExpression = function (expression: SdsExpression, frame: Generatio
const suffix = isSdsCall(expression.$container) ? '' : '()';
return `${receiver}.${enumMember}${suffix}`;
} else if (isSdsAbstractResult(member)) {
const resultList = abstractResultsOrEmpty(getContainerOfType(member, isSdsCallable));
const resultList = getAbstractResults(getContainerOfType(member, isSdsCallable));
if (resultList.length === 1) {
return receiver;
}
Expand Down Expand Up @@ -474,7 +470,7 @@ const generateExpression = function (expression: SdsExpression, frame: Generatio
const sortArguments = function (services: SafeDsServices, argumentList: SdsArgument[]): SdsArgument[] {
// $containerIndex contains the index of the parameter in the receivers parameter list
const parameters = argumentList.map((argument) => {
return { par: services.helpers.NodeMapper.argumentToParameterOrUndefined(argument), arg: argument };
return { par: services.helpers.NodeMapper.argumentToParameter(argument), arg: argument };
});
return parameters
.slice()
Expand All @@ -486,7 +482,7 @@ const sortArguments = function (services: SafeDsServices, argumentList: SdsArgum
};

const generateArgument = function (argument: SdsArgument, frame: GenerationInfoFrame) {
const parameter = frame.getServices().helpers.NodeMapper.argumentToParameterOrUndefined(argument);
const parameter = frame.getServices().helpers.NodeMapper.argumentToParameter(argument);
return expandToString`${
parameter !== undefined && !isRequiredParameter(parameter)
? generateParameter(parameter, frame, false) + '='
Expand All @@ -502,13 +498,13 @@ const getExternalReferenceNeededImport = function (
// Root Node is always a module.
const currentModule = <SdsModule>findRootNode(expression);
const targetModule = <SdsModule>findRootNode(declaration);
for (const value of importsOrEmpty(currentModule)) {
for (const value of getImports(currentModule)) {
// Verify same package
if (value.package !== targetModule.name) {
continue;
}
if (isSdsQualifiedImport(value)) {
const importedDeclarations = importedDeclarationsOrEmpty(value);
const importedDeclarations = getImportedDeclarations(value);
for (const importedDeclaration of importedDeclarations) {
if (declaration === importedDeclaration.declaration.ref) {
if (importedDeclaration.alias !== undefined) {
Expand Down
6 changes: 3 additions & 3 deletions src/language/builtins/safe-ds-annotations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isSdsAnnotation, SdsAnnotatedObject, SdsAnnotation, SdsModule, SdsParameter } from '../generated/ast.js';
import { argumentsOrEmpty, findFirstAnnotationCallOf, hasAnnotationCallOf } from '../helpers/nodeProperties.js';
import { getArguments, findFirstAnnotationCallOf, hasAnnotationCallOf } from '../helpers/nodeProperties.js';
import { SafeDsModuleMembers } from './safe-ds-module-members.js';
import { resourceNameToUri } from '../../helpers/resources.js';
import { URI } from 'langium';
Expand Down Expand Up @@ -96,8 +96,8 @@ export class SafeDsAnnotations extends SafeDsModuleMembers<SdsAnnotation> {
parameterName: string,
): EvaluatedNode {
const annotationCall = findFirstAnnotationCallOf(node, annotation);
const argumentValue = argumentsOrEmpty(annotationCall).find(
(it) => this.nodeMapper.argumentToParameterOrUndefined(it)?.name === parameterName,
const argumentValue = getArguments(annotationCall).find(
(it) => this.nodeMapper.argumentToParameter(it)?.name === parameterName,
)?.value;
return this.partialEvaluator.evaluate(argumentValue);
}
Expand Down
4 changes: 2 additions & 2 deletions src/language/builtins/safe-ds-module-members.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SafeDsServices } from '../safe-ds-module.js';
import { isSdsModule, SdsModuleMember } from '../generated/ast.js';
import { LangiumDocuments, URI, WorkspaceCache } from 'langium';
import { moduleMembersOrEmpty } from '../helpers/nodeProperties.js';
import { getModuleMembers } from '../helpers/nodeProperties.js';

export abstract class SafeDsModuleMembers<T extends SdsModuleMember> {
private readonly langiumDocuments: LangiumDocuments;
Expand Down Expand Up @@ -31,7 +31,7 @@ export abstract class SafeDsModuleMembers<T extends SdsModuleMember> {
return undefined;
}

const firstMatchingModuleMember = moduleMembersOrEmpty(root).find((m) => m.name === name);
const firstMatchingModuleMember = getModuleMembers(root).find((m) => m.name === name);
if (!predicate(firstMatchingModuleMember)) {
/* c8 ignore next 2 */
return undefined;
Expand Down
71 changes: 33 additions & 38 deletions src/language/helpers/nodeProperties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import {
SdsTypeParameter,
SdsTypeParameterList,
} from '../generated/ast.js';
import { AstNode, getContainerOfType, stream } from 'langium';
import { AstNode, getContainerOfType, Stream, stream } from 'langium';

// -------------------------------------------------------------------------------------------------
// Checks
Expand All @@ -67,7 +67,7 @@ export const hasAnnotationCallOf = (
node: SdsAnnotatedObject | undefined,
expected: SdsAnnotation | undefined,
): boolean => {
return annotationCallsOrEmpty(node).some((it) => {
return getAnnotationCalls(node).some((it) => {
const actual = it.annotation?.ref;
return actual === expected;
});
Expand Down Expand Up @@ -121,25 +121,25 @@ export const isStatic = (node: SdsClassMember): boolean => {
// Accessors for list elements
// -------------------------------------------------------------------------------------------------

export const abstractResultsOrEmpty = (node: SdsCallable | undefined): SdsAbstractResult[] => {
export const getAbstractResults = (node: SdsCallable | undefined): SdsAbstractResult[] => {
if (!node) {
return [];
}

if (isSdsBlockLambda(node)) {
return blockLambdaResultsOrEmpty(node);
return streamBlockLambdaResults(node).toArray();
} else if (isSdsCallableType(node)) {
return resultsOrEmpty(node.resultList);
return getResults(node.resultList);
} else if (isSdsFunction(node)) {
return resultsOrEmpty(node.resultList);
return getResults(node.resultList);
} else if (isSdsSegment(node)) {
return resultsOrEmpty(node.resultList);
return getResults(node.resultList);
} /* c8 ignore start */ else {
return [];
} /* c8 ignore stop */
};

export const annotationCallsOrEmpty = (node: SdsAnnotatedObject | undefined): SdsAnnotationCall[] => {
export const getAnnotationCalls = (node: SdsAnnotatedObject | undefined): SdsAnnotationCall[] => {
if (!node) {
/* c8 ignore next 2 */
return [];
Expand All @@ -157,96 +157,91 @@ export const findFirstAnnotationCallOf = (
node: SdsAnnotatedObject | undefined,
expected: SdsAnnotation | undefined,
): SdsAnnotationCall | undefined => {
return annotationCallsOrEmpty(node).find((it) => {
return getAnnotationCalls(node).find((it) => {
const actual = it.annotation?.ref;
return actual === expected;
});
};

export const argumentsOrEmpty = (node: SdsArgumentList | SdsAbstractCall | undefined): SdsArgument[] => {
export const getArguments = (node: SdsArgumentList | SdsAbstractCall | undefined): SdsArgument[] => {
if (isSdsArgumentList(node)) {
return node.arguments;
} else {
return node?.argumentList?.arguments ?? [];
}
};

export const assigneesOrEmpty = (node: SdsAssignment | undefined): SdsAssignee[] => {
export const getAssignees = (node: SdsAssignment | undefined): SdsAssignee[] => {
return node?.assigneeList?.assignees ?? [];
};

export const blockLambdaResultsOrEmpty = (node: SdsBlockLambda | undefined): SdsBlockLambdaResult[] => {
return stream(statementsOrEmpty(node?.body))
export const streamBlockLambdaResults = (node: SdsBlockLambda | undefined): Stream<SdsBlockLambdaResult> => {
return stream(getStatements(node?.body))
.filter(isSdsAssignment)
.flatMap(assigneesOrEmpty)
.filter(isSdsBlockLambdaResult)
.toArray();
.flatMap(getAssignees)
.filter(isSdsBlockLambdaResult);
};

export const classMembersOrEmpty = (
export const getMatchingClassMembers = (
node: SdsClass | undefined,
filterFunction: (member: SdsClassMember) => boolean = () => true,
): SdsClassMember[] => {
return node?.body?.members?.filter(filterFunction) ?? [];
};

export const columnsOrEmpty = (node: SdsSchema | undefined): SdsColumn[] => {
export const getColumns = (node: SdsSchema | undefined): SdsColumn[] => {
return node?.columnList?.columns ?? [];
};

export const enumVariantsOrEmpty = (node: SdsEnum | undefined): SdsEnumVariant[] => {
export const getEnumVariants = (node: SdsEnum | undefined): SdsEnumVariant[] => {
return node?.body?.variants ?? [];
};

export const importsOrEmpty = (node: SdsModule | undefined): SdsImport[] => {
export const getImports = (node: SdsModule | undefined): SdsImport[] => {
return node?.imports ?? [];
};

export const importedDeclarationsOrEmpty = (node: SdsQualifiedImport | undefined): SdsImportedDeclaration[] => {
export const getImportedDeclarations = (node: SdsQualifiedImport | undefined): SdsImportedDeclaration[] => {
return node?.importedDeclarationList?.importedDeclarations ?? [];
};

export const literalsOrEmpty = (node: SdsLiteralType | undefined): SdsLiteral[] => {
export const getLiterals = (node: SdsLiteralType | undefined): SdsLiteral[] => {
return node?.literalList?.literals ?? [];
};

export const moduleMembersOrEmpty = (node: SdsModule | undefined): SdsModuleMember[] => {
export const getModuleMembers = (node: SdsModule | undefined): SdsModuleMember[] => {
return node?.members?.filter(isSdsModuleMember) ?? [];
};

export const packageNameOrUndefined = (node: AstNode | undefined): string | undefined => {
export const getPackageName = (node: AstNode | undefined): string | undefined => {
return getContainerOfType(node, isSdsModule)?.name;
};

export const parametersOrEmpty = (node: SdsCallable | undefined): SdsParameter[] => {
export const getParameters = (node: SdsCallable | undefined): SdsParameter[] => {
return node?.parameterList?.parameters ?? [];
};

export const parentTypesOrEmpty = (node: SdsClass | undefined): SdsType[] => {
export const getParentTypes = (node: SdsClass | undefined): SdsType[] => {
return node?.parentTypeList?.parentTypes ?? [];
};

export const placeholdersOrEmpty = (node: SdsBlock | undefined): SdsPlaceholder[] => {
return stream(statementsOrEmpty(node))
.filter(isSdsAssignment)
.flatMap(assigneesOrEmpty)
.filter(isSdsPlaceholder)
.toArray();
export const streamPlaceholders = (node: SdsBlock | undefined): Stream<SdsPlaceholder> => {
return stream(getStatements(node)).filter(isSdsAssignment).flatMap(getAssignees).filter(isSdsPlaceholder);
};

export const resultsOrEmpty = (node: SdsResultList | undefined): SdsResult[] => {
export const getResults = (node: SdsResultList | undefined): SdsResult[] => {
return node?.results ?? [];
};

export const statementsOrEmpty = (node: SdsBlock | undefined): SdsStatement[] => {
export const getStatements = (node: SdsBlock | undefined): SdsStatement[] => {
return node?.statements ?? [];
};

export const typeArgumentsOrEmpty = (node: SdsTypeArgumentList | undefined): SdsTypeArgument[] => {
export const getTypeArguments = (node: SdsTypeArgumentList | undefined): SdsTypeArgument[] => {
return node?.typeArguments ?? [];
};

export const typeParametersOrEmpty = (
export const getTypeParameters = (
node: SdsTypeParameterList | SdsNamedTypeDeclaration | undefined,
): SdsTypeParameter[] => {
if (!node) {
Expand All @@ -256,9 +251,9 @@ export const typeParametersOrEmpty = (
if (isSdsTypeParameterList(node)) {
return node.typeParameters;
} else if (isSdsClass(node)) {
return typeParametersOrEmpty(node.typeParameterList);
return getTypeParameters(node.typeParameterList);
} else if (isSdsEnumVariant(node)) {
return typeParametersOrEmpty(node.typeParameterList);
return getTypeParameters(node.typeParameterList);
} /* c8 ignore start */ else {
return [];
} /* c8 ignore stop */
Expand Down
Loading

0 comments on commit 0157377

Please sign in to comment.