ConceptPortal-public/rsconcept/frontend/src/hooks/useCheckExpression.ts

76 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-07-20 17:11:03 +03:00
import { useCallback, useState } from 'react'
2023-07-25 20:27:29 +03:00
import { type ErrorInfo } from '../components/BackendError';
import { DataCallback, postCheckExpression } from '../utils/backendAPI';
import { RSErrorType } from '../utils/enums';
import { CstType, IConstituenta, IExpressionParse, IFunctionArg, type IRSForm } from '../utils/models';
import { getCstExpressionPrefix } from '../utils/staticUI';
function checkTypeConsistency(type: CstType, typification: string, args: IFunctionArg[]): boolean {
switch (type) {
case CstType.BASE:
case CstType.CONSTANT:
case CstType.STRUCTURED:
case CstType.TERM:
return typification !== '' && args.length === 0;
case CstType.AXIOM:
case CstType.THEOREM:
return typification === '' && args.length === 0;
case CstType.FUNCTION:
return typification !== '' && args.length !== 0;
case CstType.PREDICATE:
return typification === '' && args.length !== 0;
}
}
2023-07-20 17:11:03 +03:00
2023-07-25 20:27:29 +03:00
function useCheckExpression({ schema }: { schema?: IRSForm }) {
2023-07-20 17:11:03 +03:00
const [loading, setLoading] = useState(false);
const [error, setError] = useState<ErrorInfo>(undefined);
2023-07-29 03:31:21 +03:00
const [parseData, setParseData] = useState<IExpressionParse | undefined>(undefined);
2023-07-20 17:11:03 +03:00
2023-07-25 20:27:29 +03:00
const resetParse = useCallback(() => { setParseData(undefined); }, []);
function checkExpression(expression: string, activeCst?: IConstituenta, onSuccess?: DataCallback<IExpressionParse>) {
2023-07-20 17:11:03 +03:00
setError(undefined);
postCheckExpression(String(schema!.id), {
data: { expression: expression },
2023-07-20 17:11:03 +03:00
showError: true,
2023-07-25 20:27:29 +03:00
setLoading,
onError: error => { setError(error); },
onSuccess: parse => {
if (activeCst && parse.parseResult) {
if (activeCst.cstType == CstType.BASE || activeCst.cstType == CstType.CONSTANT) {
if (expression !== getCstExpressionPrefix(activeCst)) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalNonemptyBase,
isCritical: true,
params: [],
position: 0
});
}
}
if (!checkTypeConsistency(activeCst.cstType, parse.typification, parse.args)) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalUnexpectedType,
isCritical: true,
params: [],
position: 0
});
}
}
setParseData(parse);
if (onSuccess) onSuccess(parse);
2023-07-20 17:11:03 +03:00
}
});
}
return { parseData, checkExpression, resetParse, error, setError, loading };
}
2023-07-25 20:27:29 +03:00
export default useCheckExpression;