repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
secoya/hablar.js
|
test/emitting/helpers.ts
|
<gh_stars>0
import { prettyPrint, types } from 'recast';
import Context from '../../src/emitting/context';
import { encodeIfStringFunction } from '../../src/emitting/helpers';
const b = types.builders;
describe('Emitting - Encode if string helper', () => {
it('Should emit valid function', () => {
const ctx = new Context();
const stmt = encodeIfStringFunction(ctx);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"function encodeIfString(ctx, str) {
if (!ctx.isSafeString(str)) {
return ctx.encode(\\"\\" + str);
}
return ctx.convertSafeString(str);
}"
`);
});
});
|
secoya/hablar.js
|
test/type_map.ts
|
import { default as TypeMap, CustomTypeUsage, InferredType } from '../src/type_map';
describe('TypeMap', () => {
it('Created unknown empty type info when accessing unknown variable', () => {
const map = new TypeMap();
const varName = 'myVar';
const info = map.getVariableTypeInfo(varName);
expect(info).not.toBeNull();
expect({
type: 'unknown',
usages: [],
}).toEqual(info);
});
it('Can access known variable info after being frozen', () => {
const map = new TypeMap();
const varName = 'myVar';
const info = map.getVariableTypeInfo(varName);
map.freeze();
const infoPostFreeze = map.getVariableTypeInfo(varName);
expect(info).toEqual(infoPostFreeze);
});
it('Cannot access unknown variable info after being frozen', () => {
const map = new TypeMap();
const varName = 'myVar';
map.freeze();
expect(() => map.getVariableTypeInfo(varName)).toThrowErrorMatchingInlineSnapshot(
`"Trying to get type info for unknown type: myVar"`,
);
});
it('Can add type usage and retrieve it again', () => {
const map = new TypeMap();
const varName = 'myVar';
const typeUsage: CustomTypeUsage = {
nodeType: 'custom',
};
const type: InferredType = 'string';
const resultType = map.addTypeUsage(varName, type, typeUsage);
expect(type).toEqual(resultType);
const typeInfo = map.getVariableTypeInfo(varName);
expect(typeInfo).not.toBeNull();
expect(type).toEqual(typeInfo.type);
expect(1).toEqual(typeInfo.usages.length);
expect(typeUsage).toEqual(typeInfo.usages[0]);
});
it('Cannot add variable type usage after being frozen', () => {
const map = new TypeMap();
const varName = 'myVar';
map.freeze();
expect(() =>
map.addTypeUsage(varName, 'string', {
nodeType: 'custom',
}),
).toThrowErrorMatchingInlineSnapshot(`"Cannot add type usage for myVar when type map is frozen"`);
});
// Need some more tests here to verify type merging behavior
});
|
secoya/hablar.js
|
test/parsers/constraint.ts
|
import ParseError from '../../src/errors/parse_error';
import constraintParser from '../../src/parsers/constraint';
describe('Constraint parser', () => {
describe('Numeric constraints', () => {
it('Should parse simple numeric greater than constraint', () => {
const constraint = 'n>5';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '>',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
type: 'number',
value: 5,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple numeric greater than or equals constraint', () => {
const constraint = 'n>=5';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '>=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 3,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
type: 'number',
value: 5,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple numeric less than constraint', () => {
const constraint = 'n<10';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '<',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
type: 'number',
value: 10,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple numeric less than or equals constraint', () => {
const constraint = 'n<=10';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '<=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 3,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'number',
value: 10,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple numeric equals constraint', () => {
const constraint = 'n=10';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
type: 'number',
value: 10,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple numeric not-equals constraint', () => {
const constraint = 'n!=10';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '!=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 3,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'number',
value: 10,
},
},
]).toEqual(parsed.nodes);
});
describe('Floats', () => {
it('Should parse floating point number', () => {
const constraint = 'n=10.24';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
type: 'number',
value: 10.24,
},
},
]).toEqual(parsed.nodes);
});
describe('Fail cases', () => {
it('Should reject floating point number in scientific notation', () => {
const constraint = 'n=10.24e10';
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n=10.24e10
----^
Expecting 'EOF', 'COMMA', got 'INVALID'"
`);
});
});
});
describe('Fail cases', () => {
it('Should reject numbers with space separators', () => {
const constraint = 'n=10 000';
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n=10 000
-----^
Expecting 'EOF', 'COMMA', got 'NUMBER'"
`);
});
it('Should reject numbers with space comma separators', () => {
const constraint = 'n=10,000';
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n=10,000
-----^
Expecting 'IDENTIFIER', 'IGNORE', got 'NUMBER'"
`);
});
});
});
describe('Gender values', () => {
it('Should parse simple gender femina equals constraint', () => {
const constraint = "n='F'";
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'gender',
value: 'F',
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple gender maskulin equals constraint', () => {
const constraint = "n='M'";
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'gender',
value: 'M',
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple gender neutral equals constraint', () => {
const constraint = "n='N'";
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'gender',
value: 'N',
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple gender not-equals constraint', () => {
const constraint = "n != 'M'";
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '!=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
type: 'gender',
value: 'M',
},
},
]).toEqual(parsed.nodes);
});
describe('Fail cases', () => {
it('Should should reject non gender constraint', () => {
const constraint = "n='K'";
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n='K'
--^
Expecting 'GENDER_FEMINUM', 'GENDER_MASKULINUM', 'GENDER_NEUTRUM', 'ENUM_STRING', 'NUMBER', got 'INVALID'"
`);
});
it('Should throw parse error when comparing inequalities to gender strings', () => {
expect(() => constraintParser("n > 'F'")).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n > 'F'
----^
Expecting 'NUMBER', got 'GENDER_FEMINUM'"
`);
});
});
});
describe('String enums', () => {
it('Should parse simple string-enum equals constraint', () => {
const constraint = 'n = "some-string"';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 17,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 4,
firstLine: 1,
lastColumn: 17,
lastLine: 1,
},
type: 'enum',
value: 'some-string',
},
},
]).toEqual(parsed.nodes);
});
it('Should parse simple string-enum not-equals constraint', () => {
const constraint = 'n != "some-string"';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '!=',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 18,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 18,
lastLine: 1,
},
type: 'enum',
value: 'some-string',
},
},
]).toEqual(parsed.nodes);
});
describe('Fail cases', () => {
it('Should reject invalid string-enum', () => {
const constraint = 'n != "some string"';
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n != \\"some string\\"
-----^
Expecting 'GENDER_FEMINUM', 'GENDER_MASKULINUM', 'GENDER_NEUTRUM', 'ENUM_STRING', 'NUMBER', got 'INVALID'"
`);
});
it('Should throw parse error when comparing inequalities to strings', () => {
expect(() => constraintParser('n > "Mystring"')).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n > \\"Mystring\\"
----^
Expecting 'NUMBER', got 'ENUM_STRING'"
`);
});
});
});
describe('Space sensitivity', () => {
it('Should parse simple constraint ignoring whitespace', () => {
const constraint = `n
>
5`;
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '>',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 3,
},
rhs: {
pos: {
firstColumn: 3,
firstLine: 3,
lastColumn: 4,
lastLine: 3,
},
type: 'number',
value: 5,
},
},
]).toEqual(parsed.nodes);
});
});
describe('Multiple constraints', () => {
it('Should parse multiple constraints', () => {
const constraint = 'n > 5, n < 2';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '>',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 4,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'number',
value: 5,
},
},
{
lhs: {
name: 'n',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
type: 'identifier',
},
op: '<',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 11,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
type: 'number',
value: 2,
},
},
]).toEqual(parsed.nodes);
});
it('Should parse multiple constraints with multiple variables', () => {
const constraint = 'n > 5, i < 2';
const parsed = constraintParser(constraint);
expect(constraint).toEqual(parsed.input);
expect([
{
lhs: {
name: 'n',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
type: 'identifier',
},
op: '>',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 4,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
type: 'number',
value: 5,
},
},
{
lhs: {
name: 'i',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
type: 'identifier',
},
op: '<',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
rhs: {
pos: {
firstColumn: 11,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
type: 'number',
value: 2,
},
},
]).toEqual(parsed.nodes);
});
describe('Fail cases', () => {
it('Should reject dangling comma in constraints list', () => {
const constraint = 'n > 5, i < 2,';
expect(() => constraintParser(constraint)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
n > 5, i < 2,
-------------^
Expecting 'IDENTIFIER', 'IGNORE', got 'EOF'"
`);
});
});
});
});
|
secoya/hablar.js
|
src/errors/util.ts
|
<gh_stars>0
export function showErrorLocation(input: string, errText: string, line: number, column: number): string {
const lines = input.split('\n');
const maxLineNumLength = lines.length.toString().length;
const linesWithLineNumber = lines.map((e, i) => {
const lineNumber = (i + 1).toString();
const pad = ' '.repeat(maxLineNumLength - lineNumber.length + 1);
return lineNumber + ':' + pad + e;
});
const errPad = ' '.repeat(maxLineNumLength + 2);
const errColumn = Math.min(lines[line - 1].length, column + 1);
linesWithLineNumber.splice(line, 0, `${errPad}${'-'.repeat(errColumn)}^`, `${errPad}${errText}`);
return linesWithLineNumber.join('\n');
}
|
secoya/hablar.js
|
src/analysis/constant_folding.ts
|
import {
TypedFunctionInvocationNode,
TypedNode as Node,
TypedNumberNode,
TypedStringLiteralNode,
} from '../trees/expression';
import { Pos, TypedASTRoot, TypedLiteralNode, TypedNode as TextNode } from '../trees/text';
function isConstantExpression(expr: Node) {
return expr.exprNodeType === 'number' || expr.exprNodeType === 'string_literal';
}
function getConstantValue(expr: Node): string | number {
if (expr.exprNodeType === 'number') {
return expr.value;
} else if (expr.exprNodeType === 'string_literal') {
return expr.value;
}
throw new Error('Not a constant expression value. It was: ' + expr.exprNodeType);
}
function combinePosInformation(firstPos: Pos, lastPos: Pos): Pos {
return {
firstColumn: firstPos.firstColumn,
firstLine: firstPos.firstLine,
lastColumn: lastPos.lastColumn,
lastLine: lastPos.lastLine,
};
}
function constantMultiplyOp(lhs: string | number, rhs: string | number): number {
if (typeof lhs === 'string' || typeof rhs === 'string') {
const lhsType = typeof lhs;
const rhsType = typeof rhs;
throw new Error(
'Could not constant fold expression. ' +
`Multiply operation between ${lhsType} and ${rhsType}. ` +
'Only allowed between 2 numbers.',
);
}
return lhs * rhs;
}
function constantBinaryOp(
op: 'plus' | 'minus' | 'divide' | 'multiply',
lhs: string | number,
rhs: string | number,
): string | number {
switch (op) {
case 'plus':
// Type cast here to allow the addition.
// It is intended to be allowed to mix and match number/string here.
return (lhs as string) + (rhs as string);
case 'minus': {
if (typeof lhs === 'string' || typeof rhs === 'string') {
const lhsType = typeof lhs;
const rhsType = typeof rhs;
throw new Error(
'Could not constant fold expression. ' +
`Minus operation between ${lhsType} and ${rhsType}. ` +
'Only allowed between 2 numbers.',
);
}
return lhs - rhs;
}
case 'divide': {
if (typeof lhs === 'string' || typeof rhs === 'string') {
const lhsType = typeof lhs;
const rhsType = typeof rhs;
throw new Error(
'Could not constant fold expression. ' +
`Divide operation between ${lhsType} and ${rhsType}. ` +
'Only allowed between 2 numbers.',
);
}
return lhs / rhs;
}
case 'multiply':
return constantMultiplyOp(lhs, rhs);
default:
throw new Error('Invalid binary operation type: ' + op);
}
}
/**
* Constant folds the given expression.
* The result of this should at the very least be that
* every node that has isConstant = true is turned into
* either a string_literal node or a number node.
*
* This process may throw several errors, all of these
* should have been reported during the type inference
* as type errors in the code.
*/
export function constantFoldExpression(expr: Node): Node {
const exprNodeType = expr.exprNodeType;
switch (expr.exprNodeType) {
case 'string_literal': // FALLTHROUGH
case 'number': // FALLTHROUGH
case 'variable':
return expr;
case 'function_invocation': {
const parameters: Node[] = [];
for (const param of expr.parameters) {
parameters.push(constantFoldExpression(param));
}
return {
exprNodeType: 'function_invocation',
exprType: expr.exprType,
isConstant: false,
name: expr.name,
parameters,
pos: expr.pos,
typed: true,
} as TypedFunctionInvocationNode;
}
case 'binary_op': {
const lhs = constantFoldExpression(expr.lhs);
const rhs = constantFoldExpression(expr.rhs);
if (isConstantExpression(lhs) && isConstantExpression(rhs)) {
const val = constantBinaryOp(expr.binaryOp, getConstantValue(lhs), getConstantValue(rhs));
if (typeof val === 'string') {
return {
exprNodeType: 'string_literal',
exprType: 'string',
isConstant: true,
pos: expr.pos,
typed: true,
value: val,
} as TypedStringLiteralNode;
} else {
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: expr.pos,
typed: true,
value: val,
} as TypedNumberNode;
}
} else if (
expr.binaryOp === 'multiply' &&
isConstantExpression(rhs) &&
lhs.exprNodeType === 'binary_op' &&
lhs.binaryOp === 'multiply' &&
isConstantExpression(lhs.rhs)
) {
// This is to constant fold expressions such as nonConstant * constant * constant2
const val = constantMultiplyOp(getConstantValue(lhs.rhs), getConstantValue(rhs));
return {
binaryOp: 'multiply',
exprNodeType: 'binary_op',
exprType: expr.exprType,
isConstant: false,
lhs: lhs.lhs,
pos: expr.pos,
rhs: {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: combinePosInformation(lhs.rhs.pos, rhs.pos),
typed: true,
value: val,
} as TypedNumberNode,
typed: true,
};
}
return {
binaryOp: expr.binaryOp,
exprNodeType: 'binary_op',
exprType: expr.exprType,
isConstant: false,
lhs: lhs,
pos: expr.pos,
rhs: rhs,
typed: true,
};
}
case 'unary_minus': {
const val = constantFoldExpression(expr.op);
if (isConstantExpression(val)) {
if (val.exprType !== 'number') {
throw new Error(
'Could not constant fold expression. ' +
'Unary minus with a string. It is only allowed on numbers.',
);
}
const constantValue = getConstantValue(val);
if (typeof constantValue === 'string') {
throw new Error('Expected constant value to be a number, it was a string');
}
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: expr.pos,
typed: true,
value: -constantValue,
} as TypedNumberNode;
}
return {
exprNodeType: 'unary_minus',
exprType: expr.exprType,
isConstant: false,
op: val,
pos: expr.pos,
typed: true,
};
}
default:
throw new Error(`Unknown node type: ${exprNodeType}`);
}
}
export function constantFoldExpressionList(ast: TypedASTRoot): TypedASTRoot {
const result: TextNode[] = [];
let lastConstantExpr: TypedLiteralNode | null = null;
for (const expr of ast.nodes) {
switch (expr.textNodeType) {
case 'expr': {
expr.value = constantFoldExpression(expr.value);
if (isConstantExpression(expr.value)) {
const val = '' + getConstantValue(expr.value);
if (lastConstantExpr != null) {
lastConstantExpr.value += val;
lastConstantExpr.pos = combinePosInformation(lastConstantExpr.pos, expr.pos);
} else {
const newExpr: TextNode = {
pos: expr.pos,
textNodeType: 'literal',
textType: 'string',
typed: true,
value: val,
};
result.push(newExpr);
lastConstantExpr = newExpr;
}
} else {
result.push(expr);
lastConstantExpr = null;
}
break;
}
case 'literal':
if (lastConstantExpr != null) {
lastConstantExpr.value += expr.value;
lastConstantExpr.pos = combinePosInformation(lastConstantExpr.pos, expr.pos);
} else {
result.push(expr);
lastConstantExpr = expr;
}
break;
default:
result.push(expr);
lastConstantExpr = null;
}
}
return {
input: ast.input,
nodes: result,
};
}
|
secoya/hablar.js
|
src/emitting/constraint.ts
|
<reponame>secoya/hablar.js
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
import { ASTRoot } from '../trees/constraint';
import Context from './context';
export function emitConstrainedTranslation(
ast: ASTRoot,
expr: ASTTypes.ExpressionKind,
ctx: Context,
): ASTTypes.StatementKind {
const tests: ASTTypes.ExpressionKind[] = [];
for (const t of ast.nodes) {
const tOp = t.op;
switch (t.op) {
case '!': // This test generates no code
break;
case '=':
case '!=':
case '<':
case '<=':
case '>':
case '>=':
const lhs = b.memberExpression(ctx.varsExpr, b.identifier(t.lhs.name), false);
const rhs = b.literal(t.rhs.value);
let op: '===' | '!==' | '>' | '<' | '>=' | '<=';
switch (t.op) {
case '=':
op = '===';
break;
case '!=':
op = '!==';
break;
case '>':
op = '>';
break;
case '<':
op = '<';
break;
case '<=':
op = '<=';
break;
case '>=':
op = '>=';
break;
default:
throw new Error('Unknown op type: ' + tOp);
}
tests.push(b.binaryExpression(op, lhs, rhs));
break;
default:
throw new Error('Unknown constraint op: ' + tOp);
}
}
const test = tests.reduce((acc: ASTTypes.ExpressionKind | null, exp: ASTTypes.ExpressionKind) => {
if (acc === null) {
return exp;
}
return b.logicalExpression('&&', acc, exp);
}, null);
if (test === null) {
return b.returnStatement(expr);
}
return b.ifStatement(test, b.blockStatement([b.returnStatement(expr)]));
}
|
secoya/hablar.js
|
src/errors/parse_error.ts
|
<gh_stars>0
import { showErrorLocation } from './util';
export default class ParseError extends Error {
public static getErrorMessage(hash: {
text: string;
token: string;
line: number;
loc: {
first_line: number;
first_column: number;
last_line: number;
last_column: number;
};
expected: string[];
}): string {
const expected = hash.expected.join(', ');
const got = `'${hash.token}'`;
return (
`Parse error on line ${hash.loc.last_line}:\n` +
showErrorLocation(hash.text, `Expecting: ${expected} got ${got}`, hash.line, hash.loc.last_column)
);
}
public expected: string[] | null;
public firstColumn: number | null;
public firstLine: number | null;
public lastColumn: number | null;
public lastLine: number | null;
public line: number | null;
public text: string | null;
public token: string | null;
public constructor(
message: string,
hash?: {
text: string;
token: string;
line: number;
loc: {
first_line: number;
first_column: number;
last_line: number;
last_column: number;
};
expected: string[];
},
) {
super(message);
Object.setPrototypeOf(this, ParseError.prototype);
this.message = message;
if (hash != null) {
this.text = hash.text;
this.token = hash.token;
this.line = hash.line;
this.expected = hash.expected;
this.firstColumn = hash.loc.first_column;
this.firstLine = hash.loc.first_line;
this.lastLine = hash.loc.last_line;
this.lastColumn = hash.loc.last_column;
} else {
this.text = null;
this.token = null;
this.line = null;
this.expected = null;
this.firstColumn = null;
this.firstLine = null;
this.lastLine = null;
this.lastColumn = null;
}
}
}
ParseError.prototype.name = 'ParseError'; // eslint-disable-line no-extend-native
|
secoya/hablar.js
|
src/index.ts
|
import { default as parseText, parseOnlyTextExpression } from './parsers/text';
import { default as parseExpression } from './parsers/expression';
import { default as parseConstraint } from './parsers/constraint';
import * as ExprTree from './trees/expression';
export const ExpressionTree = ExprTree;
export const parsers = {
constraint: parseConstraint,
expression: parseExpression,
onlyText: parseOnlyTextExpression,
text: parseText,
};
export { default as UnknownFunctionError } from './errors/unknown_function_error';
export { default as UnknownVariableError } from './errors/unknown_variable_error';
export { default as DeadCodeError } from './errors/dead_code_error';
export { default as ParseError } from './errors/parse_error';
export { default as TypeError } from './errors/type_error';
export { showErrorLocation } from './errors/util';
import { InferredType as InferType } from './type_map';
export { default as TypeMap } from './type_map';
export type InferredType = InferType;
import { emitConstrainedTranslation } from './emitting/constraint';
import Context from './emitting/context';
import { emitExpression } from './emitting/expression';
import { encodeIfStringFunction } from './emitting/helpers';
import { getTypeGuardStatement, getTypeGuardStatements } from './emitting/type_guards';
import { emitConstrainedTranslations, emitNodeListExpression, emitTranslation } from './emitting/translation';
export const emitting = {
Context: Context,
constrainedTranslation: emitConstrainedTranslations,
encodeIfStringFunction: encodeIfStringFunction,
helpers: {
emitConstrainedTranslationStatement: emitConstrainedTranslation,
emitExpression: emitExpression,
emitNodeListExpression: emitNodeListExpression,
emitTypeGuardStatement: getTypeGuardStatement,
emitTypeGuardStatements: getTypeGuardStatements,
},
translation: emitTranslation,
};
import {
analyzeOnlyConstraintTranslation,
analyzeOnlySimpleTranslation,
analyzeOnlyTranslation,
analyzeTranslation,
typeInferTranslation,
} from './analysis/combined';
import { constantFoldExpression, constantFoldExpressionList } from './analysis/constant_folding';
import { analyzeConstraints } from './analysis/constraints';
import {
inferConstraintTypes,
inferExpressionTypes,
inferTextTypes,
makeTypedExpressionTree,
} from './analysis/type_inference';
export const analysis = {
analyzeConstraints: analyzeConstraints,
analyzeOnlyConstraintTranslation,
analyzeOnlySimpleTranslation,
analyzeOnlyTranslation,
analyzeTranslation,
constantFoldExpression: constantFoldExpression,
constantFoldTranslation: constantFoldExpressionList,
inferConstraintTypes,
inferExpressionTypes,
inferTextTypes,
makeTypedExpressionTree,
typeInferTranslation,
};
|
secoya/hablar.js
|
src/emitting/helpers.ts
|
<reponame>secoya/hablar.js
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
import Context from './context';
export function encodeIfStringFunction(ctx: Context): ASTTypes.FunctionDeclarationKind {
const strVar = b.identifier('str');
return b.functionDeclaration(
ctx.encodeIfStringExpr,
[ctx.ctxExpr, strVar],
b.blockStatement([
b.ifStatement(
b.unaryExpression(
'!',
b.callExpression(b.memberExpression(ctx.ctxExpr, b.identifier('isSafeString'), false), [strVar]),
true,
),
b.blockStatement([
b.returnStatement(
b.callExpression(b.memberExpression(ctx.ctxExpr, b.identifier('encode'), false), [
b.binaryExpression('+', b.literal(''), strVar),
]),
),
]),
),
b.returnStatement(
b.callExpression(b.memberExpression(ctx.ctxExpr, b.identifier('convertSafeString'), false), [strVar]),
),
]),
);
}
|
secoya/hablar.js
|
test/emitting/translation.ts
|
<gh_stars>0
import { prettyPrint } from 'recast';
import Context from '../../src/emitting/context';
import { emitConstrainedTranslations, emitSimpleTranslation } from '../../src/emitting/translation';
import { Node as ConstraintNode, ValueNode } from '../../src/trees/constraint';
import { TypedNode, TypedVariableNode } from '../../src/trees/expression';
import {
TypedExprNode as TypedTextExprNode,
TypedLiteralNode as TypedTextLiteralNode,
TypedVariableNode as TypedTextVariableNode,
} from '../../src/trees/text';
import { InferredType } from '../../src/type_map';
import TypeMap from '../../src/type_map';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
function tn(str: string): TypedTextLiteralNode {
return {
pos: makeEmptyPos(),
textNodeType: 'literal',
textType: 'string',
typed: true,
value: str,
};
}
function vn(name: string, type: InferredType): TypedTextVariableNode {
return {
pos: makeEmptyPos(),
textNodeType: 'variable',
textType: type,
typed: true,
value: name,
};
}
function en(exp: TypedNode): TypedTextExprNode {
return {
pos: makeEmptyPos(),
textNodeType: 'expr',
textType: exp.exprType,
typed: true,
value: exp,
};
}
function v(type: InferredType, name: string): TypedVariableNode {
return {
exprNodeType: 'variable',
exprType: type,
isConstant: false,
name: name,
pos: makeEmptyPos(),
typed: true,
};
}
function cignore(varName: string): ConstraintNode {
return {
op: '!',
operand: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
pos: makeEmptyPos(),
};
}
function ceq(op: '=' | '!=', varName: string, value: string | number): ConstraintNode {
let rhs: ValueNode;
if (typeof value === 'number') {
rhs = {
pos: makeEmptyPos(),
type: 'number',
value: value,
};
} else {
rhs = {
pos: makeEmptyPos(),
type: 'enum',
value: value,
};
}
return {
lhs: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
op: op,
pos: makeEmptyPos(),
rhs: rhs,
};
}
describe('Emitting - translation', () => {
it('Should emit simple string on basic translation', () => {
const nodes = [tn('Some text')];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: 'Some text',
nodes: nodes,
},
ctx,
map,
),
);
expect('"Some text"').toEqual(res.code);
});
it('Should emit function with guard on variable node - excluding scratch variable', () => {
const nodes = [vn('myVar', 'string')];
const map = new TypeMap();
map.addTypeUsage('myVar', 'string', {
nodeType: 'custom',
});
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: '$myVar',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
if (typeof(vars.myVar) !== \\"string\\" && !ctx.isSafeString(vars.myVar)) {
throw new Error(\\"Variable myVar must be of type string\\");
}
return encodeIfString(ctx, vars.myVar);
}"
`);
});
it('Should emit function with guard on variable node - including scratch variable', () => {
const nodes = [vn('myVar', 'number-or-string')];
const map = new TypeMap();
map.addTypeUsage('myVar', 'number-or-string', {
nodeType: 'custom',
});
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: '$myVar',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
var _;
if (!((_ = typeof(vars.myVar)) === \\"string\\" || _ === \\"number\\" || ctx.isSafeString(vars.myVar))) {
throw new Error(\\"Variable myVar must be of type number-or-string\\");
}
return encodeIfString(ctx, vars.myVar);
}"
`);
});
it('Should ensure result is a string', () => {
const nodes = [vn('myVar', 'number')];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: '$myVar',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"\\" + vars.myVar);
}"
`);
});
it('Should remove unneeded empty string literal with leading text', () => {
const nodes = [tn('Some number: '), vn('myVar', 'number')];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: 'Some number: $myVar',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"Some number: \\" + vars.myVar);
}"
`);
});
it('Should remove unneeded empty string literal with leading text - when using expression', () => {
const nodes = [tn('Some number: '), en(v('number', 'myVar'))];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: 'Some number: $number',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"Some number: \\" + vars.myVar);
}"
`);
});
it('Should add empty string literal to force string concat on two numbers', () => {
const nodes = [en(v('number', 'myOtherVar')), en(v('number', 'myVar'))];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(
emitSimpleTranslation(
{
input: '{{$myOtherVar}}{{$myVar}}',
nodes: nodes,
},
ctx,
map,
),
);
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"\\" + vars.myOtherVar + vars.myVar);
}"
`);
});
describe('Constrained translations', () => {
it('Should emit simple return on ignore constraint', () => {
const translations = [
{
constraints: {
input: '!someVar',
nodes: [cignore('someVar')],
},
translation: {
input: 'Some translation',
nodes: [tn('Some translation')],
},
},
];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(emitConstrainedTranslations(translations, ctx, map));
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"Some translation\\");
}"
`);
});
it('Should emit if statement with throw statement when not guarenteed to return', () => {
const translations = [
{
constraints: {
input: 'someVar=5',
nodes: [ceq('=', 'someVar', 5)],
},
translation: {
input: 'Some translation',
nodes: [tn('Some translation')],
},
},
];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(emitConstrainedTranslations(translations, ctx, map));
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
if (vars.someVar === 5) {
return ctx.encode(\\"Some translation\\");
}
throw new Error(\\"No translation matched the parameters\\");
}"
`);
});
it(
'Should emit constrained translations in order - ' +
'and not emit throw statement if unconstrained translation exists',
() => {
const translations = [
{
constraints: {
input: 'someVar=5',
nodes: [ceq('=', 'someVar', 5)],
},
translation: {
input: 'Some translation',
nodes: [tn('Some translation')],
},
},
{
constraints: {
input: 'someVar=10',
nodes: [ceq('=', 'someVar', 10)],
},
translation: {
input: 'Some other translation',
nodes: [tn('Some other translation')],
},
},
{
constraints: {
input: '!someVar',
nodes: [cignore('someVar')],
},
translation: {
input: 'Some default translation',
nodes: [tn('Some default translation')],
},
},
];
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(emitConstrainedTranslations(translations, ctx, map));
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
if (vars.someVar === 5) {
return ctx.encode(\\"Some translation\\");
}
if (vars.someVar === 10) {
return ctx.encode(\\"Some other translation\\");
}
return ctx.encode(\\"Some default translation\\");
}"
`);
},
);
it('Should not double escape variable in expression', () => {
const tr = {
input: 'Some translation {{$myVar}}',
nodes: [tn('Some translation '), en(v('string', 'myVar'))],
};
const map = new TypeMap();
const ctx = new Context();
const res = prettyPrint(emitSimpleTranslation(tr, ctx, map));
expect(res.code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
return ctx.encode(\\"Some translation \\") + encodeIfString(ctx, vars.myVar);
}"
`);
});
});
});
|
secoya/hablar.js
|
test/emitting/type_guards.ts
|
<gh_stars>0
import { prettyPrint, types } from 'recast';
import Context from '../../src/emitting/context';
import { getTypeGuardStatement, getTypeGuardStatements } from '../../src/emitting/type_guards';
import TypeMap from '../../src/type_map';
const b = types.builders;
describe('Emitting - Type guards', () => {
describe('Parameters', () => {
it('Should emit nothing with empty type map', () => {
const map = new TypeMap();
map.freeze();
const ctx = new Context();
const stmts = getTypeGuardStatements(map, ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(false);
expect(0).toEqual(stmts.length);
});
it('Should emit simple existence test for unknown type', () => {
const ctx = new Context();
const stmt = getTypeGuardStatement('myVar', 'unknown', ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(false);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"if (!vars.hasOwnProperty(\\"myVar\\")) {
throw new Error(\\"Variable myVar must be of type unknown\\");
}"
`);
});
it('Should emit simple typeof test for string', () => {
const ctx = new Context();
const stmt = getTypeGuardStatement('myVar', 'string', ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(false);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"if (typeof(vars.myVar) !== \\"string\\" && !ctx.isSafeString(vars.myVar)) {
throw new Error(\\"Variable myVar must be of type string\\");
}"
`);
});
it('Should emit simple typeof test for number', () => {
const ctx = new Context();
const stmt = getTypeGuardStatement('myVar', 'number', ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(false);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"if (typeof(vars.myVar) !== \\"number\\") {
throw new Error(\\"Variable myVar must be of type number\\");
}"
`);
});
it('Should emit combined typeof test for number-or-string', () => {
const ctx = new Context();
const stmt = getTypeGuardStatement('myVar', 'number-or-string', ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(true);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"if (!((_ = typeof(vars.myVar)) === \\"string\\" || _ === \\"number\\" || ctx.isSafeString(vars.myVar))) {
throw new Error(\\"Variable myVar must be of type number-or-string\\");
}"
`);
});
it('Should emit combined value equality tests for gender', () => {
const ctx = new Context();
const stmt = getTypeGuardStatement('myVar', 'gender', ctx);
expect(ctx.usesTypeGuardScratchVariable).toBe(false);
expect(prettyPrint(stmt).code).toMatchInlineSnapshot(`
"if (!(vars.myVar === \\"M\\" || vars.myVar === \\"F\\" || vars.myVar === \\"N\\")) {
throw new Error(\\"Variable myVar must be of type gender\\");
}"
`);
});
});
describe('Functions', () => {
it('Should emit nothing on empty function array', () => {
const ctx = new Context();
const map = new TypeMap();
map.freeze();
const res = getTypeGuardStatements(map, ctx);
expect(0).toEqual(res.length);
});
it('Should emit single if statement on single function', () => {
const ctx = new Context();
const map = new TypeMap();
map.addFunction('myFn');
map.freeze();
const res = getTypeGuardStatements(map, ctx);
expect(1).toEqual(res.length);
expect(prettyPrint(res[0]).code).toMatchInlineSnapshot(`
"if (typeof(fns.myFn) !== \\"function\\") {
throw new Error(\\"Translation requires function myFn to exist\\");
}"
`);
});
it('Should emit two if statements on two functions', () => {
const ctx = new Context();
const map = new TypeMap();
map.addFunction('myFn');
map.addFunction('myOtherFn');
map.freeze();
const res = getTypeGuardStatements(map, ctx);
expect(prettyPrint(b.blockStatement(res)).code).toMatchInlineSnapshot(`
"{
if (typeof(fns.myFn) !== \\"function\\") {
throw new Error(\\"Translation requires function myFn to exist\\");
}
if (typeof(fns.myOtherFn) !== \\"function\\") {
throw new Error(\\"Translation requires function myOtherFn to exist\\");
}
}"
`);
});
});
});
|
secoya/hablar.js
|
test/emitting/expression.ts
|
import { prettyPrint } from 'recast';
import Context from '../../src/emitting/context';
import { emitExpression } from '../../src/emitting/expression';
import {
TypedBinaryOpNode,
TypedFunctionInvocationNode,
TypedNode,
TypedNumberNode,
TypedStringLiteralNode,
TypedVariableNode,
} from '../../src/trees/expression';
import { InferredType } from '../../src/type_map';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
function s(str: string): TypedStringLiteralNode {
return {
exprNodeType: 'string_literal',
exprType: 'string',
isConstant: true,
pos: makeEmptyPos(),
typed: true,
value: str,
};
}
function n(num: number): TypedNumberNode {
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: makeEmptyPos(),
typed: true,
value: num,
};
}
function b(
type: InferredType,
op: 'plus' | 'minus' | 'multiply' | 'divide',
lhs: TypedNode,
rhs: TypedNode,
): TypedBinaryOpNode {
return {
binaryOp: op,
exprNodeType: 'binary_op',
exprType: type,
isConstant: lhs.isConstant && rhs.isConstant,
lhs: lhs,
pos: makeEmptyPos(),
rhs: rhs,
typed: true,
};
}
function v(type: InferredType, name: string): TypedVariableNode {
return {
exprNodeType: 'variable',
exprType: type,
isConstant: false,
name: name,
pos: makeEmptyPos(),
typed: true,
};
}
function f(name: string, args: TypedNode[]): TypedFunctionInvocationNode {
return {
exprNodeType: 'function_invocation',
exprType: 'string',
isConstant: false,
name: name,
parameters: args,
pos: makeEmptyPos(),
typed: true,
};
}
describe('Emitting - Expressions', () => {
it('Should emit simple string literal', () => {
const node = s('string');
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('"string"').toEqual(res.code);
});
it('Should emit simple number literal', () => {
const node = n(10);
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('10').toEqual(res.code);
});
it('Should emit simple binary op', () => {
const node = b('number', 'plus', n(5), n(10));
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('5 + 10').toEqual(res.code);
});
it('Should group nested binary ops properly', () => {
const node = b('number', 'plus', n(5), b('number', 'multiply', n(10), n(5)));
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('5 + 10 * 5').toEqual(res.code);
});
it('Should group nested binary ops properly - and add needed parens', () => {
const node = b('number', 'multiply', n(5), b('number', 'plus', n(10), n(5)));
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('5 * (10 + 5)').toEqual(res.code);
});
it('Should emit simple variable expression correct', () => {
const node = v('string', 'myVarName');
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('vars.myVarName').toEqual(res.code);
});
// Note: This test verifies that no weird thing is attempted
// to resolve invalid JS identifiers. We disallow them in the grammar
// so it should be *ok*
it('Should emit simple variable expressions with weird names as incorrect javascript', () => {
const node = v('string', 'myVar-Name');
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('vars.myVar-Name').toEqual(res.code);
});
it('Should inline binary plus when variable string involved', () => {
const node = b('number-or-string', 'plus', n(5), v('number-or-string', 'myVar'));
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect(res.code).toMatchInlineSnapshot(
`"ctx.makeSafeString(encodeIfString(ctx, 5) + encodeIfString(ctx, vars.myVar))"`,
);
});
it('Should not emit helper function call on plus when expr type is number', () => {
const node = b('number', 'plus', n(5), v('number', 'myVar'));
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('5 + vars.myVar').toEqual(res.code);
});
it('Should emit method call on function call', () => {
const node = f('myFn', []);
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('fns.myFn(ctx)').toEqual(res.code);
});
it('Should emit method call on function call - single parameter', () => {
const node = f('myFn', [n(10)]);
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('fns.myFn(ctx, 10)').toEqual(res.code);
});
it('Should emit method call on function call - two parameters', () => {
const node = f('myFn', [n(10), s('stuff')]);
const ctx = new Context();
const res = prettyPrint(emitExpression(node, ctx));
expect('fns.myFn(ctx, 10, "stuff")').toEqual(res.code);
});
});
|
secoya/hablar.js
|
src/errors/unknown_function_error.ts
|
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { TypedFunctionInvocationNode } from '../trees/expression';
import { TypedASTRoot } from '../trees/text';
import { showErrorLocation } from './util';
export default class UnknownFunctionError extends Error {
public functionName: string;
public allowedFunctions: string[];
public line: number;
public column: number;
public input: string;
public constraints: string | null;
public constructor(
node: TypedFunctionInvocationNode,
allowedFunctions: string[],
ast: TypedASTRoot,
constraints: ConstraintAST | null = null,
) {
const functionName = node.name;
const errMessage =
'' +
`Unknown function ${functionName} used on line ${node.pos.firstLine}:\n` +
showErrorLocation(
ast.input,
`Function ${functionName} is not known to this translation. ` +
`Known functions are: ${allowedFunctions.join(', ')}`,
node.pos.firstLine,
node.pos.firstColumn - 1,
);
super(errMessage);
Object.setPrototypeOf(this, UnknownFunctionError.prototype);
this.message = errMessage;
this.functionName = functionName;
this.allowedFunctions = allowedFunctions;
this.line = node.pos.firstLine;
this.column = node.pos.firstColumn;
this.input = ast.input;
this.constraints = constraints != null ? constraints.input : null;
}
}
UnknownFunctionError.prototype.name = 'UnknownFunctionError';
|
secoya/hablar.js
|
src/emitting/expression.ts
|
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
import { TypedNode } from '../trees/expression';
import Context from './context';
function getBinaryOp(op: 'plus' | 'minus' | 'divide' | 'multiply'): '+' | '-' | '*' | '/' {
switch (op) {
case 'plus':
return '+';
case 'minus':
return '-';
case 'divide':
return '/';
case 'multiply':
return '*';
default:
throw new Error('Invalid binary operator: ' + op);
}
}
export function emitExpression(node: TypedNode, ctx: Context): ASTTypes.ExpressionKind {
const exprNodeType = node.exprNodeType;
switch (node.exprNodeType) {
case 'string_literal': // FALLTHROUGH
case 'number':
return b.literal(node.value);
case 'variable':
return b.memberExpression(ctx.varsExpr, b.identifier(node.name), false);
case 'binary_op': {
const lhs = emitExpression(node.lhs, ctx);
const rhs = emitExpression(node.rhs, ctx);
const op = getBinaryOp(node.binaryOp);
if (node.isConstant || node.exprType === 'number') {
return b.binaryExpression(op, lhs, rhs);
} else {
return b.callExpression(b.memberExpression(ctx.ctxExpr, b.identifier('makeSafeString'), false), [
b.binaryExpression(
'+',
b.callExpression(ctx.encodeIfStringExpr, [ctx.ctxExpr, lhs]),
b.callExpression(ctx.encodeIfStringExpr, [ctx.ctxExpr, rhs]),
),
]);
}
}
case 'unary_minus': {
const operand = emitExpression(node.op, ctx);
return b.unaryExpression('-', operand, true);
}
case 'function_invocation': {
const callee = b.memberExpression(ctx.functionsExpr, b.identifier(node.name), false);
const args = node.parameters.map(n => emitExpression(n, ctx));
return b.callExpression(callee, [ctx.ctxExpr, ...args]);
}
default:
throw new Error('Unknown node type: ' + exprNodeType);
}
}
|
secoya/hablar.js
|
test/analysis/constraints.ts
|
import { analyzeConstraints } from '../../src/analysis/constraints';
import DeadCodeError from '../../src/errors/dead_code_error';
import { ASTRoot as ConstraintAST, Node as ConstraintNode } from '../../src/trees/constraint';
import { TypedASTRoot as TypedTextASTRoot, TypedNode as TypedTextNode } from '../../src/trees/text';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
function returnNode(v: string = 'var'): ConstraintNode {
return {
op: '!',
operand: {
name: v,
pos: makeEmptyPos(),
type: 'identifier',
},
pos: makeEmptyPos(),
};
}
function tn(str: string): TypedTextNode {
return {
pos: makeEmptyPos(),
textNodeType: 'literal',
textType: 'string',
typed: true,
value: str,
};
}
function noReturnNode(v: string = 'var'): ConstraintNode {
return {
lhs: {
name: v,
pos: makeEmptyPos(),
type: 'identifier',
},
op: '=',
pos: makeEmptyPos(),
rhs: {
pos: makeEmptyPos(),
type: 'number',
value: 5,
},
};
}
function makeTranslation(
constraints: ConstraintNode[] | ConstraintNode,
text: string,
): {
constraints: ConstraintAST;
translation: TypedTextASTRoot;
} {
return {
constraints: {
input: '',
nodes: Array.isArray(constraints) ? constraints : [constraints],
},
translation: {
input: text,
nodes: [tn(text)],
},
};
}
// We many more tests here. But this is simple stuff to verify
// that it works.
describe('Constraints analyzer', () => {
describe('Dead code', () => {
it('It detects a simple dead code', () => {
const ret = makeTranslation(returnNode(), 'Return node');
const noRet = makeTranslation(noReturnNode(), 'No return node');
expect(() => analyzeConstraints([ret, noRet])).toThrowErrorMatchingInlineSnapshot(`"Dead code"`);
});
it('It does not detects a simple non dead code', () => {
const ret = makeTranslation(returnNode(), 'Return node');
const noRet = makeTranslation(noReturnNode(), 'No return node');
expect(() => analyzeConstraints([noRet, ret])).not.toThrow();
});
});
});
|
secoya/hablar.js
|
src/parsers/expression.ts
|
import ParseError from '../errors/parse_error';
import { Node, TypedNode } from '../trees/expression';
import getParser from './get_parser';
const expressionParser = getParser('expression');
export function walkNode(node: Node, callback: (node: Node) => void): void {
callback(node);
switch (node.exprNodeType) {
case 'function_invocation':
for (const param of node.parameters) {
walkNode(param, callback);
}
break;
case 'unary_minus':
walkNode(node.op, callback);
break;
case 'binary_op':
walkNode(node.lhs, callback);
walkNode(node.rhs, callback);
break;
default: // Not needed, no child nodes of other types
}
}
export function walkTypedNode(node: TypedNode, callback: (node: TypedNode) => void): void {
callback(node);
switch (node.exprNodeType) {
case 'function_invocation':
for (const param of node.parameters) {
walkTypedNode(param, callback);
}
break;
case 'unary_minus':
walkTypedNode(node.op, callback);
break;
case 'binary_op':
walkTypedNode(node.lhs, callback);
walkTypedNode(node.rhs, callback);
break;
default: // Not needed, no child nodes of other types
}
}
function substituteStringLiterals(node: Node, originalText: string): Node {
walkNode(
node,
(expr): void => {
if (expr.exprNodeType === 'string_literal') {
try {
const v = JSON.parse(expr.value);
expr.value = v;
} catch (e) {
throw new ParseError(`Error parsing '${originalText}'. Invalid string literal ${expr.value}`);
}
}
},
);
return node;
}
export default function parse(input: string): Node {
const parsed: Node = expressionParser.parse(input);
return substituteStringLiterals(parsed, input);
}
|
secoya/hablar.js
|
test/complete.ts
|
<filename>test/complete.ts
import { prettyPrint } from 'recast';
import { analyzeTranslation, analyzeTranslations, ConstraintTranslation } from '../src/analysis/combined';
import Context from '../src/emitting/context';
import { emitTranslation } from '../src/emitting/translation';
import constraintParser from '../src/parsers/constraint';
import fullTextParser from '../src/parsers/text';
import TypeMap from '../src/type_map';
describe('Full tests', () => {
it('Should work with simple text translations', () => {
const text = 'Some translation';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
const ctx = new Context();
const analyzed = analyzeTranslation(ast, typeMap);
const jsAst = emitTranslation(analyzed, ctx, typeMap);
expect('"Some translation"').toEqual(prettyPrint(jsAst).code);
});
it('Should work with multiple simple text translations', () => {
const text1 = 'Some translation';
const ast1 = fullTextParser(text1);
const text2 = 'Some other translation';
const ast2 = fullTextParser(text2);
const typeMap = new TypeMap();
const ctx = new Context();
const analyzed = analyzeTranslations([ast1, ast2], typeMap);
const jsAst1 = emitTranslation(analyzed[0], ctx, typeMap);
const jsAst2 = emitTranslation(analyzed[1], ctx, typeMap);
expect('"Some translation"').toEqual(prettyPrint(jsAst1).code);
expect('"Some other translation"').toEqual(prettyPrint(jsAst2).code);
});
it('Should work with complex translations', () => {
const translation: ConstraintTranslation = [
{
constraints: constraintParser('n = 0'),
translation: fullTextParser('You have nothing in your basket'),
},
{
constraints: constraintParser('n = 1'),
translation: fullTextParser('You have one item in your basket'),
},
{
constraints: constraintParser('n > 1'),
translation: fullTextParser('You have $n items in your basket'),
},
];
const typeMap = new TypeMap();
const ctx = new Context();
const analyzed = analyzeTranslation(translation, typeMap);
const jsAst = emitTranslation(analyzed, ctx, typeMap);
expect(prettyPrint(jsAst).code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
if (typeof(vars.n) !== \\"number\\") {
throw new Error(\\"Variable n must be of type number\\");
}
if (vars.n === 0) {
return ctx.encode(\\"You have nothing in your basket\\");
}
if (vars.n === 1) {
return ctx.encode(\\"You have one item in your basket\\");
}
if (vars.n > 1) {
return ctx.encode(\\"You have \\" + vars.n + \\" items in your basket\\");
}
throw new Error(\\"No translation matched the parameters\\");
}"
`);
});
it('Should constant fold simple translation', () => {
const translation = fullTextParser("Here's one million: {{1*1000*1000}}");
const typeMap = new TypeMap();
const ctx = new Context();
const analyzed = analyzeTranslation(translation, typeMap);
const jsAst = emitTranslation(analyzed, ctx, typeMap);
expect(prettyPrint(jsAst).code).toMatchInlineSnapshot(`"\\"Here's one million: 1000000\\""`);
});
it('Should constant fold complex translations', () => {
const translation: ConstraintTranslation = [
{
constraints: constraintParser('n = 0'),
translation: fullTextParser('You have nothing in your basket. One million: {{1*1000*1000}}'),
},
{
constraints: constraintParser('n = 1'),
translation: fullTextParser('You have one item in your basket. One million: {{1*1000*1000}}'),
},
{
constraints: constraintParser('n > 1'),
translation: fullTextParser('You have $n items in your basket. One million: {{1*1000*1000}}'),
},
];
const typeMap = new TypeMap();
const ctx = new Context();
const analyzed = analyzeTranslation(translation, typeMap);
const jsAst = emitTranslation(analyzed, ctx, typeMap);
expect(prettyPrint(jsAst).code).toMatchInlineSnapshot(`
"function(vars, fns, ctx) {
if (typeof(vars.n) !== \\"number\\") {
throw new Error(\\"Variable n must be of type number\\");
}
if (vars.n === 0) {
return ctx.encode(\\"You have nothing in your basket. One million: 1000000\\");
}
if (vars.n === 1) {
return ctx.encode(\\"You have one item in your basket. One million: 1000000\\");
}
if (vars.n > 1) {
return ctx.encode(\\"You have \\" + vars.n + \\" items in your basket. One million: 1000000\\");
}
throw new Error(\\"No translation matched the parameters\\");
}"
`);
});
it('Should generate pretty type errors', () => {
const text = 'Calculation: {{$myVar*5}}.';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
typeMap.addTypeUsage('myVar', 'string', { nodeType: 'custom' });
expect(() => analyzeTranslation(ast, typeMap)).toThrowErrorMatchingInlineSnapshot(`
"Type error at line 1:
1: Calculation: {{$myVar*5}}.
----------------^
Variable $myVar was expected to have type: string, found: number."
`);
});
it('Should generate pretty unknown variable error - in expression', () => {
const text = 'Calculation: {{$myVar}}.';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
expect(() => analyzeTranslation(ast, typeMap, ['someOtherVar'])).toThrowErrorMatchingInlineSnapshot(`
"Unknown variable $myVar used on line 1:
1: Calculation: {{$myVar}}.
----------------^
Variable $myVar is not known to this translation. Known variables are: $someOtherVar"
`);
});
it('Should generate pretty unknown variable error - outside of expression', () => {
const text = 'Calculation: $myVar.';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
expect(() => analyzeTranslation(ast, typeMap, ['someOtherVar'])).toThrowErrorMatchingInlineSnapshot(`
"Unknown variable $myVar used on line 1:
1: Calculation: $myVar.
--------------^
Variable $myVar is not known to this translation. Known variables are: $someOtherVar"
`);
});
it('Should allow known variable to be used', () => {
const text = 'Calculation: $myVar';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
expect(() => analyzeTranslation(ast, typeMap, ['myVar'], ['someFunction'])).not.toThrow();
});
it('Should generate pretty unknown function error', () => {
const text = 'Calculation: {{fn()}}';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
expect(() => analyzeTranslation(ast, typeMap, null, ['otherFn'])).toThrowErrorMatchingInlineSnapshot(`
"Unknown function fn used on line 1:
1: Calculation: {{fn()}}
---------------^
Function fn is not known to this translation. Known functions are: otherFn"
`);
});
it('Should be able to type infer function arguments', () => {
const text = 'Bold text: {{bold($myVar)}}';
const ast = fullTextParser(text);
const typeMap = new TypeMap();
analyzeTranslation(ast, typeMap, null, ['bold']);
expect(typeMap.getVariableType('myVar')).toMatchInlineSnapshot(`"unknown"`);
const newTypeMap = new TypeMap();
newTypeMap.addTypedFunction('bold', ['string']);
analyzeTranslation(ast, newTypeMap, null, ['bold']);
expect(newTypeMap.getVariableType('myVar')).toMatchInlineSnapshot(`"string"`);
});
});
|
secoya/hablar.js
|
src/type_map.ts
|
import { ASTRoot, Node as TextNode } from './trees/text';
import { ASTRoot as ConstraintAST, Node as ConstraintNode } from './trees/constraint';
import { Node as ExprNode } from './trees/expression';
import TypeError from './errors/type_error';
export type InferredType = 'enum' | 'error' | 'gender' | 'number-or-string' | 'number' | 'string' | 'unknown';
export type UsageLocation = {
text: ASTRoot;
constraints?: ConstraintAST;
};
export type ConstraintTypeUsage = {
nodeType: 'constraint';
node: ConstraintNode;
location: UsageLocation;
type: 'unknown' | 'gender' | 'enum' | 'number';
};
export type ExpressionTypeUsage = {
nodeType: 'expression';
node: ExprNode;
location: UsageLocation;
type: 'unknown' | 'number-or-string' | 'number' | 'string';
};
export type TextTypeUsage = {
nodeType: 'text';
node: TextNode;
location: UsageLocation;
type: 'number-or-string';
};
// Used for third party integration. It could be that the person
// integrating with this has some sort of metadata
// on the actual translation - that specifies the types
// of all variables.
export type CustomTypeUsage = {
nodeType: 'custom';
};
export type TypeUsage = ConstraintTypeUsage | ExpressionTypeUsage | TextTypeUsage | CustomTypeUsage;
export type TypeInfo = {
usages: TypeUsage[];
type: InferredType;
};
export type UnknownFunctionParameterTypes = {
kind: 'unknown';
};
export type KnownFunctionParameterTypes = {
kind: 'known';
types: InferredType[];
};
export type FunctionParameterTypes = UnknownFunctionParameterTypes | KnownFunctionParameterTypes;
export default class TypeMap {
private static mergeTypeInfo(existingType: InferredType, newType: InferredType): InferredType {
if (newType === 'unknown') {
return existingType;
}
switch (existingType) {
case 'unknown':
return newType;
case 'error':
return 'error';
case 'number-or-string':
switch (newType) {
case 'number-or-string': // FALLTHROUGH
case 'number': // FALLTHROUGH
case 'string': // FALLTHROUGH
case 'enum': // / FALLTHROUGH
case 'gender':
return newType;
default:
return 'error';
}
case 'string':
switch (newType) {
case 'number-or-string': // FALLTHROUGH
case 'string':
return 'string';
case 'enum':
return 'enum';
case 'gender':
return 'gender';
default:
return 'error';
}
case 'enum':
switch (newType) {
case 'number-or-string': // FALLTHROUGH
case 'string': // FALLTHROUGH
case 'enum':
return 'enum';
default:
return 'error';
}
case 'gender':
switch (newType) {
case 'number-or-string': // FALLTHROUGH
case 'string': // FALLTHROUGH
case 'gender':
return 'gender';
default:
return 'error';
}
case 'number':
switch (newType) {
case 'number': // FALLTHROUGH
case 'number-or-string': // FALLTHROUGH
return 'number';
default:
return 'error';
}
default:
throw new Error('Unknown existing type: ' + existingType);
}
}
private map: Map<string, TypeInfo>;
private functions: Map<string, FunctionParameterTypes>;
private frozen: boolean;
private hasError: boolean;
private typeErrors: TypeError[];
public constructor() {
this.map = new Map<string, TypeInfo>();
this.functions = new Map<string, FunctionParameterTypes>();
this.frozen = false;
this.hasError = false;
this.typeErrors = [];
}
private _throwIfFrozen(errMsg: string): void {
if (this.frozen) {
throw new Error(errMsg);
}
}
public get size(): number {
return this.map.size;
}
public getVariableTypeInfo(variable: string): TypeInfo {
let usage = this.map.get(variable);
if (usage != null) {
return usage;
}
this._throwIfFrozen('Trying to get type info for unknown type: ' + variable);
usage = {
type: 'unknown',
usages: [],
};
this.map.set(variable, usage);
return usage;
}
public getVariableType(variable: string): InferredType {
return this.getVariableTypeInfo(variable).type;
}
public hasInfoForType(variable: string): boolean {
return this.map.has(variable);
}
public variables(): Array<string> {
return Array.from(this.map.keys());
}
public freeze(): void {
this.frozen = true;
}
public isFrozen(): boolean {
return this.frozen;
}
public hasTypeErrors(): boolean {
return this.hasError;
}
public throwTypeErrors(): never {
if (!this.hasError) {
throw new Error('No type errors found!');
}
// Perhaps figure out a way to throw all of them in some combined error
throw this.typeErrors[0];
}
public addTypeUsage(variable: string, type: InferredType, usage: TypeUsage): InferredType {
this._throwIfFrozen(`Cannot add type usage for ${variable} when type map is frozen`);
const info = this.getVariableTypeInfo(variable);
const existingType = info.type;
info.type = TypeMap.mergeTypeInfo(info.type, type);
info.usages.push(usage);
if (info.type === 'error') {
const loc = (usage as TextTypeUsage).location;
this.hasError = true;
this.typeErrors.push(
new TypeError(
existingType,
type,
this,
(usage as TextTypeUsage | ConstraintTypeUsage | ExpressionTypeUsage).node || null,
loc != null ? loc.text.input : '',
loc.constraints != null ? loc.constraints.input : null,
variable,
),
);
}
return info.type;
}
public addFunction(functionName: string): void {
this._throwIfFrozen(`Cannot add function ${functionName} after map is frozen`);
if (this.functions.has(functionName)) {
return;
}
this.functions.set(functionName, { kind: 'unknown' });
}
public addTypedFunction(functionName: string, parameterTypes: InferredType[]): void {
this._throwIfFrozen(`Cannot add function ${functionName} after map is frozen`);
if (this.functions.has(functionName)) {
throw new Error('Function has already been added with known parameter types');
}
this.functions.set(functionName, { kind: 'known', types: parameterTypes });
}
public functionNames(): string[] {
return Array.from(this.functions.keys());
}
public functionParameterTypes(functionName: string): FunctionParameterTypes {
const types = this.functions.get(functionName);
if (types == null) {
return {
kind: 'unknown',
};
}
return types;
}
}
|
secoya/hablar.js
|
src/parsers/get_parser.ts
|
<gh_stars>0
import ParseError from '../errors/parse_error';
function monkeyPatchParserWithProperParseError(parser: any): any {
const parse = parser.parse;
parser.parse = (input: string): any => {
try {
return parse.call(parser, input);
} catch (e) {
throw new ParseError(e.message, e.hash);
}
};
return parser;
}
const parsers = {
constraint: require('./grammars/constraint.js'),
expression: require('./grammars/expression.js'),
text: require('./grammars/text.js'),
};
function getParser(
name: 'expression' | 'text' | 'constraint',
): {
parse(input: string): any;
} {
const parser = parsers[name];
return monkeyPatchParserWithProperParseError(parser);
}
export default getParser;
|
secoya/hablar.js
|
src/emitting/type_guards.ts
|
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
import { default as TypeMap, InferredType } from '../type_map';
import Context from './context';
function getTypeTestStatement(ctx: Context, varName: string, type: InferredType): ASTTypes.StatementKind {
const test = getNegativeTypeTest(ctx, varName, type);
// Perhaps improve error message in the future
const error = b.newExpression(b.identifier('Error'), [
b.literal('Variable ' + varName + ' must be of type ' + type),
]);
return b.ifStatement(test, b.blockStatement([b.throwStatement(error)]));
}
function getNegativeTypeTest(ctx: Context, varName: string, type: InferredType): ASTTypes.ExpressionKind {
switch (type) {
case 'unknown': {
const hasOwnProperty = b.callExpression(
b.memberExpression(ctx.varsExpr, b.identifier('hasOwnProperty'), false),
[b.literal(varName)],
);
return b.unaryExpression('!', hasOwnProperty, true);
}
case 'string': {
const paramExpr = b.memberExpression(ctx.varsExpr, b.identifier(varName), false);
const typeOf = b.callExpression(b.identifier('typeof'), [paramExpr]);
const isString = b.binaryExpression('!==', typeOf, b.literal('string'));
const isSafeString = b.callExpression(
b.memberExpression(ctx.ctxExpr, b.identifier('isSafeString'), false),
[paramExpr],
);
const isNotSafeString = b.unaryExpression('!', isSafeString, true);
return b.logicalExpression('&&', isString, isNotSafeString);
}
case 'enum': // FALLTHROUGH
case 'number': {
const paramExpr = b.memberExpression(ctx.varsExpr, b.identifier(varName), false);
const testType = type === 'enum' ? 'string' : type;
const typeOf = b.callExpression(b.identifier('typeof'), [paramExpr]);
return b.binaryExpression('!==', typeOf, b.literal(testType));
}
case 'number-or-string': {
// I am not sure if simple OR binary tests are better
// than array + indexOf tests.
// Either way, my instincts tells me that simpler is better.
// So here goes the OR binary tests
const paramExpr = b.memberExpression(ctx.varsExpr, b.identifier(varName), false);
ctx.usesTypeGuardScratchVariable = true;
const typeOf = b.assignmentExpression(
'=',
ctx.typeGuardScratchVarExpr,
b.callExpression(b.identifier('typeof'), [paramExpr]),
);
const isString = b.binaryExpression('===', typeOf, b.literal('string'));
const isNumber = b.binaryExpression('===', ctx.typeGuardScratchVarExpr, b.literal('number'));
const numberOrString = b.logicalExpression('||', isString, isNumber);
const isSafeString = b.callExpression(
b.memberExpression(ctx.ctxExpr, b.identifier('isSafeString'), false),
[paramExpr],
);
const isGoodValue = b.logicalExpression('||', numberOrString, isSafeString);
return b.unaryExpression('!', isGoodValue, true);
}
case 'gender': {
const paramExpr = b.memberExpression(ctx.varsExpr, b.identifier(varName), false);
const isMaskulinum = b.binaryExpression('===', paramExpr, b.literal('M'));
const isFeminum = b.binaryExpression('===', paramExpr, b.literal('F'));
const isNeutrum = b.binaryExpression('===', paramExpr, b.literal('N'));
const isGender = b.logicalExpression('||', b.logicalExpression('||', isMaskulinum, isFeminum), isNeutrum);
return b.unaryExpression('!', isGender, true);
}
case 'error':
throw new Error('Cannot generate type guards for an error type!');
default:
throw new Error('Unknown type: ' + type);
}
}
export function getTypeGuardStatement(varName: string, type: InferredType, ctx: Context): ASTTypes.StatementKind {
return getTypeTestStatement(ctx, varName, type);
}
export function getTypeGuardStatements(typeMap: TypeMap, ctx: Context): ASTTypes.StatementKind[] {
const result: ASTTypes.StatementKind[] = [];
for (const varName of typeMap.variables()) {
const type = typeMap.getVariableType(varName);
result.push(getTypeTestStatement(ctx, varName, type));
}
for (const functionName of typeMap.functionNames()) {
const fn = b.memberExpression(ctx.functionsExpr, b.identifier(functionName), false);
const test = b.binaryExpression('!==', b.callExpression(b.identifier('typeof'), [fn]), b.literal('function'));
const throwError = b.throwStatement(
b.newExpression(b.identifier('Error'), [
b.literal('Translation requires function ' + functionName + ' to exist'),
]),
);
result.push(b.ifStatement(test, b.blockStatement([throwError])));
}
return result;
}
|
secoya/hablar.js
|
test/parsers/expression.ts
|
import ParseError from '../../src/errors/parse_error';
import expressionParser from '../../src/parsers/expression';
describe('Expression parser', () => {
describe('Literals', () => {
describe('Numbers', () => {
it('Should parse integer number', () => {
const exp = '5';
const res = expressionParser(exp);
expect({
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
}).toEqual(res);
});
it('Should parse floating point number', () => {
const exp = '5.24';
const res = expressionParser(exp);
expect({
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 5.24,
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject floating point number in scientific notation', () => {
const exp = '5.24e10';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
5.24e10
-^
Expecting 'EOF', 'PLUS', 'MINUS', 'DIVIDE', 'MULTIPLY', 'CLOSE_PAREN', 'COMMA', got 'INVALID'"
`);
});
});
});
describe('Strings', () => {
it('Should parse simple string', () => {
const exp = '"Some string"';
const res = expressionParser(exp);
expect({
exprNodeType: 'string_literal',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 13,
lastLine: 1,
},
value: 'Some string',
}).toEqual(res);
});
it('Should parse simple string with double-quote escape sequence', () => {
const exp = '"Some \\"string\\""';
const res = expressionParser(exp);
expect({
exprNodeType: 'string_literal',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 17,
lastLine: 1,
},
value: 'Some "string"',
}).toEqual(res);
});
it('Should parse simple string with other special characters escape sequence', () => {
const exp = '"Some \\n\\t\\f\\rstring"';
const res = expressionParser(exp);
expect({
exprNodeType: 'string_literal',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 21,
lastLine: 1,
},
value: 'Some \n\t\f\rstring',
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject simple string with invalid escape sequence', () => {
const exp = '"Some \\."';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(
`"Error parsing '\\"Some \\\\.\\"'. Invalid string literal \\"Some \\\\.\\""`,
);
});
});
});
});
describe('Variables', () => {
it('Should parse a simple variable', () => {
const exp = '$hello';
const res = expressionParser(exp);
expect({
exprNodeType: 'variable',
name: 'hello',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse a simple variable with mixed casing', () => {
const exp = '$helloWorld';
const res = expressionParser(exp);
expect({
exprNodeType: 'variable',
name: 'helloWorld',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 11,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse a simple variable with underscores', () => {
const exp = '$hello_world';
const res = expressionParser(exp);
expect({
exprNodeType: 'variable',
name: 'hello_world',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should fail on invalid identifier', () => {
const exp = '$hello-not-valid-variable-name';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
$hello-not-valid-variable-name
----------^
Expecting 'OPEN_PAREN', got 'MINUS'"
`);
});
});
});
describe('Unary minus', () => {
it('Should parse negative integer number', () => {
const exp = '-5';
const res = expressionParser(exp);
expect({
exprNodeType: 'unary_minus',
op: {
exprNodeType: 'number',
pos: {
firstColumn: 1,
firstLine: 1,
lastColumn: 2,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 2,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse negative variable', () => {
const exp = '-$n';
const res = expressionParser(exp);
expect({
exprNodeType: 'unary_minus',
op: {
exprNodeType: 'variable',
name: 'n',
pos: {
firstColumn: 1,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse negative paren expresison', () => {
const exp = '-(5)';
const res = expressionParser(exp);
expect({
exprNodeType: 'unary_minus',
op: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject unary minus without operand', () => {
const exp = '-';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
-
-^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'EOF'"
`);
});
});
});
describe('Functions', () => {
it('Should parse a simple function invocation with no parameters', () => {
const exp = 'hello()';
const res = expressionParser(exp);
expect({
exprNodeType: 'function_invocation',
name: 'hello',
parameters: [],
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse a simple function invocation with a numeric parameter', () => {
const exp = 'hello(10)';
const res = expressionParser(exp);
expect({
exprNodeType: 'function_invocation',
name: 'hello',
parameters: [
{
exprNodeType: 'number',
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
value: 10,
},
],
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse a simple function invocation with multiple parameters', () => {
const exp = 'hello(10, $world, "some string")';
const res = expressionParser(exp);
expect({
exprNodeType: 'function_invocation',
name: 'hello',
parameters: [
{
exprNodeType: 'number',
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
value: 10,
},
{
exprNodeType: 'variable',
name: 'world',
pos: {
firstColumn: 10,
firstLine: 1,
lastColumn: 16,
lastLine: 1,
},
},
{
exprNodeType: 'string_literal',
pos: {
firstColumn: 18,
firstLine: 1,
lastColumn: 31,
lastLine: 1,
},
value: 'some string',
},
],
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 32,
lastLine: 1,
},
}).toEqual(res);
});
it('Should parse a simple function invocation with a paren parameter', () => {
const exp = 'hello((10))';
const res = expressionParser(exp);
expect({
exprNodeType: 'function_invocation',
name: 'hello',
parameters: [
{
exprNodeType: 'number',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
},
value: 10,
},
],
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 11,
lastLine: 1,
},
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject invocations with trailing comma', () => {
const exp = 'hello(10, 20,)';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
hello(10, 20,)
-------------^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'CLOSE_PAREN'"
`);
});
it('Should reject invocations with trailing comma - with leading whitespace', () => {
const exp = ' hello($hans, )';
let thrown = false;
try {
expressionParser(exp);
} catch (e) {
expect(e).toBeInstanceOf(ParseError);
const parseE = e as ParseError;
const expectedMessage =
// tslint:disable:indent
`Parse error on line 1:
hello($hans, )
--------------^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'CLOSE_PAREN'`;
// tslint:enable:indent
expect(expectedMessage).toEqual(e.message);
expect(' hello($hans, '.length - 1).toEqual(parseE.lastColumn);
thrown = true;
}
expect(thrown).toBe(true);
});
it('Should reject invocations without comma separator between arguments', () => {
const exp = 'hello(10 20)';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
hello(10 20)
---------^
Expecting 'EOF', 'PLUS', 'MINUS', 'DIVIDE', 'MULTIPLY', 'CLOSE_PAREN', 'COMMA', got 'NUMBER'"
`);
});
it('Should reject invocations without parens', () => {
const exp = 'hello 10, 20';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
hello 10, 20
------^
Expecting 'OPEN_PAREN', got 'NUMBER'"
`);
});
it('Should reject invocations without closing paren', () => {
const exp = 'hello(10, 20';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
hello(10, 20
------------^
Expecting 'PLUS', 'MINUS', 'DIVIDE', 'MULTIPLY', 'CLOSE_PAREN', 'COMMA', got 'EOF'"
`);
});
});
});
describe('Arithmetic', () => {
it('Should parse simple numeric plus arithmetic', () => {
const exp = '5+10';
const res = expressionParser(exp);
expect({
binaryOp: 'plus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
}).toEqual(res);
});
it('Should parse simple numeric minus arithmetic', () => {
const exp = '5-10';
const res = expressionParser(exp);
expect({
binaryOp: 'minus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
}).toEqual(res);
});
it('Should parse simple numeric divide arithmetic', () => {
const exp = '5/10';
const res = expressionParser(exp);
expect({
binaryOp: 'divide',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
}).toEqual(res);
});
it('Should parse simple numeric multiply arithmetic', () => {
const exp = '5*10';
const res = expressionParser(exp);
expect({
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
}).toEqual(res);
});
describe('Operator precedence', () => {
it('Pure multiply behaves as expected', () => {
const exp = '5*10*20';
const res = expressionParser(exp);
expect({
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
}).toEqual(res);
});
it('Pure divide behaves as expected', () => {
const exp = '5/10/20';
const res = expressionParser(exp);
expect({
binaryOp: 'divide',
exprNodeType: 'binary_op',
lhs: {
binaryOp: 'divide',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
}).toEqual(res);
});
it('Parens groups expressions', () => {
const exp = '5*(10*20)';
const res = expressionParser(exp);
expect({
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
rhs: {
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 3,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 3,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 8,
lastLine: 1,
},
value: 20,
},
},
}).toEqual(res);
});
it('Plus operator precedence mixed with multiply', () => {
const exp = '5+10*20';
const res = expressionParser(exp);
expect({
binaryOp: 'plus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
},
}).toEqual(res);
});
it('Plus operator precedence mixed with divide', () => {
const exp = '5+10/20';
const res = expressionParser(exp);
expect({
binaryOp: 'plus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
binaryOp: 'divide',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
},
}).toEqual(res);
});
it('Minus operator precedence mixed with multiply', () => {
const exp = '5-10*20';
const res = expressionParser(exp);
expect({
binaryOp: 'minus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
},
}).toEqual(res);
});
it('Minus operator precedence mixed with divide', () => {
const exp = '5-10/20';
const res = expressionParser(exp);
expect({
binaryOp: 'minus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 1,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
binaryOp: 'divide',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 4,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
rhs: {
exprNodeType: 'number',
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 7,
lastLine: 1,
},
value: 20,
},
},
}).toEqual(res);
});
it('Unary minus operator precedence', () => {
const exp = '-5 * -(10 - -20)';
const res = expressionParser(exp);
expect({
binaryOp: 'multiply',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'unary_minus',
op: {
exprNodeType: 'number',
pos: {
firstColumn: 1,
firstLine: 1,
lastColumn: 2,
lastLine: 1,
},
value: 5,
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 2,
lastLine: 1,
},
},
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 16,
lastLine: 1,
},
rhs: {
exprNodeType: 'unary_minus',
op: {
binaryOp: 'minus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'number',
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
},
value: 10,
},
pos: {
firstColumn: 7,
firstLine: 1,
lastColumn: 15,
lastLine: 1,
},
rhs: {
exprNodeType: 'unary_minus',
op: {
exprNodeType: 'number',
pos: {
firstColumn: 13,
firstLine: 1,
lastColumn: 15,
lastLine: 1,
},
value: 20,
},
pos: {
firstColumn: 12,
firstLine: 1,
lastColumn: 15,
lastLine: 1,
},
},
},
pos: {
firstColumn: 5,
firstLine: 1,
lastColumn: 16,
lastLine: 1,
},
},
}).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject unary plus', () => {
const exp = '+10';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
+10
^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'PLUS'"
`);
});
it('Should reject unmatched parens', () => {
const exp = '(20+10';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
(20+10
------^
Expecting 'PLUS', 'MINUS', 'DIVIDE', 'MULTIPLY', 'CLOSE_PAREN', got 'EOF'"
`);
});
it('Should reject trailing binary plus op without rhs operand', () => {
const exp = '20+';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
20+
---^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'EOF'"
`);
});
it('Should reject trailing binary minus op without rhs operand', () => {
const exp = '20-';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
20-
---^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'EOF'"
`);
});
it('Should reject trailing binary multiply op without rhs operand', () => {
const exp = '20*';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
20*
---^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'EOF'"
`);
});
it('Should reject trailing binary divide op without rhs operand', () => {
const exp = '20/';
expect(() => expressionParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
20/
---^
Expecting 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER', got 'EOF'"
`);
});
});
});
});
});
|
secoya/hablar.js
|
src/emitting/context.ts
|
<reponame>secoya/hablar.js<gh_stars>0
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
export default class Context {
public ctxExpr: ASTTypes.IdentifierKind = b.identifier('ctx');
public encodeIfStringExpr: ASTTypes.IdentifierKind = b.identifier('encodeIfString');
public functionsExpr: ASTTypes.IdentifierKind = b.identifier('fns');
public plusOpExpr: ASTTypes.IdentifierKind = b.identifier('plusOp');
public typeGuardScratchVarExpr: ASTTypes.IdentifierKind = b.identifier('_');
public usesTypeGuardScratchVariable: boolean = false;
public varsExpr: ASTTypes.IdentifierKind = b.identifier('vars');
}
|
secoya/hablar.js
|
src/emitting/translation.ts
|
import { builders as b } from 'ast-types';
import * as ASTTypes from 'ast-types/gen/kinds';
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { TypedNode as ExprNode } from '../trees/expression';
import { TypedASTRoot } from '../trees/text';
import TypeMap from '../type_map';
import { emitConstrainedTranslation } from './constraint';
import Context from './context';
import { emitExpression } from './expression';
import { getTypeGuardStatements } from './type_guards';
function encodeIfString(exp: ASTTypes.ExpressionKind, ctx: Context): ASTTypes.ExpressionKind {
return b.callExpression(ctx.encodeIfStringExpr, [ctx.ctxExpr, exp]);
}
function encodeString(exp: ASTTypes.ExpressionKind, ctx: Context): ASTTypes.ExpressionKind {
return b.callExpression(b.memberExpression(ctx.ctxExpr, b.identifier('encode'), false), [exp]);
}
export function emitNodeListExpression(ast: TypedASTRoot, ctx: Context): ASTTypes.ExpressionKind {
const exprs: Array<{
type: 'string' | 'number';
exp: ASTTypes.ExpressionKind;
isConstant: boolean;
}> = [];
for (const node of ast.nodes) {
const textNodeType = node.textNodeType;
switch (node.textNodeType) {
case 'literal':
exprs.push({
exp: b.literal(node.value),
isConstant: true,
type: 'string',
});
break;
case 'variable': {
const varExp = b.memberExpression(ctx.varsExpr, b.identifier(node.value), false);
exprs.push({
exp: varExp,
isConstant: false,
type: node.textType === 'number' ? 'number' : 'string',
});
break;
}
case 'expr': {
const exp = (node.value as any) as ExprNode;
const varExp = emitExpression(exp, ctx);
exprs.push({
exp: varExp,
isConstant: false,
type: exp.exprType === 'number' ? 'number' : 'string',
});
break;
}
default:
throw new Error('Unknown node type: ' + textNodeType);
}
}
const encodeGroup = (group: ASTTypes.ExpressionKind): ASTTypes.ExpressionKind => {
return encodeString(group, ctx);
};
const encodedExprGroups: ASTTypes.ExpressionKind[] = [];
let currentGroup: ASTTypes.ExpressionKind | null = null;
for (const expr of exprs) {
if (currentGroup == null) {
if (expr.type === 'number') {
currentGroup = b.binaryExpression('+', b.literal(''), expr.exp);
} else if (expr.isConstant) {
currentGroup = expr.exp;
} else {
encodedExprGroups.push(encodeIfString(expr.exp, ctx));
}
continue;
}
if (expr.isConstant || expr.type === 'number') {
currentGroup = b.binaryExpression('+', currentGroup, expr.exp);
} else {
encodedExprGroups.push(encodeGroup(currentGroup));
currentGroup = null;
encodedExprGroups.push(encodeIfString(expr.exp, ctx));
}
}
if (currentGroup != null) {
encodedExprGroups.push(encodeGroup(currentGroup));
}
const init = b.literal('');
return encodedExprGroups.reduce((acc, e) => {
if (acc === init) {
return e;
}
return b.binaryExpression('+', acc, e);
}, init);
}
function getTypeGuards(ctx: Context, typeMap: TypeMap): ASTTypes.StatementKind[] {
const usesTypeGuardScratchVariable = ctx.usesTypeGuardScratchVariable;
ctx.usesTypeGuardScratchVariable = false;
const statements: ASTTypes.StatementKind[] = getTypeGuardStatements(typeMap, ctx);
if (ctx.usesTypeGuardScratchVariable) {
statements.splice(
0,
0,
b.variableDeclaration('var', [b.variableDeclarator(ctx.typeGuardScratchVarExpr, null)]),
);
}
ctx.usesTypeGuardScratchVariable = usesTypeGuardScratchVariable;
return statements;
}
export function emitConstrainedTranslations(
translations: ConstraintTranslation,
ctx: Context,
typeMap: TypeMap,
): ASTTypes.ExpressionKind {
if (translations.length === 0) {
throw new Error('No constraints found');
}
const statements: ASTTypes.StatementKind[] = getTypeGuards(ctx, typeMap);
let unconditionallyReturned = false;
for (const translation of translations) {
const expr = emitNodeListExpression(translation.translation, ctx);
const stmt = emitConstrainedTranslation(translation.constraints, expr, ctx);
if (stmt.type === 'ReturnStatement') {
unconditionallyReturned = true;
}
statements.push(stmt);
}
if (!unconditionallyReturned) {
statements.push(
b.throwStatement(
b.newExpression(b.identifier('Error'), [b.literal('No translation matched the parameters')]),
),
);
}
return b.functionExpression(null, [ctx.varsExpr, ctx.functionsExpr, ctx.ctxExpr], b.blockStatement(statements));
}
export function emitSimpleTranslation(ast: TypedASTRoot, ctx: Context, typeMap: TypeMap): ASTTypes.ExpressionKind {
const first = ast.nodes[0];
// Constant translations are just emitted as their Constant
// translation
if (ast.nodes.length === 1 && first.textNodeType === 'literal') {
return b.literal(first.value);
}
const statements = getTypeGuards(ctx, typeMap);
// Emit the body of the translation
const expr = emitNodeListExpression(ast, ctx);
statements.push(b.returnStatement(expr));
return b.functionExpression(null, [ctx.varsExpr, ctx.functionsExpr, ctx.ctxExpr], b.blockStatement(statements));
}
export type SimpleTranslation = TypedASTRoot;
// $FlowFixMe: Flow cannot deal with this union
export type ConstraintTranslation = Array<{
constraints: ConstraintAST;
translation: TypedASTRoot;
}>;
export type Translation = SimpleTranslation | ConstraintTranslation;
export function emitTranslation(translation: Translation, ctx: Context, typeMap: TypeMap): ASTTypes.ExpressionKind {
const simple = translation as SimpleTranslation;
if (typeof simple.input === 'string') {
return emitSimpleTranslation(simple, ctx, typeMap);
} else {
return emitConstrainedTranslations(translation as ConstraintTranslation, ctx, typeMap);
}
}
|
secoya/hablar.js
|
src/parsers/text.ts
|
<filename>src/parsers/text.ts
import ParseError from '../errors/parse_error';
import expressionParser, { walkNode } from './expression';
import getParser from './get_parser';
const textParser = getParser('text');
import { Node as NodeExpression } from '../trees/expression';
import { ExprNode, LiteralNode, Node, Pos, VariableNode } from '../trees/text';
export type InitialExprNode = {
textNodeType: 'expr';
value: string;
pos: Pos;
valuePos: Pos;
};
export type InitialNode = LiteralNode | VariableNode | InitialExprNode;
export function parseOnlyTextExpression(input: string): InitialNode[] {
return textParser.parse(input);
}
function repositionPosition(enclosingPosition: Pos, pos: Pos): Pos {
// We subtract one from line indices as they are one indexed.
// If we're still on line one - we add the firstColumn to both first and last column
return {
firstColumn: pos.firstLine !== 1 ? pos.firstColumn : enclosingPosition.firstColumn + pos.firstColumn,
firstLine: enclosingPosition.firstLine + pos.firstLine - 1,
lastColumn: pos.lastLine !== 1 ? pos.lastColumn : enclosingPosition.firstColumn + pos.lastColumn,
lastLine: enclosingPosition.firstLine + pos.lastLine - 1,
};
}
function fixupPositionInformation(node: NodeExpression, exprNode: InitialExprNode): NodeExpression {
walkNode(node, n => {
n.pos = repositionPosition(exprNode.valuePos, n.pos);
});
return node;
}
export type TextParserResult = {
input: string;
nodes: Node[];
};
export default function parse(input: string): TextParserResult {
let parsed: InitialNode[] = [];
try {
parsed = parseOnlyTextExpression(input);
} catch (e) {
if (!(e instanceof ParseError)) {
throw e;
}
const parseE = e as ParseError;
if (
parseE.firstLine == null ||
parseE.lastLine == null ||
parseE.lastColumn == null ||
parseE.firstColumn == null
) {
throw e;
}
const hash = {
expected: parseE.expected || [`'NONE'`],
line: parseE.lastLine,
loc: {
first_column: parseE.firstColumn,
first_line: parseE.lastLine,
last_column: parseE.lastColumn,
last_line: parseE.lastLine,
},
text: input,
token: parseE.token || 'NONE',
};
const message = ParseError.getErrorMessage(hash);
throw new ParseError(message, hash);
}
const result: Node[] = [];
for (const fragment of parsed) {
if (fragment.textNodeType === 'expr') {
try {
const newNode: ExprNode = {
pos: fragment.pos,
textNodeType: 'expr',
value: fixupPositionInformation(expressionParser(fragment.value), fragment),
};
result.push(newNode);
} catch (e) {
if (!(e instanceof ParseError)) {
throw e;
}
const parseErr = e as ParseError;
if (
parseErr.firstLine == null ||
parseErr.lastLine == null ||
parseErr.lastColumn == null ||
parseErr.firstColumn == null
) {
throw e;
}
const token = parseErr.token === `EOF` ? `CLOSE_EXPR` : parseErr.token || `NONE`;
const errPos = repositionPosition(fragment.valuePos, {
firstColumn: parseErr.firstColumn,
firstLine: parseErr.firstLine,
lastColumn: parseErr.lastColumn,
lastLine: parseErr.lastLine,
});
if (token === 'CLOSE_EXPR') {
errPos.firstColumn = fragment.valuePos.lastColumn;
errPos.firstLine = fragment.valuePos.lastLine;
errPos.lastColumn = fragment.valuePos.lastColumn - 1; // This should be +2 but we add that in the end
errPos.lastLine = fragment.valuePos.lastLine;
}
const expected = (parseErr.expected || ['NONE']).map(e => {
if (e === 'EOF') {
return `'CLOSE_EXPR'`;
}
return e;
});
const hash = {
expected: expected,
line: errPos.lastLine,
loc: {
first_column: errPos.firstColumn,
first_line: errPos.firstLine,
last_column: errPos.lastColumn,
last_line: errPos.lastLine,
},
text: input,
token: token,
};
const message = ParseError.getErrorMessage(hash);
if (token === 'CLOSE_EXPR') {
hash.loc.last_column += 3;
}
throw new ParseError(message, hash);
}
} else if (fragment.textNodeType === 'variable') {
result.push(fragment);
} else if (fragment.textNodeType === 'literal') {
result.push(fragment);
}
}
return {
input: input,
nodes: result,
};
}
|
secoya/hablar.js
|
test/parsers/text.ts
|
<gh_stars>0
import ParseError from '../../src/errors/parse_error';
import fullTextParser, { parseOnlyTextExpression as textParser } from '../../src/parsers/text';
describe('Text parser', () => {
describe('Simple text literals', () => {
it('Should parse simple one word literal', () => {
const exp = 'Hello';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
textNodeType: 'literal',
value: 'Hello',
},
]).toEqual(res);
});
it('Should parse simple two word literal', () => {
const exp = 'Hello world';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 11,
lastLine: 1,
},
textNodeType: 'literal',
value: 'Hello world',
},
]).toEqual(res);
});
});
describe('Variables', () => {
it('Should parse simple variable', () => {
const exp = '$hello';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'variable',
value: 'hello',
},
]).toEqual(res);
});
it('Should parse variable and text', () => {
const exp = '$hello world';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'variable',
value: 'hello',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
textNodeType: 'literal',
value: ' world',
},
]).toEqual(res);
});
it('Should parse text and variable', () => {
const exp = 'hello $world';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'literal',
value: 'hello ',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
textNodeType: 'variable',
value: 'world',
},
]).toEqual(res);
});
it('Should parse text, variable and text ', () => {
const exp = 'hello $world!';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'literal',
value: 'hello ',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 12,
lastLine: 1,
},
textNodeType: 'variable',
value: 'world',
},
{
pos: {
firstColumn: 12,
firstLine: 1,
lastColumn: 13,
lastLine: 1,
},
textNodeType: 'literal',
value: '!',
},
]).toEqual(res);
});
});
describe('Expressions', () => {
it('Should parse simple expression', () => {
const exp = '{{5}}';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 5,
lastLine: 1,
},
textNodeType: 'expr',
value: '5',
valuePos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
},
},
]).toEqual(res);
});
it('Should parse complicated expression', () => {
const exp = '{{5*10+"hello"*myFunction($world, "lol", 50.4)}}';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 48,
lastLine: 1,
},
textNodeType: 'expr',
value: '5*10+"hello"*myFunction($world, "lol", 50.4)',
valuePos: {
firstColumn: 2,
firstLine: 1,
lastColumn: 46,
lastLine: 1,
},
},
]).toEqual(res);
});
it('Should allow mixing of text and expressions', () => {
const exp = 'Hello {{"world"}}';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'literal',
value: 'Hello ',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 17,
lastLine: 1,
},
textNodeType: 'expr',
value: '"world"',
valuePos: {
firstColumn: 8,
firstLine: 1,
lastColumn: 15,
lastLine: 1,
},
},
]).toEqual(res);
});
it('Should extract relevant position information', () => {
const exp = 'Hello {{ world($hans, ) }}';
const res = textParser(exp);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'literal',
value: 'Hello ',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 26,
lastLine: 1,
},
textNodeType: 'expr',
value: ' world($hans, ) ',
valuePos: {
firstColumn: 8,
firstLine: 1,
lastColumn: 24,
lastLine: 1,
},
},
]).toEqual(res);
});
describe('Fail cases', () => {
it('Should reject empty expression', () => {
const exp = '{{}}';
expect(() => textParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
{{}}
--^
Expecting 'CHAR', 'CHARS', 'STRING_LITERAL', 'VARIABLE', got 'CLOSE_EXPR'"
`);
});
it('Should reject unclosed braces', () => {
const exp = '{{5';
expect(() => textParser(exp)).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
{{5
---^
Expecting 'CHAR', 'CHARS', 'STRING_LITERAL', 'VARIABLE', 'CLOSE_EXPR', got 'EOF'"
`);
});
});
});
describe('Text and expression parser', () => {
it('Should parse and extract relevant information', () => {
// This also heavily tests the line and column information preservation
// between the text and expression parsing.
// tslint:disable:indent
const exp = `Hello {{ "world"+
$test
}} {{
func()
}}`;
// tslint:enable:indent
const res = fullTextParser(exp);
expect(exp).toEqual(res.input);
expect([
{
pos: {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
},
textNodeType: 'literal',
value: 'Hello ',
},
{
pos: {
firstColumn: 6,
firstLine: 1,
lastColumn: 2,
lastLine: 4,
},
textNodeType: 'expr',
value: {
binaryOp: 'plus',
exprNodeType: 'binary_op',
lhs: {
exprNodeType: 'string_literal',
pos: {
firstColumn: 9,
firstLine: 1,
lastColumn: 16,
lastLine: 1,
},
value: 'world',
},
pos: {
firstColumn: 9,
firstLine: 1,
lastColumn: 5,
lastLine: 2,
},
rhs: {
exprNodeType: 'variable',
name: 'test',
pos: {
firstColumn: 0,
firstLine: 2,
lastColumn: 5,
lastLine: 2,
},
},
},
},
{
pos: {
firstColumn: 2,
firstLine: 4,
lastColumn: 3,
lastLine: 4,
},
textNodeType: 'literal',
value: ' ',
},
{
pos: {
firstColumn: 3,
firstLine: 4,
lastColumn: 2,
lastLine: 6,
},
textNodeType: 'expr',
value: {
exprNodeType: 'function_invocation',
name: 'func',
parameters: [],
pos: {
firstColumn: 4,
firstLine: 5,
lastColumn: 10,
lastLine: 5,
},
},
},
]).toEqual(res.nodes);
});
it("Should give good error message on mismatched curly's", () => {
expect(() => fullTextParser('Hello {{ world')).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
1: Hello {{ world
--------------^
Expecting: 'CHAR', 'CHARS', 'STRING_LITERAL', 'VARIABLE', 'CLOSE_EXPR' got 'EOF'"
`);
});
it('Should support long input and pad line numbers in error message accordingly', () => {
expect(() =>
fullTextParser(
`Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
{{`,
),
).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 11:
1: Line 1
2: Line 2
3: Line 3
4: Line 4
5: Line 5
6: Line 6
7: Line 7
8: Line 8
9: Line 9
10: Line 10
11: {{
--^
Expecting: 'CHAR', 'CHARS', 'STRING_LITERAL', 'VARIABLE' got 'EOF'"
`);
});
it('Should give good error message with error inside expression parser at EOF', () => {
expect(() => fullTextParser('Hello {{ world( }}')).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
1: Hello {{ world( }}
----------------^
Expecting: 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'CLOSE_PAREN', 'VARIABLE', 'IDENTIFIER' got 'CLOSE_EXPR'"
`);
});
it('Should give good error message with error inside expression parser - in expr', () => {
expect(() => fullTextParser('Hello {{ world($hans, ) }}')).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 1:
1: Hello {{ world($hans, ) }}
----------------------^
Expecting: 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'VARIABLE', 'IDENTIFIER' got 'CLOSE_PAREN'"
`);
});
it('Should give good error message when input spans multiple lines with error inside expression parser', () => {
expect(() =>
fullTextParser(
`Hello there
{{ world(
}}
Some other line`,
),
).toThrowErrorMatchingInlineSnapshot(`
"Parse error on line 4:
1: Hello there
2: {{ world(
3:
4: }}
^
Expecting: 'MINUS', 'NUMBER', 'STRING_LITERAL', 'OPEN_PAREN', 'CLOSE_PAREN', 'VARIABLE', 'IDENTIFIER' got 'CLOSE_EXPR'
5: Some other line"
`);
});
});
});
|
secoya/hablar.js
|
test/analysis/constant_folding.ts
|
<filename>test/analysis/constant_folding.ts<gh_stars>0
import { constantFoldExpression, constantFoldExpressionList } from '../../src/analysis/constant_folding';
import {
Pos,
TypedBinaryOpNode,
TypedFunctionInvocationNode,
TypedNode,
TypedNumberNode,
TypedStringLiteralNode,
TypedUnaryMinusNode,
TypedVariableNode,
} from '../../src/trees/expression';
import {
TypedExprNode as TypedTextExprNode,
TypedLiteralNode as TypedTextLiteralNode,
TypedVariableNode as TypedTextVariableNode,
} from '../../src/trees/text';
import { InferredType } from '../../src/type_map';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
function s(str: string, pos?: Pos): TypedStringLiteralNode {
return {
exprNodeType: 'string_literal',
exprType: 'string',
isConstant: true,
pos: pos == null ? makeEmptyPos() : pos,
typed: true,
value: str,
};
}
function n(num: number, pos?: Pos): TypedNumberNode {
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: pos == null ? makeEmptyPos() : pos,
typed: true,
value: num,
};
}
function um(node: TypedNode, exprType: 'number' | 'string' = 'number', pos?: Pos): TypedUnaryMinusNode {
return {
exprNodeType: 'unary_minus',
exprType: exprType,
isConstant: node.isConstant,
op: node,
pos: pos == null ? makeEmptyPos() : pos,
typed: true,
};
}
function b(
type: InferredType,
op: 'plus' | 'minus' | 'multiply' | 'divide',
lhs: TypedNode,
rhs: TypedNode,
pos?: Pos,
): TypedBinaryOpNode {
return {
binaryOp: op,
exprNodeType: 'binary_op',
exprType: type,
isConstant: lhs.isConstant && rhs.isConstant,
lhs: lhs,
pos: pos == null ? makeEmptyPos() : pos,
rhs: rhs,
typed: true,
};
}
function v(type: InferredType, name: string, pos?: Pos): TypedVariableNode {
return {
exprNodeType: 'variable',
exprType: type,
isConstant: false,
name: name,
pos: pos == null ? makeEmptyPos() : pos,
typed: true,
};
}
function f(name: string, args: TypedNode[], pos?: Pos): TypedFunctionInvocationNode {
return {
exprNodeType: 'function_invocation',
exprType: 'string',
isConstant: false,
name: name,
parameters: args,
pos: pos == null ? makeEmptyPos() : pos,
typed: true,
};
}
function tn(str: string): TypedTextLiteralNode {
return {
pos: makeEmptyPos(),
textNodeType: 'literal',
textType: 'string',
typed: true,
value: str,
};
}
function vn(name: string, type: InferredType): TypedTextVariableNode {
return {
pos: makeEmptyPos(),
textNodeType: 'variable',
textType: type,
typed: true,
value: name,
};
}
function en(exp: TypedNode): TypedTextExprNode {
return {
pos: makeEmptyPos(),
textNodeType: 'expr',
textType: exp.exprType,
typed: true,
value: exp,
};
}
describe('Constant folding', () => {
describe('Number', () => {
it('Constant folds 10 to itself', () => {
const numberNode = n(10);
const folded = constantFoldExpression(numberNode);
expect(numberNode).toEqual(folded);
});
it('Constant folds -5 to itself', () => {
const numberNode = n(-5);
const folded = constantFoldExpression(numberNode);
expect(numberNode).toEqual(folded);
});
});
describe('Number', () => {
it('Constant empty string to itself', () => {
const stringNode = s('');
const folded = constantFoldExpression(stringNode);
expect(stringNode).toEqual(folded);
});
it('Constant folds "hello" to itself', () => {
const stringNode = s('hello');
const folded = constantFoldExpression(stringNode);
expect(stringNode).toEqual(folded);
});
});
describe('Unary Minus', () => {
it('Can constant fold a simple unary minus number node', () => {
const numberNode = n(10);
const unaryMinusNode = um(numberNode);
const folded = constantFoldExpression(unaryMinusNode);
expect(n(-10)).toEqual(folded);
expect(unaryMinusNode.pos).toEqual(folded.pos);
});
it('Can constant fold a simple unary minus number node with negative starting number', () => {
const numberNode = n(-100);
const unaryMinusNode = um(numberNode);
const folded = constantFoldExpression(unaryMinusNode);
expect(n(100)).toEqual(folded);
expect(unaryMinusNode.pos).toEqual(folded.pos);
});
it('Errors on unary minus with a string', () => {
const stringNode = s('hello');
const unaryMinusNode = um(stringNode);
expect(() => constantFoldExpression(unaryMinusNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Unary minus with a string. It is only allowed on numbers."`,
);
});
it('Does not constant fold -var', () => {
const varNode = v('number', 'var');
const unaryMinus = um(varNode);
const folded = constantFoldExpression(unaryMinus);
expect(unaryMinus).toEqual(folded);
expect(unaryMinus.pos).toEqual(folded.pos);
});
});
describe('Binary op - plus', () => {
it('Can concat two strings', () => {
const lhs = s('Hello ');
const rhs = s('world');
const concatNode = b('string', 'plus', lhs, rhs);
const folded = constantFoldExpression(concatNode);
expect(s('Hello world')).toEqual(folded);
expect(concatNode.pos).toEqual(folded.pos);
});
it('Accepts string and variable', () => {
const lhs = s('Hello ');
const rhs = v('string', 'world');
const concatNode = b('string', 'plus', lhs, rhs);
const folded = constantFoldExpression(concatNode);
expect(concatNode).toEqual(folded);
expect(concatNode.pos).toEqual(folded.pos);
});
it('Accepts variable and variable', () => {
const lhs = v('string', 'hello');
const rhs = v('string', 'world');
const concatNode = b('string', 'plus', lhs, rhs);
const folded = constantFoldExpression(concatNode);
expect(concatNode).toEqual(folded);
expect(concatNode.pos).toEqual(folded.pos);
});
it('Can concat string and number', () => {
const lhs = s('5');
const rhs = n(10);
const concatNode = b('string', 'plus', lhs, rhs);
const folded = constantFoldExpression(concatNode);
expect(s('510')).toEqual(folded);
expect(concatNode.pos).toEqual(folded.pos);
});
it('Can concat number and string', () => {
const lhs = n(10);
const rhs = s(' hello');
const concatNode = b('string', 'plus', lhs, rhs);
const folded = constantFoldExpression(concatNode);
expect(s('10 hello')).toEqual(folded);
expect(concatNode.pos).toEqual(folded.pos);
});
it('Can add two numbers', () => {
const lhs = n(10);
const rhs = n(5);
const additionNode = b('number', 'plus', lhs, rhs);
const folded = constantFoldExpression(additionNode);
expect(n(15)).toEqual(folded);
expect(additionNode.pos).toEqual(folded.pos);
});
});
describe('Binary op minus', () => {
it('Cannot minus two strings', () => {
const lhs = s('Hello ');
const rhs = s('world');
const minusNode = b('string', 'minus', lhs, rhs);
expect(() => constantFoldExpression(minusNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Minus operation between string and string. Only allowed between 2 numbers."`,
);
});
it('Cannot minus string and number', () => {
const lhs = s('5');
const rhs = n(10);
const minusNode = b('string', 'minus', lhs, rhs);
expect(() => constantFoldExpression(minusNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Minus operation between string and number. Only allowed between 2 numbers."`,
);
});
it('Cannot minus number and string', () => {
const lhs = n(10);
const rhs = s(' hello');
const minusNode = b('string', 'minus', lhs, rhs);
expect(() => constantFoldExpression(minusNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Minus operation between number and string. Only allowed between 2 numbers."`,
);
});
it('Can minus two numbers', () => {
const lhs = n(10);
const rhs = n(5);
const minusNode = b('number', 'minus', lhs, rhs);
const folded = constantFoldExpression(minusNode);
expect(n(5)).toEqual(folded);
expect(minusNode.pos).toEqual(folded.pos);
});
it('Accepts number and varaible', () => {
const lhs = n(10);
const rhs = v('number', 'var');
const minusNode = b('number', 'minus', lhs, rhs);
const folded = constantFoldExpression(minusNode);
expect(minusNode).toEqual(folded);
expect(minusNode.pos).toEqual(folded.pos);
});
it('Accepts variable and varaible', () => {
const lhs = v('number', 'var1');
const rhs = v('number', 'var2');
const minusNode = b('number', 'minus', lhs, rhs);
const folded = constantFoldExpression(minusNode);
expect(minusNode).toEqual(folded);
expect(minusNode.pos).toEqual(folded.pos);
});
});
describe('Binary op multiply', () => {
it('Cannot multiply two strings', () => {
const lhs = s('Hello ');
const rhs = s('world');
const multiplyNode = b('string', 'multiply', lhs, rhs);
expect(() => constantFoldExpression(multiplyNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Multiply operation between string and string. Only allowed between 2 numbers."`,
);
});
it('Cannot multiply string and number', () => {
const lhs = s('5');
const rhs = n(10);
const multiplyNode = b('string', 'multiply', lhs, rhs);
expect(() => constantFoldExpression(multiplyNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Multiply operation between string and number. Only allowed between 2 numbers."`,
);
});
it('Cannot multiply number and string', () => {
const lhs = n(10);
const rhs = s(' hello');
const multiplyNode = b('string', 'multiply', lhs, rhs);
expect(() => constantFoldExpression(multiplyNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Multiply operation between number and string. Only allowed between 2 numbers."`,
);
});
it('Can multiply two numbers', () => {
const lhs = n(10);
const rhs = n(5);
const multiplyNode = b('number', 'multiply', lhs, rhs);
const folded = constantFoldExpression(multiplyNode);
expect(n(50)).toEqual(folded);
expect(multiplyNode.pos).toEqual(folded.pos);
});
it('Folds var*number*number', () => {
const varNode = v('number', 'var', {
firstColumn: 0,
firstLine: 1,
lastColumn: 3,
lastLine: 1,
});
const numberNode = n(5, {
firstColumn: 5,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
});
const number2 = n(10, {
firstColumn: 7,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
});
const lhs = b('number', 'multiply', varNode, numberNode, {
firstColumn: 0,
firstLine: 1,
lastColumn: 6,
lastLine: 1,
});
const node = b('number', 'multiply', lhs, number2, {
firstColumn: 0,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
});
const folded = constantFoldExpression(node);
const expected = b(
'number',
'multiply',
varNode,
n(50, {
firstColumn: 5,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
}),
{
firstColumn: 0,
firstLine: 1,
lastColumn: 9,
lastLine: 1,
},
);
expect(folded).toEqual(expected);
});
});
describe('Binary op divide', () => {
it('Cannot divide two strings', () => {
const lhs = s('Hello ');
const rhs = s('world');
const divideNode = b('string', 'divide', lhs, rhs);
expect(() => constantFoldExpression(divideNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Divide operation between string and string. Only allowed between 2 numbers."`,
);
});
it('Cannot divide string and number', () => {
const lhs = s('5');
const rhs = n(10);
const divideNode = b('string', 'divide', lhs, rhs);
expect(() => constantFoldExpression(divideNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Divide operation between string and number. Only allowed between 2 numbers."`,
);
});
it('Cannot divide number and string', () => {
const lhs = n(10);
const rhs = s(' hello');
const divideNode = b('string', 'divide', lhs, rhs);
expect(() => constantFoldExpression(divideNode)).toThrowErrorMatchingInlineSnapshot(
`"Could not constant fold expression. Divide operation between number and string. Only allowed between 2 numbers."`,
);
});
it('Can divide two numbers', () => {
const lhs = n(10);
const rhs = n(5);
const divideNode = b('number', 'divide', lhs, rhs);
const folded = constantFoldExpression(divideNode);
expect(n(2)).toEqual(folded);
expect(divideNode.pos).toEqual(folded.pos);
});
});
describe('Functions', () => {
it('Does not constant fold a function call', () => {
const functionNode = f('someFunction', []);
const folded = constantFoldExpression(functionNode);
expect(functionNode).toEqual(folded);
expect(functionNode.pos).toEqual(folded.pos);
});
it('Does fold arguments', () => {
const functionNode = f('someFunction', [um(n(10))]);
const folded = constantFoldExpression(functionNode);
const expectedFolded = f('someFunction', [n(-10)]);
expect(expectedFolded).toEqual(folded);
expect(functionNode.pos).toEqual(folded.pos);
});
});
describe('Full text constant folding', () => {
it('Can constant fold some stuff', () => {
const text = tn('Some text: ');
const varNode = vn('var', 'string');
const expNode = en(b('string', 'plus', s('Hello '), s('world')));
const text2 = tn('!');
const folded = constantFoldExpressionList({
input: 'Some text: $var{{"Hello"+"world"}}!',
nodes: [text, varNode, expNode, text2],
});
expect('Some text: $var{{"Hello"+"world"}}!').toEqual(folded.input);
expect([tn('Some text: '), vn('var', 'string'), tn('Hello world!')]).toEqual(folded.nodes);
});
it('Can constant fold a complete constant expression', () => {
const text = tn('Some text: ');
const expNode = en(b('string', 'plus', s('Hello '), s('world')));
const text2 = tn('!');
const folded = constantFoldExpressionList({
input: 'Some text: {{"Hello "+"world"}}!',
nodes: [text, expNode, text2],
});
expect([tn('Some text: Hello world!')]).toEqual(folded.nodes);
});
// Regression: https://github.com/secoya/hablar.js/issues/1
it('Can constant fold simple text + interpolation', () => {
const nodes = [tn('Svar til '), en(v('string', 'name')), tn("'s pulse")];
const nodesClone = JSON.parse(JSON.stringify(nodes));
const folded = constantFoldExpressionList({
input: "Svar til {{$name}}'s pulse",
nodes: nodesClone,
});
expect(folded.nodes).toEqual(nodes);
});
});
});
|
secoya/hablar.js
|
test/emitting/constraint.ts
|
import { prettyPrint, types } from 'recast';
import { emitConstrainedTranslation } from '../../src/emitting/constraint';
import Context from '../../src/emitting/context';
import { EqualityNode, IgnoreNode, IneqNode, ValueNode } from '../../src/trees/constraint';
const b = types.builders;
const nullExpr = b.identifier('null');
const five = b.literal(5);
function makeEmptyPos() {
return {
firstColumn: 0,
firstLine: 0,
lastColumn: 0,
lastLine: 0,
};
}
function makeIgnoreConstraint(varName: string): IgnoreNode {
return {
op: '!',
operand: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
pos: makeEmptyPos(),
};
}
function makeEqualityConstraint(varName: string, value: string | number): EqualityNode {
let rhs: ValueNode;
if (typeof value === 'string') {
rhs = {
pos: makeEmptyPos(),
type: 'enum',
value: value,
};
} else {
rhs = {
pos: makeEmptyPos(),
type: 'number',
value: value,
};
}
return {
lhs: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
op: '=',
pos: makeEmptyPos(),
rhs: rhs,
};
}
function makeInequalityConstraint(varName: string, value: number, op: '>' | '<' | '>=' | '<=' = '>'): IneqNode {
return {
lhs: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
op: op,
pos: makeEmptyPos(),
rhs: {
pos: makeEmptyPos(),
type: 'number',
value: value,
},
};
}
describe('Emitting - Constraints', () => {
it('Emits simple return statement with no constraints', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: '',
nodes: [],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`"return null;"`);
});
it('Emits simple return statement with just ignore constraints', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: '!someVar',
nodes: [makeIgnoreConstraint('someVar')],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`"return null;"`);
});
it('Emits simple if statement on single constraint', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5',
nodes: [makeEqualityConstraint('someVar', 5)],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5) {
return null;
}"
`);
});
it('Emits simple if statement on multiple constraints with one ignore constraint', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5,!someOtherVar',
nodes: [makeEqualityConstraint('someVar', 5), makeIgnoreConstraint('someOtherVar')],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5) {
return null;
}"
`);
});
it('Emits simple if statement on constraint with multiple tests', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5,someOtherVar<10',
nodes: [makeEqualityConstraint('someVar', 5), makeInequalityConstraint('someOtherVar', 10)],
},
five,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5 && vars.someOtherVar > 10) {
return 5;
}"
`);
});
});
|
secoya/hablar.js
|
src/errors/unknown_variable_error.ts
|
<reponame>secoya/hablar.js<gh_stars>0
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { TypedVariableNode as ExprVarNode } from '../trees/expression';
import { TypedASTRoot, TypedVariableNode as TextVarNode } from '../trees/text';
import { showErrorLocation } from './util';
export default class UnknownVariableError extends Error {
public variable: string;
public allowedVariables: string[];
public line: number;
public column: number;
public input: string;
public constraints: string | null;
public constructor(
node: ExprVarNode | TextVarNode,
allowedVariables: string[],
ast: TypedASTRoot,
constraints: ConstraintAST | null = null,
) {
let varName: string;
if ((node as ExprVarNode).exprNodeType === 'variable') {
varName = (node as ExprVarNode).name;
} else {
varName = (node as TextVarNode).value;
}
const errMessage =
'' +
`Unknown variable \$${varName} used on line ${node.pos.firstLine}:\n` +
showErrorLocation(
ast.input,
`Variable \$${varName} is not known to this translation. ` +
`Known variables are: ${allowedVariables.map(e => '$' + e).join(', ')}`,
node.pos.firstLine,
node.pos.firstColumn,
);
super(errMessage);
Object.setPrototypeOf(this, UnknownVariableError.prototype);
this.message = errMessage;
this.variable = varName;
this.allowedVariables = allowedVariables;
this.line = node.pos.firstLine;
this.column = node.pos.firstColumn;
this.input = ast.input;
this.constraints = constraints != null ? constraints.input : null;
}
}
UnknownVariableError.prototype.name = 'UnknownVariableError';
|
secoya/hablar.js
|
src/analysis/allowed_symbols.ts
|
import { walkTypedNode } from '../parsers/expression';
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { TypedNode as TypedExprNode } from '../trees/expression';
import { TypedASTRoot } from '../trees/text';
import UnknownFunctionError from '../errors/unknown_function_error';
import UnknownVariableError from '../errors/unknown_variable_error';
export function ensureAllVariablesAndFunctionsAreAllowed(
ast: TypedASTRoot,
constraintAST: ConstraintAST | null,
allowedVariables: string[] | null,
allowedFunctions: string[] | null,
): void {
const allowedVars = allowedVariables != null ? new Set<string>(allowedVariables) : null;
const allowedFuns = allowedFunctions != null ? new Set<string>(allowedFunctions) : null;
for (const textNode of ast.nodes) {
switch (textNode.textNodeType) {
case 'variable':
if (allowedVars != null && !allowedVars.has(textNode.value)) {
throw new UnknownVariableError(textNode, Array.from(allowedVars.values()), ast, constraintAST);
}
break;
case 'expr':
{
const expr: TypedExprNode = (textNode.value as any) as TypedExprNode;
walkTypedNode(expr, node => {
switch (node.exprNodeType) {
case 'variable':
if (allowedVars != null && !allowedVars.has(node.name)) {
throw new UnknownVariableError(
node,
Array.from(allowedVars.values()),
ast,
constraintAST,
);
}
break;
case 'function_invocation':
if (allowedFuns != null && !allowedFuns.has(node.name)) {
throw new UnknownFunctionError(
node,
Array.from(allowedFuns.values()),
ast,
constraintAST,
);
}
break;
default: // We don't care about the remaining node types
}
});
}
break;
default: // We don't care about the string literals, they cannot contain functions or variables
}
}
}
|
secoya/hablar.js
|
src/trees/constraint.ts
|
<gh_stars>0
export type Pos = {
firstLine: number;
firstColumn: number;
lastLine: number;
lastColumn: number;
};
export type IgnoreNode = {
op: '!';
operand: IdentifierNode;
pos: Pos;
};
export type IdentifierNode = {
type: 'identifier';
name: string;
pos: Pos;
};
export type GenderNode = {
type: 'gender';
value: 'F' | 'N' | 'M';
pos: Pos;
};
export type EnumNode = {
type: 'enum';
value: string;
pos: Pos;
};
export type NumberNode = {
type: 'number';
value: number;
pos: Pos;
};
export type ValueNode = GenderNode | EnumNode | NumberNode;
export type EqualityNode = {
op: '=' | '!=';
lhs: IdentifierNode;
rhs: ValueNode;
pos: Pos;
};
export type IneqNode = {
op: '<=' | '>=' | '<' | '>';
lhs: IdentifierNode;
rhs: NumberNode;
pos: Pos;
};
export type Node = IgnoreNode | EqualityNode | IneqNode;
export type ASTRoot = {
input: string;
nodes: Node[];
};
|
secoya/hablar.js
|
src/trees/expression.ts
|
import { InferredType } from '../type_map';
export type Pos = {
firstLine: number;
firstColumn: number;
lastLine: number;
lastColumn: number;
};
export type BinaryOpNode = {
exprNodeType: 'binary_op';
binaryOp: 'plus' | 'multiply' | 'divide' | 'minus';
lhs: Node;
rhs: Node;
pos: Pos;
typed?: false;
};
export type TypedBinaryOpNode = {
exprNodeType: 'binary_op';
binaryOp: 'plus' | 'multiply' | 'divide' | 'minus';
lhs: TypedNode;
rhs: TypedNode;
pos: Pos;
exprType: InferredType;
typed: true;
isConstant: boolean;
};
export type UnaryMinusNode = {
exprNodeType: 'unary_minus';
op: Node;
pos: Pos;
typed?: false;
};
export type TypedUnaryMinusNode = {
exprNodeType: 'unary_minus';
op: TypedNode;
pos: Pos;
exprType: InferredType;
typed: true;
isConstant: boolean;
};
export type NumberNode = {
exprNodeType: 'number';
value: number;
pos: Pos;
typed?: false;
};
export type TypedNumberNode = {
exprNodeType: 'number';
value: number;
pos: Pos;
exprType: 'number';
typed: true;
isConstant: true;
};
export type StringLiteralNode = {
exprNodeType: 'string_literal';
value: string;
pos: Pos;
typed?: false;
};
export type TypedStringLiteralNode = {
exprNodeType: 'string_literal';
value: string;
pos: Pos;
exprType: 'string';
typed: true;
isConstant: true;
};
export type VariableNode = {
exprNodeType: 'variable';
name: string;
pos: Pos;
typed?: false;
};
export type TypedVariableNode = {
exprNodeType: 'variable';
name: string;
pos: Pos;
exprType: InferredType;
typed: true;
isConstant: false;
};
export type FunctionInvocationNode = {
exprNodeType: 'function_invocation';
name: string;
parameters: Node[];
pos: Pos;
typed?: false;
};
export type TypedFunctionInvocationNode = {
exprNodeType: 'function_invocation';
name: string;
parameters: TypedNode[];
pos: Pos;
exprType: 'error' | 'string';
typed: true;
isConstant: false;
};
export type Node =
| BinaryOpNode
| UnaryMinusNode
| NumberNode
| StringLiteralNode
| VariableNode
| FunctionInvocationNode;
export type TypedNode =
| TypedBinaryOpNode
| TypedUnaryMinusNode
| TypedNumberNode
| TypedStringLiteralNode
| TypedVariableNode
| TypedFunctionInvocationNode;
|
secoya/hablar.js
|
src/trees/text.ts
|
<reponame>secoya/hablar.js
import { Node as ExpressionNode, TypedNode as TypedExpressionNode } from './expression';
import { InferredType } from '../type_map';
export type Pos = {
firstLine: number;
firstColumn: number;
lastLine: number;
lastColumn: number;
};
export type LiteralNode = {
textNodeType: 'literal';
value: string;
pos: Pos;
typed?: false;
};
export type TypedLiteralNode = {
textNodeType: 'literal';
value: string;
pos: Pos;
textType: InferredType;
typed: true;
};
export type VariableNode = {
textNodeType: 'variable';
value: string;
pos: Pos;
typed?: false;
};
export type TypedVariableNode = {
textNodeType: 'variable';
value: string;
pos: Pos;
textType: InferredType;
typed: true;
};
export type ExprNode = {
textNodeType: 'expr';
value: ExpressionNode;
pos: Pos;
typed?: false;
};
export type TypedExprNode = {
textNodeType: 'expr';
value: TypedExpressionNode;
pos: Pos;
textType: InferredType;
typed: true;
};
export type Node = LiteralNode | VariableNode | ExprNode;
export type TypedNode = TypedLiteralNode | TypedVariableNode | TypedExprNode;
export type ASTRoot = {
input: string;
nodes: Node[];
};
export type TypedASTRoot = {
input: string;
nodes: TypedNode[];
};
|
secoya/hablar.js
|
src/analysis/combined.ts
|
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { ASTRoot, TypedASTRoot } from '../trees/text';
import TypeMap from '../type_map';
import { ensureAllVariablesAndFunctionsAreAllowed } from './allowed_symbols';
import { constantFoldExpressionList } from './constant_folding';
import { inferConstraintTypes, inferTextTypes, makeTypedExpressionList } from './type_inference';
export type SimpleTranslation = ASTRoot;
// $FlowFixMe: Flow is not happy that we use unions between two types that have no relations
export type ConstraintTranslation = {
constraints: ConstraintAST;
translation: ASTRoot;
}[];
export type SimpleTypedTranslation = TypedASTRoot;
export type TypedConstraintTranslation = Array<{
constraints: ConstraintAST;
translation: TypedASTRoot;
}>;
export type Translation = SimpleTranslation | ConstraintTranslation;
export type TypedTranslation = SimpleTypedTranslation | TypedConstraintTranslation;
function workWithTranslation<TSimple, TConstraint>(
translation: Translation,
callbackSimple: (translation: SimpleTranslation) => TSimple,
callbackConstraint: (translation: ConstraintTranslation) => TConstraint,
): TSimple | TConstraint {
const simple = translation as SimpleTranslation;
const constraint = translation as ConstraintTranslation;
if (!Array.isArray(constraint)) {
return callbackSimple(simple);
} else {
return callbackConstraint(constraint);
}
}
export function typeInferTranslation(translation: Translation, map: TypeMap): void {
workWithTranslation(
translation,
tr => inferTextTypes(map, tr),
tr => {
for (const trans of tr) {
inferConstraintTypes(map, trans.constraints, trans.translation);
inferTextTypes(map, trans.translation, trans.constraints);
}
},
);
}
export function analyzeOnlyTranslation(
translation: Translation,
map: TypeMap,
allowedVariables: string[] | null = null,
allowedFunctions: string[] | null = null,
): TypedTranslation {
return workWithTranslation(
translation,
(tr): SimpleTypedTranslation => analyzeOnlySimpleTranslation(tr, map, allowedVariables, allowedFunctions),
tr => analyzeOnlyConstraintTranslation(tr, map, allowedVariables, allowedFunctions),
);
}
export function analyzeTranslation(
translation: Translation,
map: TypeMap,
allowedVariables: string[] | null = null,
allowedFunctions: string[] | null = null,
): TypedTranslation {
typeInferTranslation(translation, map);
map.freeze();
return analyzeOnlyTranslation(translation, map, allowedVariables, allowedFunctions);
}
export function analyzeTranslations(
translations: Translation[],
map: TypeMap,
allowedVariables: string[] | null = null,
allowedFunctions: string[] | null = null,
): TypedTranslation[] {
for (const translation of translations) {
typeInferTranslation(translation, map);
}
map.freeze();
return translations.map(translation =>
analyzeOnlyTranslation(translation, map, allowedVariables, allowedFunctions),
);
}
export function analyzeOnlySimpleTranslation(
translation: SimpleTranslation,
map: TypeMap,
allowedVariables: string[] | null = null,
allowedFunctions: string[] | null = null,
): SimpleTypedTranslation {
const res = makeTypedExpressionList(map, translation);
if (allowedVariables != null || allowedFunctions != null) {
ensureAllVariablesAndFunctionsAreAllowed(res, null, allowedVariables, allowedFunctions);
}
return constantFoldExpressionList(res);
}
export function analyzeOnlyConstraintTranslation(
translations: ConstraintTranslation,
map: TypeMap,
allowedVariables: string[] | null = null,
allowedFunctions: string[] | null = null,
): TypedConstraintTranslation {
const res: TypedConstraintTranslation = [];
for (const translation of translations) {
const typed = makeTypedExpressionList(map, translation.translation);
if (allowedVariables != null || allowedFunctions != null) {
ensureAllVariablesAndFunctionsAreAllowed(
typed,
translation.constraints,
allowedVariables,
allowedFunctions,
);
}
res.push({
constraints: translation.constraints,
translation: typed,
});
}
for (const tr of res) {
tr.translation = constantFoldExpressionList(tr.translation);
}
return res;
}
|
secoya/hablar.js
|
src/errors/type_error.ts
|
<filename>src/errors/type_error.ts
import { Node as ConstraintNode } from '../trees/constraint';
import { Node as ExprNode } from '../trees/expression';
import { Node as TextNode, Pos } from '../trees/text';
import { showErrorLocation } from './util';
import { default as TypeMap, InferredType } from '../type_map';
function printTypes(t: InferredType | InferredType[]): string {
if (Array.isArray(t)) {
return t.map(printType).join(', ');
}
return printType(t);
}
function printType(t: InferredType): string {
return t;
}
function getLocation(node: ExprNode | ConstraintNode | TextNode): Pos {
return node.pos;
}
function getErrorMessageForSimpleText(
line: number,
column: number,
variable: string,
expectedType: string,
foundType: string,
input: string,
): string {
return (
`Type error at line ${line}:\n` +
showErrorLocation(
input,
`Variable \$${variable} was expected to have type: ${expectedType}, ` + `found: ${foundType}.`,
line,
column,
)
);
}
function getErrorMessageForConstraintError(
line: number,
column: number,
variable: string,
expectedType: string,
foundType: string,
constraintInput: string,
textInput: string,
): string {
return (
`Type error at line ${line}:\n` +
showErrorLocation(
constraintInput,
`Variable \$${variable} was expected to have type: ${expectedType}, ` + `found: ${foundType}.`,
line,
column,
)
);
}
function getErrorMessageConstraintTextError(
line: number,
column: number,
variable: string,
expectedType: string,
foundType: string,
constraintInput: string,
textInput: string,
): string {
return (
`Type error at line ${line}:\n` +
showErrorLocation(
textInput,
`Variable \$${variable} was expected to have type: ${expectedType}, ` + `found: ${foundType}.`,
line,
column,
)
);
}
export default class TypeError extends Error {
public expectedType: InferredType;
public foundType: InferredType;
public text: string;
public constraintText: string | null;
public node: ConstraintNode | TextNode | ExprNode | null;
public position: Pos;
public typeMap: TypeMap;
public variable: string;
public constructor(
expectedType: InferredType,
foundType: InferredType,
typeMap: TypeMap,
node: ConstraintNode | TextNode | ExprNode | null,
text: string,
constraintText: string | null,
variable: string,
) {
const position =
node != null
? getLocation(node)
: {
firstColumn: 0,
firstLine: 0,
lastColumn: 0,
lastLine: 0,
// tslint:disable-next-line
};
const isConstraintError = (node as ConstraintNode).op != null;
let errorMessage: string;
if (isConstraintError) {
errorMessage = getErrorMessageForConstraintError(
position.firstLine,
position.firstColumn,
variable,
printTypes(expectedType),
printTypes(foundType),
constraintText as string,
text,
);
} else if (constraintText != null) {
errorMessage = getErrorMessageConstraintTextError(
position.firstLine,
position.firstColumn,
variable,
printTypes(expectedType),
printTypes(foundType),
constraintText as string,
text,
);
} else {
errorMessage = getErrorMessageForSimpleText(
position.firstLine,
position.firstColumn,
variable,
printTypes(expectedType),
printTypes(foundType),
text,
);
}
super(errorMessage);
Object.setPrototypeOf(this, TypeError.prototype);
this.message = errorMessage;
this.foundType = foundType;
this.typeMap = typeMap;
this.expectedType = expectedType;
this.node = this.node;
this.position = position;
this.variable = variable;
this.text = text;
this.constraintText = constraintText;
}
}
TypeError.prototype.name = 'TypeError';
|
MMF-FE/weex-vue-fixed
|
src/index.ts
|
/**
* fixed tag for weex
* @author vfasky<<EMAIL>>
*
**/
'use strict'
import { clear } from './reg'
import component from './fixed'
declare var require
export default {
install(Vue) {
Vue.fixedClear = function() {
clear()
}
let fixed
if (String(weex.config.env.platform).toLowerCase() == 'web'){
fixed = require('../dist/weex-vue-fixed.js')
} else {
fixed = require('../dist/weex-weex-fixed.js')
}
component.render = fixed.render
Vue.component('wv-fixed', component)
}
}
|
MMF-FE/weex-vue-fixed
|
src/reg.ts
|
<gh_stars>1-10
/**
*
* @author vfasky<<EMAIL>>
*
**/
'use strict'
let _data = []
const _isRun = String(weex.config.env.platform).toLowerCase() == 'android'
export function clear() {
if (!_isRun) return
_data.forEach((component) => {
let node = component.$refs.fixed
if(node) {
let parent = node.parentNode
if (parent) {
try {
parent.removeChild(node, true)
} catch (error) {}
}
}
})
_data = []
}
export function add(component) {
if (!_isRun) return
_data.push(component)
}
|
MMF-FE/weex-vue-fixed
|
src/fixed.ts
|
/**
* @date 2017-02-21 11:26:57
*
**/
'use strict'
import * as Vue from 'vue'
import * as reg from './reg'
let attr = ['left', 'right', 'top', 'bottom']
export default {
render() {
//hook
},
props: {
left: {
type: [Number, String]
},
right: {
type: [Number, String]
},
top: {
type: [Number, String]
},
bottom: {
type: [Number, String]
},
show: {
type: Boolean,
default: true
}
},
computed: {
style() {
let css = {
position: 'fixed'
}
attr.forEach(v => {
if (this[v] && this[v] !== 'auto') {
css[v] = `${this[v]}px`
}
})
return css
}
},
created() {
reg.add(this)
}
}
|
d3m0n-r00t/BentoML
|
bentoml/yatai/web/src/server.ts
|
<gh_stars>1-10
import path from "path";
import morgan from "morgan";
import { Request, Response } from "express";
import express from "express";
import { bentoml } from "./generated/bentoml_grpc";
import { createYataiClient } from "./yatai_client";
import { getLogger } from "./logger";
const logger = getLogger();
const createRoutes = (app, yataiClient) => {
let router = express.Router();
router.get("/api/ListBento", async (req: Request, res: Response) => {
const requestQuery: any = Object.assign({}, req.query);
if (req.query.limit && typeof req.query.limit == "string") {
requestQuery.limit = Number(req.query.limit);
}
if (req.query.offset && typeof req.query.offset == "string") {
requestQuery.offset = Number(req.query.offset);
}
let verifyError = bentoml.ListBentoRequest.verify(requestQuery);
if (verifyError) {
logger.error({ request: "ListBento", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.ListBentoRequest.create(requestQuery);
try {
const result = await yataiClient.listBento(requestMessage);
logger.info({
request: "ListBento",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({ request: "ListBento", error: JSON.stringify(error) });
return res.status(500).json(error);
}
});
router.get("/api/GetBento", async (req: Request, res: Response) => {
let verifyError = bentoml.GetBentoRequest.verify(req.query);
if (verifyError) {
logger.error({ request: "GetBento", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.GetBentoRequest.create(req.query);
try {
const result = await yataiClient.getBento(requestMessage);
logger.info({
request: "GetBento",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({ request: "GetBento", error: JSON.stringify(error) });
return res.status(500).json(error);
}
});
router.get("/api/GetDeployment", async (req: Request, res: Response) => {
let verifyError = bentoml.GetDeploymentRequest.verify(req.query);
if (verifyError) {
logger.error({ request: "GetDeployment", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.GetDeploymentRequest.create(req.query);
try {
const result = await yataiClient.getDeployment(requestMessage);
logger.info({
request: "GetDeployment",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({ request: "GetDeployment", error: JSON.stringify(error) });
return res.status(500).json(error);
}
});
router.get("/api/ListDeployments", async (req: Request, res: Response) => {
const requestQuery: any = Object.assign({}, req.query);
if (req.query.limit && typeof req.query.limit == "string") {
requestQuery.limit = Number(req.query.limit);
}
let verifyError = bentoml.ListDeploymentsRequest.verify(requestQuery);
if (verifyError) {
logger.error({ request: "ListDeployments", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.ListDeploymentsRequest.create(requestQuery);
try {
const result = await yataiClient.listDeployments(requestMessage);
logger.info({
request: "ListDeployments",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({ request: "ListDeployment", error: JSON.stringify(error) });
return res.status(500).json(error);
}
});
router.post("/api/DeleteDeployment", async (req: Request, res: Response) => {
let verifyError = bentoml.DeleteDeploymentRequest.verify(req.body);
if (verifyError) {
logger.error({ request: "DeleteDeployment", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.DeleteDeploymentRequest.create(req.body);
try {
const result = await yataiClient.deleteDeployment(requestMessage);
logger.info({
request: "DeleteDeployment",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({
request: "DeleteDeployment",
error: JSON.stringify(error),
});
return res.status(500).json(error);
}
});
router.post("/api/DeleteBento", async (req: Request, res: Response) => {
let verifyError = bentoml.DangerouslyDeleteBentoRequest.verify(req.body);
if (verifyError) {
logger.error({ request: "DeleteBento", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.DangerouslyDeleteBentoRequest.create(req.body);
try {
const result = await yataiClient.dangerouslyDeleteBento(requestMessage);
logger.info({
request: "DeleteBento",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({ request: "DeleteBento", error: JSON.stringify(error) });
return res.status(500).json(error);
}
});
router.post("/api/ApplyDeployment", async (req: Request, res: Response) => {
let verifyError = bentoml.ApplyDeploymentRequest.verify(req.body);
if (verifyError) {
logger.error({ request: "ApplyDeployment", error: verifyError });
return res.status(400).json({ error: verifyError });
}
let requestMessage = bentoml.ApplyDeploymentRequest.create(req.body);
try {
const result = await yataiClient.applyDeployment(requestMessage);
logger.info({
request: "ApplyDeployment",
data: requestMessage,
result: result,
});
if (result.status.status_code != 0) {
return res.status(400).json({ error: result.status.error_message });
}
return res.status(200).json(result);
} catch (error) {
logger.error({
request: "ApplyDeployment",
error: JSON.stringify(error),
});
return res.status(500).json(error);
}
});
return router;
};
export const getExpressApp = (grpcAddress: string | null, baseURL: string) => {
const app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(function (req, res, next) {
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
res.cookie('baseURLCookie',baseURL, { maxAge: 900000, httpOnly: false });
console.log('cookie created successfully');
} else {
console.log('cookie exists', cookie);
}
next();
});
app.use(express.json());
app.use(
morgan("combined", {
stream: { write: (message) => logger.info(message.trim()) },
})
);
const yataiClient = createYataiClient(grpcAddress);
const router = createRoutes(app, yataiClient);
const apiUrlPrefix = (baseURL=="." ? '/' : '/' + baseURL);
app.use(apiUrlPrefix, router);
app.get("/*", (req, res) => {
let directory = req.path.split("/").slice(-2, -1);
let filename = req.path.split("/").pop();
if (/.js$|.css$/.test(req.path)) {
res.sendFile(path.join(__dirname, `../dist/client/static/${directory}/${filename}`));
} else if (/favicon.png$|logo192.png$/.test(req.path)) {
res.sendFile(path.join(__dirname, `../dist/client/${filename}`));
} else if (/.png/.test(req.path)) {
res.sendFile(path.join(__dirname, `../dist/client/static/${directory}/${filename}`));
} else {
res.sendFile(path.join(__dirname, "../dist/client/index.html"));
}
});
app.use(express.static(path.join(__dirname, "../dist/client")));
return app;
};
|
JakeStanger/Reactive-Gallery
|
src/components/card/Card.tsx
|
import React from "react";
import styles from "./Card.module.scss";
import { Link } from "react-router-dom";
import { DateTime } from "luxon";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faMapMarker,
faClock,
faTrash
} from "@fortawesome/free-solid-svg-icons";
import ICardProps from "./ICardProps";
import LazyLoad from "react-lazyload";
import css from "../../styles/css";
const Card: React.FC<ICardProps> = ({
image,
imageService,
showDescription,
showLocation,
showTags,
showTime,
showPriceInfo,
basketItem,
onDelete,
height,
query
}) => {
// TODO: Fix going back reloading gallery, not saving scroll state
// TODO: Fix editing location CSS
return (
<div className={styles.card} id={`card-${image.id}`}>
<Link to={`/preview/${image.id}`}>
<LazyLoad height={height} offset={300} once={true} resize={true}>
<div style={{height}}>
<img
className={styles.image}
src={imageService.getLink(image)}
alt={image.name}
height={height}
/>
</div>
</LazyLoad>
</Link>
<div className={styles.info}>
<div className={styles.title}>{image.name}</div>
{showLocation && image.location && (
<div className={styles.infoTag}>
<FontAwesomeIcon icon={faMapMarker} />
{image.location.name}
</div>
)}
{showTime && image.timeTaken && (
<div className={styles.infoTag}>
<FontAwesomeIcon icon={faClock} />
{DateTime.fromISO(image.timeTaken).toFormat("dd/MM/yyyy HH:mm")}
</div>
)}
{showDescription && image.description && (
<div className={styles.description}>{image.description}</div>
)}
{showPriceInfo && basketItem && (
<div className={styles.priceInfo}>
<div>Size: {basketItem.price.name}</div>
<div>Framed: {basketItem.framed ? "Yes" : "No"}</div>
<div>
Price: £
{(basketItem.framed
? basketItem.price.framed
: basketItem.price.unframed) * basketItem.quantity}
</div>
<div>Quantity: {basketItem.quantity}</div>
</div>
)}
{showTags && image.tags && (
<div className={styles.tags}>
{image.tags.map(tag => (
<Link
key={tag.id}
className={css(
styles.tag,
query === tag.name && styles.selected
)}
to={{
pathname: "/",
search: `q=${tag.name}`
}}
>
{tag.name}
</Link>
))}
</div>
)}
{showPriceInfo && basketItem && (
<div className={styles.controls}>
{onDelete && (
<div
className={styles.button}
onClick={() => onDelete(basketItem)}
>
<FontAwesomeIcon icon={faTrash} />
<span>Delete</span>
</div>
)}
</div>
)}
</div>
</div>
);
};
export default Card;
|
JakeStanger/Reactive-Gallery
|
server/routes/checkout/Checkout.ts
|
<filename>server/routes/checkout/Checkout.ts
import { Request, Response } from "express";
import { getUserBasket } from "../basketItem/BasketItems";
import StripeManager from "../../StripeManager";
export const getClientPublic = async (req: Request, res: Response) => {
return res.json({ publicKey: process.env.STRIPE_PUBLIC });
};
export const createCheckoutSession = async (req: Request, res: Response) => {
const basket = await getUserBasket((req.user as any).id);
const publicAddress = process.env.PUBLIC_ADDRESS;
const basketItems = basket.map(item => ({
name: `${item.image.name} [${item.price.name}, ${
item.framed ? "framed" : "unframed"
}]`,
description: `${item.price.name}, ${item.framed ? "framed" : "unframed"}`,
images: [`${publicAddress}/api/image/thumb/${item.image.filename}`],
amount: (item.framed ? item.price.framed : item.price.unframed) * 100,
quantity: item.quantity,
currency: "gbp"
}));
// Include postage if requested
const GREETINGS_CARDS_GROUP = 1000;
const canPost = !basket.find(
item =>
(item.framed && item.price.price_group_id !== GREETINGS_CARDS_GROUP) ||
!item.price.postage
);
if (req.body.post && canPost) {
const postagePrice = basket
.map(item => item.price.postage)
.reduce((max, price) => {
if (price > max) max = price;
return max;
});
basketItems.push({
name: "Postage & Packaging",
amount: postagePrice * 100,
currency: "gbp",
quantity: 1,
description: undefined,
images: undefined
});
}
const session = await StripeManager.getStripe().checkout.sessions.create({
payment_method_types: ["card"],
line_items: basketItems,
client_reference_id: (req.user as any).id,
shipping_address_collection: {
allowed_countries: ["GB"]
},
success_url: `${publicAddress}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${publicAddress}/basket`
});
return res.json({ sessionId: session.id });
};
export const getCheckoutSession = async (req: Request, res: Response) => {
const session = await StripeManager.getStripe().checkout.sessions.retrieve(
req.params.sessionId
);
return res.json({
items: session.display_items,
address: session.shipping.address,
name: session.shipping.name
});
};
|
JakeStanger/Reactive-Gallery
|
server/routes/price/Prices.ts
|
<filename>server/routes/price/Prices.ts
import { Request, Response } from "express";
import Price from "../../database/models/Price";
export const getPrices = async (req: Request, res: Response) => {
const prices = await Price.findAll();
return res.json(prices);
};
export const getPricesForGroup = async (req: Request, res: Response) => {
const prices = await Price.findAll({
where: { price_group_id: req.params.groupId }
});
return res.json(prices);
};
|
JakeStanger/Reactive-Gallery
|
src/components/loader/Loader.tsx
|
<reponame>JakeStanger/Reactive-Gallery
import React from "react";
import styles from "./Loader.module.scss";
const Loader: React.FC<{small?: boolean}> = ({small}) => {
const loader = <div className={styles.loader}>Loading...</div>;
if(small) return loader;
return (
<div className={styles.loaderContainer}>
{loader}
</div>
);
};
export default Loader;
|
JakeStanger/Reactive-Gallery
|
src/types.d.ts
|
<filename>src/types.d.ts
declare module "filepond-plugin-file-validate-type";
declare module "filepond-plugin-image-preview";
|
JakeStanger/Reactive-Gallery
|
src/pages/pricing/priceTable/IPriceTableProps.ts
|
<filename>src/pages/pricing/priceTable/IPriceTableProps.ts
import IPriceGroup from "../../../services/priceService/IPriceGroup";
import IPrice from "../../../services/priceService/IPrice";
interface IPriceTableProps {
group: IPriceGroup;
prices: IPrice[];
className?: string;
}
export default IPriceTableProps;
|
JakeStanger/Reactive-Gallery
|
server/database/models/Tag.ts
|
import { Model, DataTypes } from "sequelize";
import Database from "../index";
import Image from "./Image";
class Tag extends Model {
public id: number;
public name: string;
public images?: Image[];
public static load() {
Tag.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(32),
unique: true
}
},
{
sequelize: Database.getConnection(),
tableName: "tags"
}
);
}
public static async getFromArray(tags: any[]) {
return await Promise.all(
tags.map(
(tagData: Tag) =>
new Promise<Tag>(resolve => {
Tag.findOrCreate({ where: { name: tagData.name } }).then(([tag]) =>
resolve(tag)
);
})
)
);
}
}
export default Tag;
|
JakeStanger/Reactive-Gallery
|
server/utils/exifReader.ts
|
import { ExifData, ExifImage } from "exif";
import { DateTime } from "luxon";
async function loadExif(image: Buffer) {
return await new Promise<Error | ExifData>(
(resolve, reject) =>
new ExifImage(image, (err, data) => {
if (data) resolve(data);
else reject(err);
})
);
}
export async function getExif(image: Buffer) {
const exif = await loadExif(image);
if ((exif as Error).message) throw exif;
const imageData: any = {};
if ((exif as ExifData).exif) {
const exifRaw = (exif as ExifData).exif;
imageData.exposure = exifRaw.ExposureTime;
imageData.focalLength = exifRaw.FocalLength;
imageData.aperture = exifRaw.FNumber;
imageData.iso = exifRaw.ISO;
imageData.cameraModel = (exif as ExifData).image.Model;
if (exifRaw.DateTimeOriginal) {
const timeTaken = DateTime.fromFormat(
exifRaw.DateTimeOriginal,
"yyyy:MM:dd hh:mm:ss"
);
if (timeTaken && timeTaken.isValid)
imageData.timeTaken = timeTaken.toJSDate();
}
}
return imageData;
}
|
JakeStanger/Reactive-Gallery
|
server/routes/image/Image.ts
|
<filename>server/routes/image/Image.ts
import { Request, Response } from "express";
import Location from "../../database/models/Location";
import Tag from "../../database/models/Tag";
import Image from "../../database/models/Image";
import * as imageGenerator from "../../utils/imageGenerator";
import * as exifReader from "../../utils/exifReader";
import User from "../../database/models/User";
import PriceGroup from "../../database/models/PriceGroup";
import * as path from "path";
import Category from "../../database/models/Category";
export const getImageThumbnail = async (req: Request, res: Response) => {
if (req.params.filename.endsWith("webp")) {
return res.type("image/webp").sendFile(req.params.filename, {
root: path.join(process.env.UPLOAD_PATH, "thumb")
});
} else {
const filename = req.params.filename.replace(/jpeg$/, "webp");
await imageGenerator.generateJpeg(filename, "thumb");
return res.type("image/jpeg").sendFile(req.params.filename, {
root: path.join(process.env.UPLOAD_PATH, "thumb")
});
}
};
export const getImageMarked = async (req: Request, res: Response) => {
if (req.params.filename.endsWith("webp")) {
return res.type("image/webp").sendFile(req.params.filename, {
root: path.join(process.env.UPLOAD_PATH, "marked")
});
} else {
const filename = req.params.filename.replace(/jpeg$/, "webp");
await imageGenerator.generateJpeg(filename, "marked");
return res.type("image/jpeg").sendFile(req.params.filename, {
root: path.join(process.env.UPLOAD_PATH, "marked")
});
}
};
export const getImageInfo = async (req: Request, res: Response) => {
const image = await Image.findOne({
where: { id: req.params.id },
include: [
{ model: Category, as: "categories" },
{ model: Location, as: "location" },
{ model: Tag, as: "tags" },
{ model: PriceGroup, as: "priceGroup" }
]
});
return res.json(image);
};
export const patchImageInfo = async (req: Request, res: Response) => {
if (!req.body || !Object.keys(req.body).length)
res.status(400).json({ msg: "Missing request body" });
const user = await User.findOne({ where: { id: (req.user as any).id } });
if (!user.canEdit) {
res.status(401).json({ msg: "Missing edit permissions" });
}
// Update name/description
await Image.update(req.body, {
where: { id: req.params.id }
});
// Update tags, categories and location
const image = await Image.findOne({
where: { id: req.params.id }
});
if (req.body.location !== undefined) {
if (req.body.location !== null) {
const location = await Location.getFromObject(req.body.location);
await image.setLocation(location);
} else await image.setLocation(null);
}
if (req.body.categories !== undefined) {
const categories = await Category.getFromArray(req.body.categories);
await image.setCategories(categories);
}
if (req.body.tags !== undefined) {
const tags = await Tag.getFromArray(req.body.tags);
await image.setTags(tags);
}
if (req.body.priceGroup !== undefined) {
const priceGroup = await PriceGroup.getFromObject(req.body.priceGroup);
await image.setPriceGroup(priceGroup);
}
return res.json(image);
};
export const deleteImage = async (req: Request, res: Response) => {
const user = await User.findOne({ where: { id: (req.user as any).id } });
if (!user.canUpload) {
res.status(401).json({ msg: "Missing upload permissions" });
}
await Image.update({ deleted: true }, { where: { id: req.params.id } });
return res.json({ msg: "Image deleted" });
};
export const postImage = async (req: Request, res: Response) => {
let imageData = JSON.parse(req.body.data);
imageData.filename = req.file.originalname.replace(/\.(.*)$/, ".webp");
const user = await User.findOne({ where: { id: (req.user as any).id } });
if (!user.canUpload) {
res.status(401).json({ msg: "Missing upload permissions" });
}
try {
imageData = {
...imageData,
...(await exifReader.getExif(req.file.buffer))
};
} catch (err) {
console.error(err);
return res.status(500).json({ msg: err.message });
}
await imageGenerator.generateThumbnail(req.file.buffer, imageData.filename);
const { width, height } = await imageGenerator.generateMarked(
req.file.buffer,
imageData.filename
);
// width and height should be returned form
imageData.width = width;
imageData.height = height;
// delete previous matching entry
const existingImage = await Image.findOne({
where: { filename: imageData.filename }
});
if (existingImage) {
if (existingImage.deleted) {
await existingImage.destroy();
} else {
return res.status(400).json({ msg: "Image already exists" });
}
}
const image = await Image.create(imageData);
if (imageData.location) {
const location = await Location.getFromObject(imageData.location);
await image.setLocation(location);
}
if (imageData.tags) {
const tags = await Tag.getFromArray(imageData.tags);
await image.setTags(tags as Tag[]);
}
if (imageData.priceGroup) {
const priceGroup = await PriceGroup.getFromObject(imageData.priceGroup);
image.setPriceGroup(priceGroup);
}
return res.status(201).json(imageData);
};
|
JakeStanger/Reactive-Gallery
|
src/components/button/secondary/ISecondaryButtonProps.ts
|
<filename>src/components/button/secondary/ISecondaryButtonProps.ts
import IButtonProps from "../IButtonProps";
interface ISecondaryButtonProps extends IButtonProps {
text: string;
}
export default ISecondaryButtonProps;
|
JakeStanger/Reactive-Gallery
|
server/routes/location/Locations.ts
|
import { Request, Response } from "express";
import Location from "../../database/models/Location";
export const getLocations = async (req: Request, res: Response) => {
const locations = await Location.findAll();
return res.json(locations);
};
|
JakeStanger/Reactive-Gallery
|
src/pageContent/contact/TextDescription.tsx
|
<reponame>JakeStanger/Reactive-Gallery<filename>src/pageContent/contact/TextDescription.tsx
import React from "react";
import photo from "./photo.jpg";
const TextDescription: React.FC = () => (
<>
<img src={photo} alt={"<NAME>"} title={"<NAME>"} />
<p>Thank you for looking at my website.</p>
<p>
I have spent most of my life either in the countryside or beside the sea
and I am passionate about both. For over twenty years I worked alongside
anglers at a Site of Special Scientific Interest at Fordwich, as well as
several other fabulous venues in the Kent countryside. I have also fished
commercially off the Kent coast for bass for several years out of my own
boat (rod and line).
</p>
<p>
I am fortunate enough now to have enough time to pursue photography and
art which I can combine with my love of the outdoor life. I enjoy
landscape photography, with the early mornings when no one is about my
favourite time, along with astrophotography which gives me a real buzz; I
love the atmosphere and peace that only the small hours can give. I am
based just outside Canterbury and lucky enough to be surrounded by
beautiful rural countryside as well as a close distance to the sea.
</p>
</>
);
export default TextDescription;
|
JakeStanger/Reactive-Gallery
|
src/pages/gallery/controls/Controls.tsx
|
<filename>src/pages/gallery/controls/Controls.tsx
import React from "react";
import styles from "./Controls.module.scss";
import IControlsProps from "./IControlsProps";
import Visibility from "./visibility/Visibility";
import TextField from "../../../components/textField/TextField";
import Dropdown from "../../../components/dropdown/Dropdown";
const Controls: React.FC<IControlsProps> = props => (
<div className={styles.controls}>
<TextField
value={props.query}
onChange={props.onQueryChange}
placeholder={"Search"}
/>
<Dropdown
value={props.group}
onChange={props.onGroupChange}
placeholder={'Group By'}
options={[
{ key: "", value: "Group By" },
{ key: "taken_time", value: "Date" },
{ key: 'name', value: 'Name'},
{ key: 'location', value: 'Location'}
]}
/>
<Visibility
showLocation={props.showLocation}
showTime={props.showTime}
showDescription={props.showDescription}
showTags={props.showTags}
onChangeShowLocation={props.onChangeShowLocation}
onChangeShowTime={props.onChangeShowTime}
onChangeShowDescription={props.onChangeShowDescription}
onChangeShowTags={props.onChangeShowTags}
/>
</div>
);
export default React.memo(Controls);
|
JakeStanger/Reactive-Gallery
|
src/components/textField/TextField.tsx
|
<reponame>JakeStanger/Reactive-Gallery
import React from "react";
import styles from "./TextField.module.scss";
import ITextFieldProps from "./ITextFieldProps";
const TextField: React.FC<ITextFieldProps> = ({
value,
onChange,
placeholder
}) => {
return (
<div className={styles.textField}>
<input
placeholder={placeholder}
value={value}
onChange={ev => onChange(ev.target.value)}
/>
</div>
);
};
export default TextField;
|
JakeStanger/Reactive-Gallery
|
server/index.ts
|
<gh_stars>0
import express from "express";
import bodyParser from "body-parser";
import multer from "multer";
import Database from "./database";
import User from "./database/models/User";
import Image from "./database/models/Image";
import Location from "./database/models/Location";
import Tag from "./database/models/Tag";
import Event from "./database/models/Event";
import tokenChecker from "./tokenChecker";
import { getTags } from "./routes/tag/Tags";
import { getLocations } from "./routes/location/Locations";
import { getImages } from "./routes/image/Images";
import {
deleteImage,
getImageInfo,
getImageMarked,
getImageThumbnail,
patchImageInfo,
postImage
} from "./routes/image/Image";
import { getUser, login, signup } from "./routes/user/User";
import { getEvents } from "./routes/event/Events";
import { deleteEvent, patchEvent, postEvent } from "./routes/event/Event";
import PriceGroup from "./database/models/PriceGroup";
import Price from "./database/models/Price";
import { getPrices, getPricesForGroup } from "./routes/price/Prices";
import { getPriceGroups } from "./routes/priceGroup/PriceGroups";
import BasketItem from "./database/models/BasketItem";
import {
deleteBasketItem,
postBasketItem
} from "./routes/basketItem/BasketItem";
import { clearBasket, getBasket } from "./routes/basketItem/BasketItems";
import {
createCheckoutSession,
getCheckoutSession,
getClientPublic
} from "./routes/checkout/Checkout";
import { handleStripeWebhook } from "./routes/webhook/Webhook";
import morgan from "morgan";
import * as dotenv from "dotenv";
import Category from "./database/models/Category";
import { getCategories } from './routes/category/Categories';
dotenv.config();
// Database initialization
Database.get()
.init()
.then(() => {
User.load();
Image.load();
Category.load();
Location.load();
Tag.load();
Event.load();
PriceGroup.load();
Price.load();
BasketItem.load();
Image.belongsToMany(Category, {
through: "image_category",
foreignKey: "image_id",
as: "categories"
});
Image.belongsTo(Location, {
foreignKey: "location_key",
as: "location"
});
Image.belongsToMany(Tag, {
through: "image_tag",
foreignKey: "image_id",
as: "tags"
});
Image.belongsTo(PriceGroup, {
foreignKey: "price_group_id",
as: "priceGroup"
});
Category.belongsToMany(Image, {
through: "image_category",
foreignKey: "category_id",
as: "images",
constraints: false
});
Tag.belongsToMany(Image, {
through: "image_tag",
foreignKey: "tag_id",
as: "images",
constraints: false
});
Price.belongsTo(PriceGroup, {
foreignKey: "price_group_id",
as: "priceGroup"
});
BasketItem.belongsTo(Image, {
foreignKey: "image_id",
as: "image"
});
BasketItem.belongsTo(User, {
foreignKey: "user_id",
as: "user"
});
BasketItem.belongsTo(Price, {
foreignKey: "price_id",
as: "price"
});
if (process.env.DATABASE_DO_SYNC) {
console.log("syncing database...");
Database.getConnection()
.sync()
.then(() => console.log("database synced"))
.catch(console.error);
}
});
const app = express();
const router = express.Router();
// file uploading middleware
const upload = multer({
storage: multer.memoryStorage(),
limits: { fieldSize: Number.MAX_VALUE }
});
// Logging middleware
app.use(morgan("combined"));
// Use JSON parser middleware for all non-webhook routes
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === "/api/webhook") {
next();
} else {
bodyParser.json()(req, res, next);
}
}
);
// Error handling
app.use(
(
err: Error,
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
console.error(err.stack);
res.status(500).send({ message: "An internal server error has occured" });
}
);
// Add router middleware.
// This must be done after the app-level middleware!
app.use("/api", router);
// images
router.get("/image", getImages);
router.post("/image", tokenChecker, upload.single("file"), postImage);
router.get("/image/thumb/:filename", getImageThumbnail);
router.get("/image/:filename", getImageMarked);
router.get("/image/:id/info", getImageInfo);
router.patch("/image/:id/info", tokenChecker, patchImageInfo);
router.delete("/image/:id", tokenChecker, deleteImage);
// categories
router.get('/category', getCategories);
// tags and locations
router.get("/tag", getTags);
router.get("/location", getLocations);
// events
router.get("/event", getEvents);
router.post("/event/:id", tokenChecker, postEvent);
router.patch("/event/:id", tokenChecker, patchEvent);
router.delete("/event/:id", tokenChecker, deleteEvent);
// prices
router.get("/price", getPrices);
router.get("/price/group/:groupId", getPricesForGroup);
router.get("/pricegroup", getPriceGroups);
// account
router.post("/login", login);
router.post("/signup", signup);
router.get("/user", tokenChecker, getUser);
// basket
router.get("/basket", tokenChecker, getBasket);
router.post("/basket", tokenChecker, postBasketItem);
router.delete("/basket", tokenChecker, clearBasket);
router.delete("/basket/:basketItemId", tokenChecker, deleteBasketItem);
// checkout
router.get("/checkout/public", getClientPublic);
router.post("/checkout/secret", tokenChecker, createCheckoutSession);
router.get("/checkout/session/:sessionId", tokenChecker, getCheckoutSession);
router.post(
"/webhook",
bodyParser.raw({ type: "application/json" }),
handleStripeWebhook
);
// Auth check error handler
app.use((err: any, req: any, res: any, next: any) => {
if (err.name === "UnauthorizedError") {
res.status(401).json({ msg: err.message });
}
next(err);
});
app.listen(
parseInt(process.env.SERVER_PORT) || 9000,
process.env.SERVER_HOST || "127.0.0.1",
() => console.log(`Express listening on port ${process.env.SERVER_PORT}`)
);
|
JakeStanger/Reactive-Gallery
|
src/components/header/Header.tsx
|
<reponame>JakeStanger/Reactive-Gallery
import React, { useEffect, useState } from "react";
import styles from "./Header.module.scss";
import IHeaderProps from "./IHeaderProps";
import { NavLink } from "react-router-dom";
import UserService from "../../services/userService/UserService";
import IUser from "../../services/userService/IUser";
import { startCase } from "lodash";
const UserLabel: React.FC<{ userService: UserService }> = ({ userService }) => {
const [user, setUser] = useState<IUser | null>(null);
useEffect(() => {
userService.getCurrentUser().then(setUser);
}, [userService]);
return user ? (
<span className={styles.link}>Hi, {startCase(user.username)}</span>
) : (
<span />
);
};
const Header: React.FC<IHeaderProps> = ({ routes, userService }) => {
const next = new URLSearchParams(window.location.search).get("next");
return (
<nav className={styles.header}>
<div className={styles.left}>
{routes.map(route => (
<NavLink
key={route.name}
to={route.path}
className={styles.link}
activeClassName={styles.active}
>
{route.name}
</NavLink>
))}
</div>
<div className={styles.right}>
{userService.isLoggedIn() ? (
<>
<UserLabel userService={userService} />
<NavLink
to="/basket"
className={styles.link}
activeClassName={styles.active}
>
Basket
</NavLink>
<NavLink
to="/logout"
className={styles.link}
activeClassName={styles.active}
>
Log out
</NavLink>
</>
) : (
<>
<NavLink
to={"/login" + (next ? `?next=${next}` : "")}
className={styles.link}
activeClassName={styles.active}
>
Log in
</NavLink>
<NavLink
to={"/signup" + (next ? `?next=${next}` : "")}
className={styles.link}
activeClassName={styles.active}
>
Sign up
</NavLink>
</>
)}
</div>
</nav>
);
};
export default Header;
|
JakeStanger/Reactive-Gallery
|
server/routes/priceGroup/PriceGroups.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Request, Response } from "express";
import PriceGroup from "../../database/models/PriceGroup";
export const getPriceGroups = async (req: Request, res: Response) => {
const events = await PriceGroup.findAll();
return res.json(events);
};
|
JakeStanger/Reactive-Gallery
|
server/database/models/PriceGroup.ts
|
<reponame>JakeStanger/Reactive-Gallery<gh_stars>0
import { Model, DataTypes } from "sequelize";
import Database from "../index";
class PriceGroup extends Model {
public id: number;
public name: string;
public description: string;
public ratioWidth: number;
public ratioHeight: number;
public static load() {
PriceGroup.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true
},
description: DataTypes.TEXT,
ratioWidth: DataTypes.SMALLINT,
ratioHeight: DataTypes.SMALLINT
},
{
sequelize: Database.getConnection(),
tableName: "price_group"
}
);
}
public static async getFromObject(group: any): Promise<PriceGroup> {
return await PriceGroup.findOne({
where: { id: group.id }
});
}
}
export default PriceGroup;
|
JakeStanger/Reactive-Gallery
|
src/App.tsx
|
<filename>src/App.tsx
import React, { Suspense } from "react";
import Header from "./components/header/Header";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import UserService from "./services/userService/UserService";
import Login from "./pages/login/Login";
import IRoute from "./routes/IRoute";
import Preview from "./pages/preview/Preview";
import ScrollMemory from "react-router-scroll-memory";
import PageNotFound from "./pages/error/404";
import Basket from "./pages/basket/Basket";
import Success from "./pages/checkout/Success";
import Loader from "./components/loader/Loader";
import * as Sentry from "@sentry/react";
interface Props {
userService: UserService;
routes: IRoute[];
}
const App: React.FC<Props> = ({ userService, routes }) => {
const isLoggedIn = userService.isLoggedIn();
return (
<div className="Reactive-Portfolio">
<BrowserRouter>
<ScrollMemory />
<Header routes={routes} userService={userService} />
<Sentry.ErrorBoundary fallback={"An error has occurred"}>
<Suspense fallback={<Loader />}>
<Switch>
{routes.map(route => (
<Route
key={route.path}
path={route.path}
exact={route.exact}
component={route.component}
/>
))}
<Route path="/preview/:filename" component={Preview} />
{isLoggedIn ? (
<>
<Route path="/basket" component={Basket} />
<Route path="/checkout" component={Success} />
<Route
path="/logout"
component={() => {
userService.logout();
window.location.href = "/"; // Force refresh
return <span>You are now logged out</span>;
}}
/>
</>
) : (
<>
<Route
path="/login"
render={props => (
<Login {...props} userService={userService} />
)}
/>
<Route
path="/signup"
render={props => (
<Login {...props} userService={userService} signup />
)}
/>
</>
)}
<Route component={PageNotFound} />
</Switch>
</Suspense>
</Sentry.ErrorBoundary>
</BrowserRouter>
</div>
);
};
export default App;
|
JakeStanger/Reactive-Gallery
|
src/pages/login/ILoginProps.ts
|
<filename>src/pages/login/ILoginProps.ts
import UserService from "../../services/userService/UserService";
import { StaticContext, RouteComponentProps } from "react-router";
interface ILoginProps extends RouteComponentProps<any, StaticContext, any> {
userService: UserService;
signup?: boolean;
}
export default ILoginProps;
|
JakeStanger/Reactive-Gallery
|
server/routes/event/Event.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Request, Response } from "express";
import Event from "../../database/models/Event";
import User from "../../database/models/User";
export const postEvent = async (req: Request, res: Response) => {
if (!req.body || !req.body.name)
return res.status(400).json({ msg: "Missing body" });
const user = await User.findOne({ where: { id: (req.user as any).id } });
if (!user.canUpload) {
res.status(401).json({ msg: "Missing upload permissions" });
}
const event = await Event.getFromObject(req.body);
return res.status(201).json(event);
};
export const patchEvent = async (req: Request, res: Response) => {
if (!req.body || !Object.keys(req.body).length)
return res.status(400).json({ msg: "Missing body" });
const user = await User.findOne({ where: { id: (req.user as any).id } });
if (!user.canEdit) {
res.status(401).json({ msg: "Missing edit permissions" });
}
// Update name/description
await Event.update(req.body, {
where: { id: req.params.name }
});
};
export const deleteEvent = async(req: Request, res: Response) => {
};
|
JakeStanger/Reactive-Gallery
|
src/components/editForm/IEditFormState.ts
|
<reponame>JakeStanger/Reactive-Gallery
import ILocation from "../../services/imageService/ILocation";
import ITag from "../../services/imageService/ITag";
import IPriceGroup from "../../services/priceService/IPriceGroup";
import ICategory from '../../services/imageService/ICategory';
interface IEditPanelState {
name: string;
description: string;
categories: ICategory[];
location: [ILocation] | null;
tags: ITag[];
suggestedCategories: ICategory[];
suggestedTags: ITag[];
suggestedLocations: ILocation[];
priceGroup: IPriceGroup | undefined;
priceGroups: IPriceGroup[];
loading: boolean;
}
export default IEditPanelState;
|
JakeStanger/Reactive-Gallery
|
src/components/editForm/IEditFormProps.ts
|
<reponame>JakeStanger/Reactive-Gallery
import IImage from "../../services/imageService/IImage";
import { History } from "history";
interface IEditFormProps {
image: Partial<IImage>;
mode: "upload" | "edit";
file?: File;
onError?: (error: string) => void;
history: History;
}
export default IEditFormProps;
|
JakeStanger/Reactive-Gallery
|
server/database/models/Event.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Model, DataTypes } from "sequelize";
import Database from "../index";
class Event extends Model {
public id: number;
public name: string;
public location: string;
public startTime: Date;
public endTime: Date;
public static load() {
Event.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(255),
},
location: {
type: DataTypes.TEXT,
},
startTime: {
type: DataTypes.DATE
},
endTime: {
type: DataTypes.DATE
}
},
{
sequelize: Database.getConnection(),
tableName: "events"
}
);
}
public static async getFromObject(event: any): Promise<Event> {
return await Event.findOrCreate({
where: { id: event.id }
}).then(([event]) => event);
}
}
export default Event;
|
JakeStanger/Reactive-Gallery
|
src/pageContent/pricing/TextPreamble.tsx
|
<gh_stars>0
import React from "react";
const TextPreamble: React.FC = () => (
<>
<p>
Photos are grouped into pricing categories depending on their aspect
ratio. Each photo lists its group in its description. An order can be
placed through the Facebook shop or by email.
</p>
<p>
Canvases are now available. 3:2 (group 1) canvases can be ordered through the site; please contact us to discuss your
requirements for other size photos.
</p>
</>
);
export default TextPreamble;
|
JakeStanger/Reactive-Gallery
|
src/services/imageService/ImageService.ts
|
<reponame>JakeStanger/Reactive-Gallery
import IImage from "./IImage";
import UserService from "../userService/UserService";
import ITag from "./ITag";
import ICategory from './ICategory';
class ImageService {
private static _instance: ImageService;
private _userService: UserService;
private constructor() {
this._userService = UserService.getInstance();
}
public static getInstance(): ImageService {
if (ImageService._instance) return ImageService._instance;
else {
const instance = new ImageService();
ImageService._instance = instance;
return instance;
}
}
private _updateCache(images: IImage[]) {
sessionStorage.setItem("images", JSON.stringify(images));
}
private _tryGetFromCache(): IImage[] | null {
const images = sessionStorage.getItem("images");
if (images) return JSON.parse(images);
else return null;
}
private _clearCache() {
sessionStorage.removeItem("images");
}
public async get(id: number): Promise<IImage> {
return await fetch(`/api/image/${id}/info`).then(r => r.json());
}
public async update(image: Partial<IImage>) {
this._clearCache();
return await fetch(`/api/image/${image.id}/info`, {
method: "PATCH",
body: JSON.stringify(image),
headers: {
Authorization: `Bearer ${this._userService.getToken()}`,
"Content-Type": "application/json"
}
}).then(r => r.json());
}
public async delete(image: IImage) {
this._clearCache();
return await fetch(`/api/image/${image.id}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${this._userService.getToken()}`
}
}).then(r => r.json());
}
public async getAll(skipCache?: boolean): Promise<IImage[]> {
let images = !skipCache && this._tryGetFromCache();
if (!images) images = await fetch("/api/image").then(r => r.json());
if (images && !(images as any).msg) {
this._updateCache(images);
return images;
} else return [];
}
public getLink(image: IImage, full?: boolean) {
const jpeg = sessionStorage.getItem('supportsWebp') !== 'true';
let filename = image.filename;
if (jpeg) filename = filename.replace(/webp$/, "jpeg");
return `/api/image/${!full ? "thumb/" : ""}${filename}`;
}
public async upload(
file: File,
image: Partial<IImage>
): Promise<IImage | { msg: string }> {
const formData = new FormData();
formData.append("file", file);
formData.append("data", JSON.stringify(image));
const res = await fetch("/api/image", {
method: "POST",
body: formData,
headers: {
Authorization: `Bearer ${this._userService.getToken()}`
}
});
this._clearCache();
if (res.ok && res.status >= 200 && res.status < 300) return res.json();
else return { msg: await res.text() };
}
public async getCategories(): Promise<ICategory[]> {
return fetch(`/api/category`).then(r => r.json());
}
public async getTags(): Promise<ITag[]> {
return fetch(`/api/tag`).then(r => r.json());
}
public async getLocations(): Promise<ITag[]> {
return fetch(`/api/location`).then(r => r.json());
}
}
export default ImageService;
|
JakeStanger/Reactive-Gallery
|
src/services/userService/IUser.ts
|
import IPermissionSet from "./IPermissionSet";
interface IUser {
username: string;
email: string;
permissions: IPermissionSet;
}
export default IUser;
|
JakeStanger/Reactive-Gallery
|
src/routes/Routes.tsx
|
<reponame>JakeStanger/Reactive-Gallery
import IRoute from "./IRoute";
import Contact from "../pages/contact/Contact";
import Pricing from "../pages/pricing/Pricing";
import Gallery from "../pages/gallery/Gallery";
import Events from "../pages/events/Events";
import Reports from "../pages/reports/Reports";
import { lazy } from "react";
const routes: IRoute[] = [
{
name: "Home",
path: "/",
component: Gallery,
exact: true
},
{
name: "Contact & About",
path: "/contact",
component: Contact,
},
{
name: "Pricing",
path: "/pricing",
component: Pricing,
},
{
name: "Events",
path: "/events",
component: Events,
},
{
name: "Upload",
path: "/upload",
component: lazy(() => import('../pages/upload/Upload')),
permissions: {upload: true}
},
{
name: "Reports",
path: "/reports",
component: Reports,
permissions: {edit: true}
}
];
export default routes;
|
JakeStanger/Reactive-Gallery
|
server/routes/tag/Tags.ts
|
<filename>server/routes/tag/Tags.ts
import { Response, Request } from "express";
import Tag from "../../database/models/Tag";
import Image from "../../database/models/Image";
export const getTags = async (req: Request, res: Response) => {
const tags = await Tag.findAll({ include: [{ model: Image, as: "images" }] });
const usedTags = tags.filter(tag => tag.images.length > 0);
return res.json(usedTags.map(t => ({ id: t.id, name: t.name })));
};
|
JakeStanger/Reactive-Gallery
|
src/components/button/secondary/SecondaryButton.tsx
|
import React from 'react';
import styles from '../Button.module.scss';
import ISecondaryButtonProps from './ISecondaryButtonProps';
const SecondaryButton: React.FC<ISecondaryButtonProps> = ({onClick, disabled, text}) => {
return (
<button className={`${styles.button}`} onClick={onClick} disabled={disabled}>
{text}
</button>
);
};
export default SecondaryButton;
|
JakeStanger/Reactive-Gallery
|
src/pages/upload/IUploadState.ts
|
interface IUploadState {
file: File | null;
error?: string;
}
export default IUploadState;
|
JakeStanger/Reactive-Gallery
|
src/react-router-scroll-memory.d.ts
|
declare module "react-router-scroll-memory";
|
JakeStanger/Reactive-Gallery
|
src/pages/contact/Contact.tsx
|
import React from "react";
import styles from "./Contact.module.scss";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEnvelope } from "@fortawesome/free-solid-svg-icons";
import {
faPaypal,
faFacebook,
faInstagram
} from "@fortawesome/free-brands-svg-icons";
import config from "../../config.json";
import css from "../../styles/css";
import TextPreamble from "../../pageContent/contact/TextPreamble";
import TextDescription from "../../pageContent/contact/TextDescription";
import { ReactComponent as IconRedbubble } from "./redbubble.svg";
// const faRedbubble: IconDefinition = {
// prefix: "fas",
// iconName: "mycar" as any,
// icon: [
// 512,
// 512,
// [],
// "f0000",
// iconRedbubble
// ]
// };
// library.add(faRedbubble);
const Contact: React.FC = () => (
<div className={styles.container}>
<div className={styles.title}>Contact</div>
<div className={styles.links}>
<div className={styles.link}>
<a href={`mailto:${config.contact.email}`}>
<FontAwesomeIcon icon={faEnvelope} style={{ width: "unset" }} />
<div className={styles.label}>Email</div>
</a>
</div>
<div className={styles.link}>
<a
href={config.contact.facebook}
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon icon={faFacebook} style={{ width: "unset" }} />
<div className={styles.label}>Facebook</div>
</a>
</div>
<div className={styles.link}>
<a
href={config.contact.instagram}
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon icon={faInstagram} style={{ width: "unset" }} />
<div className={styles.label}>Instagram</div>
</a>
</div>
<div className={styles.link}>
<a
href={config.contact.paypal}
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon icon={faPaypal} style={{ width: "unset" }} />
<div className={styles.label}>PayPal</div>
</a>
</div>
<div className={styles.link}>
<a
href={config.contact.redbubble}
target="_blank"
rel="noopener noreferrer"
>
<IconRedbubble
style={{
width: "unset",
overflow: "visible",
display: "inline-block",
fontSize: 'inherit',
height: '1em'
}}
/>
<div className={styles.label}>Redbubble</div>
</a>
</div>
</div>
<div className={styles.text}>
<TextPreamble />
</div>
<div className={css(styles.text, styles.biography)}>
<TextDescription />
</div>
</div>
);
export default Contact;
|
JakeStanger/Reactive-Gallery
|
src/pages/gallery/controls/visibility/IVisibilityProps.ts
|
<reponame>JakeStanger/Reactive-Gallery<filename>src/pages/gallery/controls/visibility/IVisibilityProps.ts<gh_stars>0
interface IVisibilityProps {
showLocation: boolean;
showTime: boolean;
showDescription: boolean;
showTags: boolean;
onChangeShowLocation: (show: boolean) => void;
onChangeShowTime: (show: boolean) => void;
onChangeShowDescription: (show: boolean) => void;
onChangeShowTags: (show: boolean) => void;
}
export default IVisibilityProps;
|
JakeStanger/Reactive-Gallery
|
src/components/header/IHeaderProps.ts
|
import IRoute from "../../routes/IRoute";
import UserService from "../../services/userService/UserService";
interface IHeaderProps {
routes: IRoute[];
userService: UserService;
}
export default IHeaderProps;
|
JakeStanger/Reactive-Gallery
|
src/components/button/primary/PrimaryButton.tsx
|
import React from "react";
import styles from "../Button.module.scss";
import IPrimaryButtonProps from "./IPrimaryButtonProps";
const PrimaryButton: React.FC<IPrimaryButtonProps> = ({ onClick, text, disabled }) => {
return (
<button className={`${styles.button} ${styles.primary}`} onClick={onClick} disabled={disabled}>
{text}
</button>
);
};
export default PrimaryButton;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/IPreviewProps.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { RouteComponentProps, StaticContext } from "react-router";
interface IPreviewProps extends RouteComponentProps<any, StaticContext, any> {
}
export default IPreviewProps;
|
JakeStanger/Reactive-Gallery
|
src/services/priceService/PriceService.ts
|
<gh_stars>0
import IPrice from "./IPrice";
import IPriceGroup from "./IPriceGroup";
class PriceService {
private static _instance: PriceService;
public static getInstance(): PriceService {
if (PriceService._instance) return PriceService._instance;
else {
const instance = new PriceService();
PriceService._instance = instance;
return instance;
}
}
public async getAllPrices(): Promise<IPrice[]> {
const prices = await fetch("/api/price").then(r => r.json());
if (prices && !(prices as any).msg) {
return prices;
} else {
console.error(prices);
return [];
}
}
public async getPricesForGroup(group: IPriceGroup): Promise<IPrice[]> {
const prices = await fetch(`/api/price/group/${group.id}`).then(r =>
r.json()
);
if (prices && !(prices as any).msg) {
return prices;
} else {
console.error(prices);
return [];
}
}
public async getAllPriceGroups(): Promise<IPriceGroup[]> {
const priceGroups = await fetch("/api/pricegroup").then(r => r.json());
if (priceGroups && !(priceGroups as any).msg) {
return priceGroups;
} else {
console.error(priceGroups);
return [];
}
}
}
export default PriceService;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/previewInfo/basketDialog/IBasketDialogProps.ts
|
<gh_stars>0
import IImage from "../../../../services/imageService/IImage";
import IPrice from "../../../../services/priceService/IPrice";
import { History } from 'history';
interface IBasketDialogProps {
onDismiss: () => void;
image: IImage;
prices: IPrice[];
history: History
}
export default IBasketDialogProps;
|
JakeStanger/Reactive-Gallery
|
server/routes/event/Events.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Request, Response } from "express";
import Event from "../../database/models/Event";
import { Op } from "sequelize";
export const getEvents = async (req: Request, res: Response) => {
const events = await Event.findAll({
where: { endTime: { [Op.gt]: new Date() } },
order: ["startTime"]
});
return res.json(events);
};
|
JakeStanger/Reactive-Gallery
|
src/components/button/icon/IIconButtonProps.ts
|
import IButtonProps from "../IButtonProps";
interface IIconButtonProps extends IButtonProps {
}
export default IIconButtonProps;
|
JakeStanger/Reactive-Gallery
|
src/pages/reports/IReportsProps.ts
|
import { RouteComponentProps } from "react-router-dom";
interface IReportsProps {
}
export default IReportsProps;
|
JakeStanger/Reactive-Gallery
|
server/database/models/User.ts
|
import { Model, DataTypes } from "sequelize";
import Database from "../index";
class User extends Model {
public id: number;
public username: string;
public email: string;
public password: string;
public canEdit: boolean;
public canUpload: boolean;
public static load() {
User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
username: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
canEdit: {
type: DataTypes.BOOLEAN
},
canUpload: {
type: DataTypes.BOOLEAN
}
},
{
sequelize: Database.getConnection(),
tableName: "users"
}
);
}
}
export default User;
|
JakeStanger/Reactive-Gallery
|
src/pages/gallery/controls/visibility/Visibility.tsx
|
import React, { useState } from "react";
import styles from "./Visibility.module.scss";
import IVisibilityProps from "./IVisibilityProps";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faChevronRight,
faChevronLeft
} from "@fortawesome/free-solid-svg-icons";
import Checkbox from "../../../../components/checkbox/Checkbox";
const Visibility: React.FC<IVisibilityProps> = props => {
const [expanded, setExpanded] = useState(false);
return (
<div className={styles.visibility}>
<button className={styles.moreBtn} onClick={() => setExpanded(!expanded)}>
{!expanded ? (
<div className={styles.label}>
<div>More</div>
<FontAwesomeIcon className={styles.arrow} icon={faChevronRight} />
</div>
) : (
<div className={styles.label}>
<div>Less</div>
<FontAwesomeIcon className={styles.arrow} icon={faChevronLeft} />
</div>
)}
</button>
{expanded && (
<div className={styles.more}>
<Checkbox
checked={props.showLocation}
onChange={props.onChangeShowLocation}
label={"Show location"}
/>
<Checkbox
checked={props.showTime}
onChange={props.onChangeShowTime}
label={"Show time"}
/>
<Checkbox
checked={props.showDescription}
onChange={props.onChangeShowDescription}
label={"Show description"}
/>
<Checkbox
checked={props.showTags}
onChange={props.onChangeShowTags}
label={"Show tags"}
/>
</div>
)}
</div>
);
};
export default React.memo(Visibility);
|
JakeStanger/Reactive-Gallery
|
src/services/userService/IPermissionSet.ts
|
interface IPermissionSet {
edit: boolean;
upload: boolean;
}
export default IPermissionSet;
|
JakeStanger/Reactive-Gallery
|
src/pages/basket/Basket.tsx
|
<reponame>JakeStanger/Reactive-Gallery<gh_stars>0
import React, { useCallback, useEffect, useState } from "react";
import styles from "./Basket.module.scss";
import BasketService from "../../services/basketService/BasketService";
import IBasketItem from "../../services/basketService/IBasketItem";
import Card from "../../components/card/Card";
import ImageService from "../../services/imageService/ImageService";
import Masonry from "react-masonry-component";
import { loadStripe, Stripe, StripeError } from "@stripe/stripe-js";
import PrimaryButton from "../../components/button/primary/PrimaryButton";
import CheckoutService from "../../services/checkoutService/CheckoutService";
import Dialog from "../../components/dialog/Dialog";
import SecondaryButton from "../../components/button/secondary/SecondaryButton";
import { RouteComponentProps } from "react-router-dom";
function getBasketTotal(basket: IBasketItem[]) {
if (!basket.length) return 0;
return basket
.map(
item =>
(item.framed ? item.price.framed : item.price.unframed) * item.quantity
)
.reduce((total, price) => total + price);
}
const Basket: React.FC<RouteComponentProps> = ({ history }) => {
const [basket, setBasket] = useState<IBasketItem[]>([]);
const [stripePromise, setStripePromise] = useState<
Promise<Stripe | null> | undefined
>(undefined);
const [deleteItem, setDeleteItem] = useState<IBasketItem | undefined | null>(
undefined
);
const [showBasketDialog, setShowBasketDialog] = useState(false);
const [error, setError] = useState<Error | StripeError | undefined>();
useEffect(() => {
CheckoutService.getInstance()
.getPublicKey()
.then(key => setStripePromise(loadStripe(key)));
}, []);
const onDelete = useCallback(() => {
if (deleteItem === undefined) return;
const basketService = BasketService.getInstance();
if (deleteItem) {
basketService
.removeFromBasket(deleteItem)
.then(() => setBasket(basket.filter(item => item.id !== deleteItem.id)))
.catch(console.error);
} else {
basketService
.emptyBasket()
.then(() => setBasket([]))
.catch(console.error);
}
setDeleteItem(undefined);
}, [basket, deleteItem]);
const onSetDeleteItem = useCallback(
(basketItem: IBasketItem | undefined | null) => {
setDeleteItem(basketItem);
},
[]
);
const onCheckout = useCallback(
async (post: boolean) => {
const sessionId = await CheckoutService.getInstance().getSecretKey(post);
const stripe = await stripePromise;
if (!stripe) {
const err = new Error(
"Stripe is not configured correctly on the client. This is our fault, not yours, so please let us know."
);
console.error(err);
setError(err);
return;
}
const { error } = await stripe!.redirectToCheckout({
sessionId
});
if (error) {
console.error(error);
setError(error);
}
},
[stripePromise]
);
React.useEffect(() => {
BasketService.getInstance()
.getBasket()
.then(basketItems => {
if ((basketItems as { msg: string }).msg) {
throw new Error((basketItems as { msg: string }).msg);
} else {
setBasket(basketItems as IBasketItem[]);
}
});
}, []);
const onCheckoutDialog = useCallback(() => {
setShowBasketDialog(true);
}, []);
const GREETINGS_CARDS_GROUP = 1000;
const cannotPost = !!basket.find(
item =>
(item.framed && item.price.price_group_id !== GREETINGS_CARDS_GROUP) ||
!item.price.postage
);
return (
<div className={styles.container}>
{error && <div className={styles.error}>{error.message}</div>}
<div className={styles.subTitle}>Basket</div>
<div className={styles.basket}>
{basket.length ? (
<>
<div className={styles.controls}>
<div>Basket Total: £{getBasketTotal(basket)}</div>
<PrimaryButton onClick={onCheckoutDialog} text={"Checkout"} />
<PrimaryButton
onClick={() => history.push("/")}
text={"Add more"}
/>
<SecondaryButton
onClick={() => onSetDeleteItem(null)}
text={"Empty basket"}
/>
</div>
<Masonry className={styles.cards}>
{basket.map(item => (
<Card
key={item.id}
image={item.image}
imageService={ImageService.getInstance()}
height={item.image.height * (360 / item.image.width)}
showLocation={false}
showTags={false}
showDescription={false}
showTime={false}
showPriceInfo={true}
basketItem={item}
onDelete={onSetDeleteItem}
/>
))}
</Masonry>
</>
) : (
<div>
Your basket is empty right now. Go to the gallery and add some then
check out here.
</div>
)}
</div>
<Dialog
isOpen={deleteItem !== undefined}
onDismiss={() => onSetDeleteItem(undefined)}
>
<div className={styles.subSubTitle}>Are you sure?</div>
<div>
{deleteItem !== null
? "Are you sure you want to delete this order from your basket?"
: "Are you sure you want to empty your basket? This will remove all orders."}
</div>
<PrimaryButton text={"Delete"} onClick={onDelete} />
<SecondaryButton
text={"Cancel"}
onClick={() => onSetDeleteItem(undefined)}
/>
</Dialog>
<Dialog
isOpen={showBasketDialog}
onDismiss={() => setShowBasketDialog(false)}
>
<div className={styles.subSubTitle}>Checkout</div>
<div>
Collection/local delivery is available. Please contact us if you wish
to arrange delivery; we ask that you pay a small delivery fee using
PayPal or cash on collection.
</div>
{cannotPost && (
<div>
Your basket contains one or more framed prints of canvases, which we
are unfortunately unable to post.
</div>
)}
<PrimaryButton
onClick={() => onCheckout(true)}
text={"Post"}
disabled={cannotPost}
/>
<PrimaryButton
onClick={() => onCheckout(false)}
text={"Collect/Deliver"}
/>
</Dialog>
</div>
);
};
export default Basket;
|
JakeStanger/Reactive-Gallery
|
server/routes/user/User.ts
|
<reponame>JakeStanger/Reactive-Gallery<filename>server/routes/user/User.ts
import { Request, Response } from "express";
import User from "../../database/models/User";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
function signJwt(user: User) {
return jwt.sign({ id: user.id }, process.env.SESSION_SECRET, {
expiresIn: process.env.TOKEN_LIFE
});
}
export const login = async (req: Request, res: Response) => {
if (!req.body.username)
return res.status(400).json({ msg: "Missing username" });
if (!req.body.password)
return res.status(400).json({ msg: "Missing password" });
const user = await User.findOne({ where: { username: req.body.username } });
if (!user) return res.status(401).json({ msg: "Incorrect username" });
const passwordIsValid = <PASSWORD>.compareSync(req.body.password, user.password);
if (!passwordIsValid)
return res.status(401).json({ msg: "Incorrect password" });
const accessToken = signJwt(user);
return res.status(200).send({ accessToken });
};
export const signup = async (req: Request, res: Response) => {
if (!req.body.username)
return res.status(400).json({ msg: "Missing username" });
if (!req.body.password)
return res.status(400).json({ msg: "Missing password" });
const user = await User.create({
username: req.body.username,
email: req.body.email,
password: <PASSWORD>(<PASSWORD>.body.password)
});
const accessToken = signJwt(user);
return res.status(201).send({ accessToken });
};
export const getUser = async (req: Request, res: Response) => {
const user = (req as any).user;
if (user && user.id) {
const dbUser = await User.findOne({ where: { id: user.id } });
if (dbUser)
return res.json({
username: dbUser.username,
email: dbUser.email,
permissions: {
edit: dbUser.canEdit,
upload: dbUser.canUpload
}
});
}
return res.status(400).json({ msg: "User not found" });
};
|
JakeStanger/Reactive-Gallery
|
src/services/settingsService/SettingsService.ts
|
class SettingsService {
private _getBool(keyName: string, def: any) {
const value = localStorage.getItem(keyName);
if (value === null) return def;
else return value === "true";
}
public getShowLocation() {
return this._getBool("showLocation", true);
}
public setShowLocation(show: boolean) {
localStorage.setItem("showLocation", show.toString());
}
public getShowTime() {
return this._getBool("showTime", true);
}
public setShowTime(show: boolean) {
localStorage.setItem("showTime", show.toString());
}
public getShowDescription() {
return this._getBool("showDescription", true);
}
public setShowDescription(show: boolean) {
localStorage.setItem("showDescription", show.toString());
}
public getShowTags() {
return this._getBool("showTags", false);
}
public setShowTags(show: boolean) {
localStorage.setItem("showTags", show.toString());
}
}
export default SettingsService;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/previewInfo/editPanel/IEditPanelProps.ts
|
import IImage from "../../../../services/imageService/IImage";
import { History } from "history";
interface IEditPanelProps {
isOpen: boolean;
onDismiss: () => void;
image: IImage;
history: History;
}
export default IEditPanelProps;
|
JakeStanger/Reactive-Gallery
|
src/pages/error/404.tsx
|
<filename>src/pages/error/404.tsx<gh_stars>0
import React from "react";
import styles from "./error.module.scss";
const PageNotFound: React.FC = () => (
<div className={styles.container}>
<div className={styles.subTitle}>Error 404</div>
<div>
The page you tried to navigate to cannot be found. If you typed the
address, check it for any mistakes. If another page took you here, please
contact us with details. Click{" "}
<span className={styles.link} onClick={() => window.history.back()}>here</span> to go back.
</div>
</div>
);
export default PageNotFound;
|
JakeStanger/Reactive-Gallery
|
server/database/models/Category.ts
|
<gh_stars>0
import { DataTypes, Model } from "sequelize";
import Image from "./Image";
import Database from "../index";
class Category extends Model {
public id: number;
public name: string;
public images?: Image[];
public static load() {
Category.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(128),
unique: true
}
},
{
sequelize: Database.getConnection(),
tableName: "categories"
}
);
}
public static async getFromArray(categories: any[]) {
return await Promise.all(
categories.map(
(categoryData: Category) =>
new Promise<Category>(resolve => {
Category.findOrCreate({
where: { name: categoryData.name }
}).then(([category]) => resolve(category));
})
)
);
}
}
export default Category;
|
JakeStanger/Reactive-Gallery
|
src/routes/IRoute.ts
|
<filename>src/routes/IRoute.ts
import { RouteComponentProps } from "react-router-dom";
import IPermissionSet from "../services/userService/IPermissionSet";
interface IRoute {
name: string;
path: string;
component: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>;
exact?: boolean;
permissions?: Partial<IPermissionSet>;
}
export default IRoute;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/previewInfo/editPanel/EditPanel.tsx
|
<filename>src/pages/preview/previewInfo/editPanel/EditPanel.tsx<gh_stars>0
import React from "react";
import styles from "./EditPanel.module.scss";
import IEditPanelProps from "./IEditPanelProps";
import css from "../../../../styles/css";
import { faTimes } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import EditForm from "../../../../components/editForm/EditForm";
const EditPanel: React.FC<IEditPanelProps> = props => {
const { isOpen, onDismiss, image } = props;
return (
<div className={css(styles.panel, !isOpen && styles.closed)}>
<div className={styles.closeBtn} onClick={onDismiss}>
<FontAwesomeIcon icon={faTimes} />
</div>
<div className={styles.content}>
<div className={styles.subTitle}>{image.name}</div>
<EditForm image={image} mode="edit" history={props.history} />
</div>
</div>
);
};
export default EditPanel;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/previewInfo/PreviewInfo.tsx
|
import React, { useEffect, useState } from "react";
import styles from "./PreviewInfo.module.scss";
import IPreviewInfoProps from "./IPreviewInfoProps";
import { DateTime } from "luxon";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPencilAlt } from "@fortawesome/free-solid-svg-icons";
import EditPanel from "./editPanel/EditPanel";
import UserService from "../../../services/userService/UserService";
import BasketDialog from "./basketDialog/BasketDialog";
import PrimaryButton from "../../../components/button/primary/PrimaryButton";
import PriceTable from "../../pricing/priceTable/PriceTable";
import PriceService from "../../../services/priceService/PriceService";
import IPrice from "../../../services/priceService/IPrice";
import { Link } from "react-router-dom";
import Fraction from "fraction.js";
const PreviewInfo: React.FC<IPreviewInfoProps> = ({ image, user, history }) => {
const [editing, setEditing] = useState(false);
const [showBasketDialog, setShowBasketDialog] = useState(false);
const [prices, setPrices] = useState<IPrice[]>([]);
useEffect(() => {
if (image.priceGroup) {
PriceService.getInstance()
.getPricesForGroup(image.priceGroup)
.then(prices => {
setPrices(prices);
});
}
}, [image.priceGroup]);
return (
<div className={styles.container}>
{user && user.permissions && user.permissions.edit && (
<>
<div className={styles.buttons}>
<div className={styles.button} onClick={() => setEditing(!editing)}>
<FontAwesomeIcon icon={faPencilAlt} />
</div>
</div>
<EditPanel
isOpen={editing}
onDismiss={() => setEditing(false)}
image={image}
history={history}
/>
</>
)}
<div className={styles.subTitle}>{image.name}</div>
<div className={styles.description}>{image.description}</div>
{!!image.categories?.length && (
<div>
<b>Categories</b>: {image.categories.map(c => c.name).join(", ")}
</div>
)}
{image.location && (
<div>
<b>Location</b>: {image.location.name}
</div>
)}
{image.tags && (
<div className={styles.tags}>
{image.tags.map(tag => (
<Link
key={tag.id}
className={styles.tag}
to={{
pathname: "/",
search: `q=${tag.name}`
}}
>
{tag.name}
</Link>
))}
</div>
)}
{image.priceGroup && (
<PrimaryButton
text={"Add to Basket"}
onClick={() => {
if (UserService.getInstance().isLoggedIn()) {
setShowBasketDialog(!showBasketDialog);
} else {
history.push(`/login?next=${window.location.pathname}`);
}
}}
/>
)}
<div className={styles.row}>
<div className={`${styles.infoTechnical} ${styles.mobileCentre}`}>
<div className={`${styles.subSubTitle} ${styles.posLeft}`}>
Technical Information
</div>
<table>
<tbody>
<tr className={styles.tableRow}>
<td>Time Taken</td>
<td>
{DateTime.fromISO(image.timeTaken).toFormat(
"dd/MM/yyyy HH:mm"
)}
</td>
</tr>
<tr className={styles.tableRow}>
<td>Dimensions</td>
<td>
{image.width} x {image.height}
</td>
</tr>
<tr className={styles.tableRow}>
<td>Exposure</td>
<td>{new Fraction(image.exposure).toFraction(true)}s</td>
</tr>
<tr className={styles.tableRow}>
<td>Focal Length</td>
<td>{image.focalLength}mm</td>
</tr>
<tr className={styles.tableRow}>
<td>Aperture</td>
<td>f/{image.aperture}</td>
</tr>
<tr className={styles.tableRow}>
<td>ISO</td>
<td>{image.iso}</td>
</tr>
</tbody>
</table>
</div>
{image.priceGroup && (
<div>
<div className={`${styles.subSubTitle} ${styles.posRight}`}>
Pricing ({image.priceGroup.name})
</div>
<PriceTable
group={image.priceGroup}
prices={prices || []}
className={`${styles.pushRight} ${styles.mobileCentre}`}
/>
</div>
)}
{showBasketDialog && (
<BasketDialog
onDismiss={() => setShowBasketDialog(false)}
image={image}
prices={prices}
history={history}
/>
)}
</div>
</div>
);
};
export default PreviewInfo;
|
JakeStanger/Reactive-Gallery
|
server/routes/category/Categories.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Request, Response } from "express";
import Image from "../../database/models/Image";
import Category from "../../database/models/Category";
export const getCategories = async (req: Request, res: Response) => {
const categories = await Category.findAll({
include: [{ model: Image, as: "images" }]
});
return res.json(categories.map(t => ({ id: t.id, name: t.name })));
};
|
JakeStanger/Reactive-Gallery
|
src/components/dialog/IDialogProps.ts
|
<gh_stars>0
interface IDialogProps {
isOpen: boolean;
onDismiss: () => void;
}
export default IDialogProps;
|
JakeStanger/Reactive-Gallery
|
src/components/button/icon/IconButton.tsx
|
import React from 'react';
import styles from './IconButton.module.scss';
import IIconButtonProps from './IIconButtonProps';
const IconButton: React.FC<IIconButtonProps> = () => {
return (
<span />
);
};
export default IconButton;
|
JakeStanger/Reactive-Gallery
|
src/pages/gallery/Gallery.tsx
|
import React from "react";
import styles from "./Gallery.module.scss";
import IGalleryState from "./IGalleryState";
import ImageService from "../../services/imageService/ImageService";
import Loader from "../../components/loader/Loader";
import Card from "../../components/card/Card";
import Masonry, { MasonryOptions } from "react-masonry-component";
import Controls from "./controls/Controls";
import IImage from "../../services/imageService/IImage";
import { groupBy, memoize } from "lodash";
import { DateTime } from "luxon";
import SettingsService from "../../services/settingsService/SettingsService";
import { forceCheck } from "react-lazyload";
import { RouteComponentProps, withRouter } from "react-router-dom";
const getMasonryStyle = memoize((width: number) => ({ width }));
class Gallery extends React.PureComponent<RouteComponentProps, IGalleryState> {
private readonly _imageService: ImageService;
private _settingsService: SettingsService;
private static readonly MasonryOptions: MasonryOptions = {
transitionDuration: 250
};
constructor(props: RouteComponentProps) {
super(props);
this._imageService = ImageService.getInstance();
const settingsService = new SettingsService();
this._settingsService = settingsService;
this.state = {
loading: true,
images: [],
showLocation: settingsService.getShowLocation(),
showTime: settingsService.getShowTime(),
showDescription: settingsService.getShowDescription(),
showTags: settingsService.getShowTags(),
query: Gallery.getQuery(props),
group: "",
width: Gallery._getWidth()
};
}
public static getQuery(props: RouteComponentProps) {
return new URLSearchParams(props.location.search).get("q") || "";
}
private static _getWidth() {
return (360 + 20) * Math.floor(window.innerWidth / (360 + 20));
}
private _updateWidth = () => {
this.setState({ width: Gallery._getWidth() });
};
public componentDidMount() {
this.setState({ loading: true });
this._imageService
.getAll()
.then(images => this.setState({ images, loading: false }));
window.addEventListener("resize", this._updateWidth);
}
public componentWillUnmount() {
window.removeEventListener("resize", this._updateWidth);
}
public componentWillReceiveProps(
nextProps: Readonly<RouteComponentProps>,
nextContext: any
) {
if (
Gallery.getQuery(nextProps) &&
Gallery.getQuery(nextProps) !== Gallery.getQuery(this.props)
) {
this.setState({ query: Gallery.getQuery(nextProps) });
}
}
private _updateQuery = (query: string) => {
this.setState({ query });
this.props.history.replace(`/?q=${query}`);
};
private _updateGroup = (group: string) => {
this.setState({ group });
};
private _updateShowLocation = (showLocation: boolean) => {
this.setState({ showLocation });
this._settingsService.setShowLocation(showLocation);
};
private _updateShowTime = (showTime: boolean) => {
this.setState({ showTime });
this._settingsService.setShowTime(showTime);
};
private _updateShowDescription = (showDescription: boolean) => {
this.setState({ showDescription });
this._settingsService.setShowDescription(showDescription);
};
private _updateShowTags = (showTags: boolean) => {
this.setState({ showTags });
this._settingsService.setShowTags(showTags);
};
private _getSortedGroups(groups: string[]) {
return groups.sort((a, b) => {
switch (this.state.group) {
case "taken_time":
return DateTime.fromISO(a)
.diff(DateTime.fromISO(b))
.as("months");
default:
return (a !== "null" && a !== "No Location"
? a
: "zzz"
).localeCompare(b !== "null" && b !== "No Location" ? b : "zzz");
}
});
}
private _getFilteredImages(images: IImage[]) {
const query = this.state.query.toLowerCase();
return images.filter(
image =>
!query ||
(image.name && image.name.toLowerCase().indexOf(query) > -1) ||
(image.location &&
image.location.name.toLowerCase().indexOf(query) > -1) ||
(image.description &&
image.description.toLowerCase().indexOf(query) > -1) ||
(image.tags &&
image.tags
.map(t => t.name)
.join("")
.toLowerCase()
.indexOf(query) > -1)
);
}
private _getGroupedImages() {
const { group } = this.state;
const images = this._getFilteredImages(this.state.images);
return groupBy(images, image => {
switch (group) {
case "taken_time":
// Group by month
const date = DateTime.fromISO(image.timeTaken);
return date.isValid ? date.toFormat("MMMM yyyy") : "No Date";
case "name":
// Group by first letter
return image.name.trim()[0].toUpperCase();
case "location":
return image.location ? image.location.name : "No Location";
default:
return "";
}
});
}
private static _onLayoutComplete() {
setTimeout(forceCheck, 100);
}
public render() {
const {
loading,
showLocation,
showTime,
showDescription,
showTags,
query,
group,
width
} = this.state;
const groupedImages = this._getGroupedImages();
return (
<div>
{loading && <Loader />}
<Controls
showLocation={showLocation}
onChangeShowLocation={this._updateShowLocation}
showTime={showTime}
onChangeShowTime={this._updateShowTime}
showDescription={showDescription}
onChangeShowDescription={this._updateShowDescription}
showTags={showTags}
onChangeShowTags={this._updateShowTags}
query={query}
onQueryChange={this._updateQuery}
group={group}
onGroupChange={this._updateGroup}
/>
<div className={styles.galleryContainer}>
{this._getSortedGroups(Object.keys(groupedImages)).map(groupName => (
<div className={styles.group} key={groupName}>
<div className={styles.subTitle}>{groupName}</div>
<Masonry
className={styles.cards}
style={getMasonryStyle(width)}
onLayoutComplete={Gallery._onLayoutComplete}
options={Gallery.MasonryOptions}
>
{groupedImages[groupName].map(image => (
<Card
key={image.filename}
imageService={this._imageService}
image={image}
height={image.height * (360 / image.width)}
showLocation={this.state.showLocation}
showTime={this.state.showTime}
showTags={this.state.showTags}
showDescription={this.state.showDescription}
query={query}
/>
))}
</Masonry>
</div>
))}
</div>
</div>
);
}
}
export default withRouter(Gallery);
|
JakeStanger/Reactive-Gallery
|
server/routes/image/Images.ts
|
<reponame>JakeStanger/Reactive-Gallery
import { Request, Response } from "express";
import Location from "../../database/models/Location";
import Tag from "../../database/models/Tag";
import Image from "../../database/models/Image";
import { Op } from "sequelize";
import Category from "../../database/models/Category";
export const getImages = async (req: Request, res: Response) => {
const images = await Image.findAll({
where: { deleted: { [Op.or]: [0, null] } },
include: [
{ model: Category, as: "categories" },
{ model: Location, as: "location" },
{ model: Tag, as: "tags" }
],
order: [["timeTaken", "DESC"]]
});
return res.json(images);
};
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/IPreviewState.ts
|
import IImage from "../../services/imageService/IImage";
import IUser from "../../services/userService/IUser";
interface IPreviewState {
image: IImage | null;
user: IUser | null;
}
export default IPreviewState;
|
JakeStanger/Reactive-Gallery
|
src/pages/preview/previewInfo/IPreviewInfoProps.ts
|
<filename>src/pages/preview/previewInfo/IPreviewInfoProps.ts
import IImage from "../../../services/imageService/IImage";
import IUser from "../../../services/userService/IUser";
import { History } from 'history';
interface IPreviewInfoProps {
image: IImage;
user: IUser | null;
history: History;
}
export default IPreviewInfoProps;
|
JakeStanger/Reactive-Gallery
|
src/pages/login/Login.tsx
|
<reponame>JakeStanger/Reactive-Gallery<gh_stars>0
import React, { useCallback, useEffect, useState } from "react";
import styles from "./Login.module.scss";
import ILoginProps from "./ILoginProps";
const Login: React.FC<ILoginProps> = ({ userService, signup, history }) => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const [message, setMessage] = useState("");
const method = !signup ? userService.login : userService.signup;
useEffect(() => {
if (password && passwordConfirm && password !== passwordConfirm) {
setMessage("Passwords do not match");
} else {
setMessage("");
}
}, [password, passwordConfirm]);
const canSubmit = useCallback(() => {
if (signup) {
if (password !== passwordConfirm) return false;
}
return username && password;
}, [signup, username, password, passwordConfirm]);
// TODO: Convert to use `TextField`
return (
<div>
<form
className={styles.form}
onSubmit={ev =>
method(ev, username, password, email).then(msg => {
if (msg) setMessage(msg);
else {
// Force reload
window.location.href =
new URLSearchParams(window.location.search).get("next") || "/";
}
})
}
>
<div className={styles.formText}>
An account is required to purchase photo prints as it helps us keep
track of orders.
</div>
<label htmlFor="username">Username</label>
<input
name="username"
id="username"
value={username}
onChange={ev => setUsername(ev.target.value)}
required={true}
/>
{signup && (
<>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
value={email}
onChange={ev => setEmail(ev.target.value)}
/>
</>
)}
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
required={true}
value={password}
onChange={ev => setPassword(ev.target.value)}
/>
{signup && (
<>
<label htmlFor="passwordConfirm">Confirm Password</label>
<input
type="password"
name="passwordConfirm"
id="passwordConfirm"
required={true}
value={passwordConfirm}
onChange={ev => setPasswordConfirm(ev.target.value)}
/>
</>
)}
<button type="submit" disabled={!canSubmit()}>
{!signup ? "Sign in" : "Create Account"}
</button>
{!signup && (
<button onClick={() => history.push("/signup")}>
Create Account
</button>
)}
{message}
</form>
</div>
);
};
export default React.memo(Login);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.