diff --git a/.prettierrc b/.prettierrc index 0967ef424b..522fca5d9a 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1 +1,3 @@ -{} +{ + "organizeImportsSkipDestructiveCodeActions": true +} diff --git a/package.json b/package.json index 4c113b7f14..230dbc37d5 100644 --- a/package.json +++ b/package.json @@ -35,10 +35,10 @@ "markdown-toc": "^1.2.0", "nx": "^15.0.13", "prettier": "2.2.1", - "prettier-plugin-organize-imports": "^2.3.4", + "prettier-plugin-organize-imports": "^3.2.1", "pretty-quick": "^3.1.0", "rimraf": "^3.0.2", - "typescript": "^4.1.3" + "typescript": "^4.9.4" }, "workspaces": { "packages": [ diff --git a/packages/automator/artifacts.ts b/packages/automator/artifacts.ts index 4aef354d7d..f3de09eeed 100644 --- a/packages/automator/artifacts.ts +++ b/packages/automator/artifacts.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import _ from "lodash"; import pug from "pug"; import { InstanceData } from "./types"; -import vis from "./vis"; +import * as vis from "./vis"; const PAGELEN = 5; const gridLink = "grid.html"; diff --git a/packages/automator/index.tsx b/packages/automator/index.tsx index b67c8cd05e..4b7e76f006 100755 --- a/packages/automator/index.tsx +++ b/packages/automator/index.tsx @@ -1,4 +1,5 @@ -require("global-jsdom/register"); +import "global-jsdom/register"; // must be first + import { compileTrio, evalEnergy, @@ -18,7 +19,7 @@ import * as fs from "fs"; import neodoc from "neodoc"; import fetch from "node-fetch"; import { dirname, join, parse, resolve } from "path"; -import * as prettier from "prettier"; +import prettier from "prettier"; import uniqid from "uniqid"; import { printTextChart, renderArtifacts } from "./artifacts"; import { AggregateData, InstanceData } from "./types"; diff --git a/packages/automator/package.json b/packages/automator/package.json index af01b2c463..ac5e8838ab 100644 --- a/packages/automator/package.json +++ b/packages/automator/package.json @@ -2,11 +2,12 @@ "name": "@penrose/automator", "version": "1.3.0", "description": "", + "type": "module", "main": "index.tsx", "scripts": { "build": ":", "build-decls": ":", - "start": "ts-node ./index.tsx", + "start": "ts-node --esm --experimentalSpecifierResolution=node ./index.tsx", "generate-site": "yarn clean && yarn start batch registry.json artifacts --render=browser --src-prefix=progs --folders --cross-energy", "clean": "rimraf artifacts browser", "typecheck": "tsc --noEmit" @@ -45,7 +46,6 @@ }, "devDependencies": { "@types/node": "^12.12.68", - "ts-node": "^9.0.0", - "typescript": "^4.1.3" + "ts-node": "^10.9.1" } } diff --git a/packages/automator/tsconfig.json b/packages/automator/tsconfig.json index f661580063..82cd624a79 100644 --- a/packages/automator/tsconfig.json +++ b/packages/automator/tsconfig.json @@ -1,9 +1,9 @@ { "compilerOptions": { - "module": "CommonJS", + "module": "es2022", "allowJs": true, "esModuleInterop": true, - "target": "es6", + "target": "es2017", "moduleResolution": "Node", "sourceMap": true, "outDir": "dist", diff --git a/packages/automator/vis.js b/packages/automator/vis.js index 0546dc8aba..5a35f1f708 100644 --- a/packages/automator/vis.js +++ b/packages/automator/vis.js @@ -1,281 +1,279 @@ -module.exports = { - optimizerSeries: function (data) { - var res = []; - for (let id in data) { - let ins = data[id]; - const timeTypes = [ - // "overall", - ["compilation", "compilation"], - ["labelling", "state preparation"], - ["optimization", "optimization"], - ["rendering", "rendering"], - ]; - const entries = timeTypes.map(([t, label]) => ({ - size: ins.optProblem.constraintCount + ins.optProblem.objectiveCount, - time: ins.timeTaken[t], - id: ins.id, - name: ins.substanceName, +export const optimizerSeries = (data) => { + var res = []; + for (let id in data) { + let ins = data[id]; + const timeTypes = [ + // "overall", + ["compilation", "compilation"], + ["labelling", "state preparation"], + ["optimization", "optimization"], + ["rendering", "rendering"], + ]; + const entries = timeTypes.map(([t, label]) => ({ + size: ins.optProblem.constraintCount + ins.optProblem.objectiveCount, + time: ins.timeTaken[t], + id: ins.id, + name: ins.substanceName, + nonzeroConstraints: ins.nonzeroConstraints, + type: label, + })); + res = res.concat(entries); + } + return res; +}; +export const compileSeries = (data) => { + var res = []; + for (let id in data) { + let ins = data[id]; + const entries = [ + { + matches: ins.selectorMatches.reduce((a, b) => a + b, 0), + time: ins.timeTaken.compilation, nonzeroConstraints: ins.nonzeroConstraints, - type: label, - })); - res = res.concat(entries); - } - return res; - }, - compileSeries: function (data) { - var res = []; - for (let id in data) { - let ins = data[id]; - const entries = [ - { - matches: ins.selectorMatches.reduce((a, b) => a + b, 0), - time: ins.timeTaken.compilation, - nonzeroConstraints: ins.nonzeroConstraints, - name: ins.substanceName, - // time: ins.timeTaken.overall, - id: ins.id, - type: "compilation", - }, - ]; - res = res.concat(entries); - } - return res; - }, - optSpec: function (data) { - return { - width: 700, - height: 500, - $schema: "https://vega.github.io/schema/vega-lite/v4.json", - // title: "# of constraints and objectives vs. Execution time", - data: { values: data }, - config: { - axisX: { labelFontSize: 18, titleFontSize: 18 }, - axisY: { labelFontSize: 18, titleFontSize: 18 }, + name: ins.substanceName, + // time: ins.timeTaken.overall, + id: ins.id, + type: "compilation", }, - selection: { - constr: { - type: "single", - fields: ["nonzeroConstraints"], - bind: { - input: "select", - options: [null, true, false], - name: "Nonzero-constraints: ", - }, - }, - timeType: { - type: "multi", - fields: ["type"], - bind: "legend", + ]; + res = res.concat(entries); + } + return res; +}; +export const optSpec = (data) => { + return { + width: 700, + height: 500, + $schema: "https://vega.github.io/schema/vega-lite/v4.json", + // title: "# of constraints and objectives vs. Execution time", + data: { values: data }, + config: { + axisX: { labelFontSize: 18, titleFontSize: 18 }, + axisY: { labelFontSize: 18, titleFontSize: 18 }, + }, + selection: { + constr: { + type: "single", + fields: ["nonzeroConstraints"], + bind: { + input: "select", + options: [null, true, false], + name: "Nonzero-constraints: ", }, }, - mark: { type: "area" }, - transform: [{ filter: { selection: "constr" } }], - encoding: { - x: { - field: "size", - type: "quantitative", - bin: { step: 5 }, - legend: { title: "The number of constraints and objectives" }, - }, - y: { - aggregate: "mean", - field: "time", - type: "quantitative", - stack: true, - }, - color: { - field: "type", - type: "nominal", - legend: { - orient: "top", - titleFontSize: 18, - labelFontSize: 18, - }, - }, - opacity: { - condition: { selection: "timeType", value: 1 }, - value: 0.2, - }, + timeType: { + type: "multi", + fields: ["type"], + bind: "legend", }, - }; - }, - optScatterSpec: function (data) { - return { - width: 700, - height: 500, - $schema: "https://vega.github.io/schema/vega-lite/v4.json", - // title: "Problem size vs. Optimization time", - data: { values: data }, - mark: { - type: "point", + }, + mark: { type: "area" }, + transform: [{ filter: { selection: "constr" } }], + encoding: { + x: { + field: "size", + type: "quantitative", + bin: { step: 5 }, + legend: { title: "The number of constraints and objectives" }, }, - config: { - axisX: { labelFontSize: 18, titleFontSize: 18 }, - axisY: { labelFontSize: 18, titleFontSize: 18 }, + y: { + aggregate: "mean", + field: "time", + type: "quantitative", + stack: true, }, - selection: { - constr: { - type: "single", - fields: ["nonzeroConstraints"], - bind: { - input: "select", - options: [null, true, false], - name: "Nonzero-constraints: ", - }, + color: { + field: "type", + type: "nominal", + legend: { + orient: "top", + titleFontSize: 18, + labelFontSize: 18, }, }, - encoding: { - x: { - field: "size", - type: "quantitative", - title: "Number of constraints and objectives", - }, - y: { - field: "time", - type: "quantitative", - title: "Execution time (ms)", - }, - color: { - field: "type", - type: "nominal", - title: "Time type", - }, - shape: { - field: "type", - type: "nominal", - title: "Time type", - legend: { - orient: "top", - titleFontSize: 18, - labelFontSize: 18, - }, - }, - opacity: { - condition: { selection: "constr", value: 1 }, - value: 0.0, + opacity: { + condition: { selection: "timeType", value: 1 }, + value: 0.2, + }, + }, + }; +}; +export const optScatterSpec = (data) => { + return { + width: 700, + height: 500, + $schema: "https://vega.github.io/schema/vega-lite/v4.json", + // title: "Problem size vs. Optimization time", + data: { values: data }, + mark: { + type: "point", + }, + config: { + axisX: { labelFontSize: 18, titleFontSize: 18 }, + axisY: { labelFontSize: 18, titleFontSize: 18 }, + }, + selection: { + constr: { + type: "single", + fields: ["nonzeroConstraints"], + bind: { + input: "select", + options: [null, true, false], + name: "Nonzero-constraints: ", }, - tooltip: [ - { field: "size", type: "quantitative" }, - { field: "time", type: "quantitative" }, - { field: "name", type: "nominal" }, - { field: "type", type: "nominal" }, - { field: "id", type: "nominal" }, - ], }, - }; - }, - exampleBarSpec: function (data) { - return { - width: 700, - height: 500, - $schema: "https://vega.github.io/schema/vega-lite/v4.json", - config: { - axisX: { labelFontSize: 14, titleFontSize: 18, labelAngle: 45 }, - axisY: { labelFontSize: 18, titleFontSize: 18 }, + }, + encoding: { + x: { + field: "size", + type: "quantitative", + title: "Number of constraints and objectives", }, - data: { values: data }, - mark: "bar", - encoding: { - x: { - field: "name", - type: "nominal", - axis: { title: "Example Name" }, - sort: "y", - }, - y: { - field: "time", - type: "quantitative", - title: "Execution time (ms)", - }, - color: { - field: "type", - type: "nominal", - title: "Time type", + y: { + field: "time", + type: "quantitative", + title: "Execution time (ms)", + }, + color: { + field: "type", + type: "nominal", + title: "Time type", + }, + shape: { + field: "type", + type: "nominal", + title: "Time type", + legend: { + orient: "top", + titleFontSize: 18, + labelFontSize: 18, }, - tooltip: [ - { field: "size", type: "quantitative" }, - { field: "time", type: "quantitative" }, - { field: "name", type: "nominal" }, - { field: "id", type: "nominal" }, - ], }, - }; - }, - compileSpec: function (data) { - return { - width: 700, - height: 500, - $schema: "https://vega.github.io/schema/vega-lite/v4.json", - // title: "Selector matches vs. Compilation time", - config: { - axisX: { labelFontSize: 18, titleFontSize: 18 }, - axisY: { labelFontSize: 18, titleFontSize: 18 }, + opacity: { + condition: { selection: "constr", value: 1 }, + value: 0.0, + }, + tooltip: [ + { field: "size", type: "quantitative" }, + { field: "time", type: "quantitative" }, + { field: "name", type: "nominal" }, + { field: "type", type: "nominal" }, + { field: "id", type: "nominal" }, + ], + }, + }; +}; +export const exampleBarSpec = (data) => { + return { + width: 700, + height: 500, + $schema: "https://vega.github.io/schema/vega-lite/v4.json", + config: { + axisX: { labelFontSize: 14, titleFontSize: 18, labelAngle: 45 }, + axisY: { labelFontSize: 18, titleFontSize: 18 }, + }, + data: { values: data }, + mark: "bar", + encoding: { + x: { + field: "name", + type: "nominal", + axis: { title: "Example Name" }, + sort: "y", + }, + y: { + field: "time", + type: "quantitative", + title: "Execution time (ms)", + }, + color: { + field: "type", + type: "nominal", + title: "Time type", }, - data: { values: data }, - layer: [ - { - selection: { - constr: { - type: "single", - fields: ["nonzeroConstraints"], - bind: { - input: "select", - options: [null, true, false], - name: "Nonzero-constraints: ", - }, + tooltip: [ + { field: "size", type: "quantitative" }, + { field: "time", type: "quantitative" }, + { field: "name", type: "nominal" }, + { field: "id", type: "nominal" }, + ], + }, + }; +}; +export const compileSpec = (data) => { + return { + width: 700, + height: 500, + $schema: "https://vega.github.io/schema/vega-lite/v4.json", + // title: "Selector matches vs. Compilation time", + config: { + axisX: { labelFontSize: 18, titleFontSize: 18 }, + axisY: { labelFontSize: 18, titleFontSize: 18 }, + }, + data: { values: data }, + layer: [ + { + selection: { + constr: { + type: "single", + fields: ["nonzeroConstraints"], + bind: { + input: "select", + options: [null, true, false], + name: "Nonzero-constraints: ", }, }, - mark: { - type: "point", + }, + mark: { + type: "point", + }, + encoding: { + x: { + field: "matches", + type: "quantitative", + title: "Selector matches", }, - encoding: { - x: { - field: "matches", - type: "quantitative", - title: "Selector matches", - }, - y: { - field: "time", - type: "quantitative", - title: "Compilation time (ms)", - }, - // color: { - // field: "nonzeroConstraints", - // type: "nominal", - // legend: null - // }, - tooltip: [ - { field: "matches", type: "quantitative" }, - { field: "time", type: "quantitative" }, - { field: "name", type: "nominal" }, - { field: "id", type: "nominal" }, - ], - opacity: { - condition: { selection: "constr", value: 0.8 }, - value: 0.0, - }, + y: { + field: "time", + type: "quantitative", + title: "Compilation time (ms)", + }, + // color: { + // field: "nonzeroConstraints", + // type: "nominal", + // legend: null + // }, + tooltip: [ + { field: "matches", type: "quantitative" }, + { field: "time", type: "quantitative" }, + { field: "name", type: "nominal" }, + { field: "id", type: "nominal" }, + ], + opacity: { + condition: { selection: "constr", value: 0.8 }, + value: 0.0, }, }, - // { - // mark: { - // type: "line", - // color: "firebrick" - // }, - // transform: [ - // { filter: { selection: "constr" } }, - // { regression: "time", on: "matches", method: "log" } - // ], - // encoding: { - // x: { - // field: "matches", - // type: "quantitative", - // title: "Selector Matches" - // }, - // y: { field: "time", type: "quantitative", title: "Time (ms)" }, - // color: { value: "#dd565c" } - // } - // } - ], - }; - }, + }, + // { + // mark: { + // type: "line", + // color: "firebrick" + // }, + // transform: [ + // { filter: { selection: "constr" } }, + // { regression: "time", on: "matches", method: "log" } + // ], + // encoding: { + // x: { + // field: "matches", + // type: "quantitative", + // title: "Selector Matches" + // }, + // y: { field: "time", type: "quantitative", title: "Time (ms)" }, + // color: { value: "#dd565c" } + // } + // } + ], + }; }; diff --git a/packages/components/package.json b/packages/components/package.json index af56d94da8..9fb489dcba 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -73,7 +73,6 @@ "@types/react-dom": "^17.0.10", "@vitejs/plugin-react": "^1.0.7", "babel-loader": "^8.2.5", - "typescript": "^4.4.4", "vite": "^2.7.2" } } diff --git a/packages/core/.eslintrc.js b/packages/core/.eslintrc.cjs similarity index 100% rename from packages/core/.eslintrc.js rename to packages/core/.eslintrc.cjs diff --git a/packages/core/build.js b/packages/core/build.cjs similarity index 69% rename from packages/core/build.js rename to packages/core/build.cjs index e90a8acbd3..96657ac93c 100644 --- a/packages/core/build.js +++ b/packages/core/build.cjs @@ -22,7 +22,12 @@ build({ ...common, outfile: "./build/dist/index.js", platform: "node", + // https://github.com/evanw/esbuild/pull/2067#issuecomment-1324171716 + banner: { + js: + "import { createRequire } from 'module'; const require = createRequire(import.meta.url);", + }, minify: false, - format: "cjs", + format: "esm", sourcemap: "both", }); diff --git a/packages/core/jest.config.js b/packages/core/jest.config.cjs similarity index 67% rename from packages/core/jest.config.js rename to packages/core/jest.config.cjs index d5dfd3f68a..5b91076473 100644 --- a/packages/core/jest.config.js +++ b/packages/core/jest.config.cjs @@ -3,4 +3,6 @@ module.exports = { testEnvironment: "jsdom", modulePaths: ["node_modules", "/src/"], testPathIgnorePatterns: ["build/dist/"], + extensionsToTreatAsEsm: [".ts"], + globals: { "ts-jest": { useESM: true } }, }; diff --git a/packages/core/package.json b/packages/core/package.json index 6f7da81c5c..47e2b21886 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,7 @@ { "name": "@penrose/core", "version": "1.3.0", + "type": "module", "main": "build/dist/index.js", "module": "build/dist/index.esm.js", "unpkg": "build/dist/penrose.min.js", @@ -15,15 +16,15 @@ "build": "yarn build:esbuild", "start": "yarn watch:esbuild", "watch": "yarn watch:esbuild", - "test": "jest", - "test-watch": "jest --watchAll", - "build:esbuild": "node build.js", - "watch:esbuild": "node build.js -watch", + "test": "cross-env NODE_OPTIONS='--no-warnings --experimental-vm-modules' jest", + "test-watch": "yarn test --watchAll", + "build:esbuild": "node build.cjs", + "watch:esbuild": "node build.cjs -watch", "build-decls": "tsc --emitDeclarationOnly --outDir build/dist && tsc-alias -p tsconfig.json", "typecheck": ":", "docs": "typedoc --plugin none --out docs", "docs:md": "typedoc --plugin typedoc-plugin-markdown --out docs/md", - "coverage": "jest --coverage --ci --runInBand --reporters=default --reporters=jest-junit", + "coverage": "yarn test --coverage --ci --runInBand --reporters=default --reporters=jest-junit", "lint": "eslint --ext js,ts,tsx src" }, "nx": { @@ -147,7 +148,6 @@ "tsc-alias": "^1.6.7", "tslib": "^2.1.0", "typedoc": "^0.22.11", - "typedoc-plugin-markdown": "^3.11.13", - "typescript": "^4.1.3" + "typedoc-plugin-markdown": "^3.11.13" } } diff --git a/packages/core/src/__tests__/mathtransform.test.ts b/packages/core/src/__tests__/mathtransform.test.ts index f6678108f3..1e38d391fc 100644 --- a/packages/core/src/__tests__/mathtransform.test.ts +++ b/packages/core/src/__tests__/mathtransform.test.ts @@ -1,8 +1,28 @@ +import { jest } from "@jest/globals"; +import * as fs from "fs"; // @ts-ignore -import { defineTest } from "jscodeshift/dist/testUtils"; +import { defineInlineTest } from "jscodeshift/dist/testUtils"; +import * as path from "path"; +import { dirname } from "path"; +import { fileURLToPath } from "url"; +import * as transform from "../utils/toCustomAD"; jest.autoMockOff(); // idk if this is required // const defineTest = require("jscodeshift/dist/testUtils").defineTest; // i know we don't use require but i could not get it to work with import // may not be a typing for that specific file -defineTest(__dirname, "utils/toCustomAD", null, "transformtest", { - parser: "ts", -}); // docs for this are here: https://github.com/facebook/jscodeshift +// https://stackoverflow.com/a/62892482 +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +defineInlineTest( + transform, + { + parser: "ts", + }, + fs.readFileSync( + path.join(__dirname, "../__testfixtures__/transformtest.input.ts"), + "utf8" + ), + fs.readFileSync( + path.join(__dirname, "../__testfixtures__/transformtest.output.ts"), + "utf8" + ) +); // docs for this are here: https://github.com/facebook/jscodeshift diff --git a/packages/core/src/analysis/SubstanceAnalysis.test.ts b/packages/core/src/analysis/SubstanceAnalysis.test.ts index 1be27693fc..7e932e9d87 100644 --- a/packages/core/src/analysis/SubstanceAnalysis.test.ts +++ b/packages/core/src/analysis/SubstanceAnalysis.test.ts @@ -5,7 +5,7 @@ import { prettySubstance, } from "compiler/Substance"; import { dummyIdentifier } from "engine/EngineUtils"; -import { intersectionWith } from "lodash"; +import _ from "lodash"; import { similarMappings, similarNodes, SubNode } from "synthesis/Search"; import { A } from "types/ast"; import { Env } from "types/domain"; @@ -79,10 +79,10 @@ describe("Substance AST queries", () => { const rightAST = compile(right); const commonStmts = intersection(leftAST, rightAST); const leftFiltered = leftAST.statements.filter((a) => { - return intersectionWith(commonStmts, [a], nodesEqual).length === 0; + return _.intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); const rightFiltered = rightAST.statements.filter((a) => { - return intersectionWith(commonStmts, [a], nodesEqual).length === 0; + return _.intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); expect(commonStmts.map(prettyStmt)).toEqual([ "Set A", diff --git a/packages/core/src/analysis/SubstanceAnalysis.ts b/packages/core/src/analysis/SubstanceAnalysis.ts index df043f1dfd..e165ddc2ba 100644 --- a/packages/core/src/analysis/SubstanceAnalysis.ts +++ b/packages/core/src/analysis/SubstanceAnalysis.ts @@ -1,16 +1,6 @@ import { prettyStmt } from "compiler/Substance"; import im from "immutable"; -import { - cloneDeep, - cloneDeepWith, - compact, - filter, - intersectionWith, - isEqual, - isEqualWith, - sortBy, - uniq, -} from "lodash"; +import _ from "lodash"; import { A, AbstractNode, C, Identifier, metaProps } from "types/ast"; import { ConstructorDecl, @@ -106,7 +96,7 @@ export const removeStmt = ( stmt: SubStmt ): SubProg => ({ ...prog, - statements: filter(prog.statements, (s) => !nodesEqual(stmt, s)), + statements: _.filter(prog.statements, (s) => !nodesEqual(stmt, s)), }); /** @@ -454,8 +444,8 @@ export const autoLabelStmt: AutoLabel = { * @returns a boolean value */ export const nodesEqual = (node1: AbstractNode, node2: AbstractNode): boolean => - isEqualWith(node1, node2, (node1: AbstractNode, node2: AbstractNode) => { - return isEqual(cleanNode(node1), cleanNode(node2)); + _.isEqualWith(node1, node2, (node1: AbstractNode, node2: AbstractNode) => { + return _.isEqual(cleanNode(node1), cleanNode(node2)); }); /** @@ -466,7 +456,7 @@ export const nodesEqual = (node1: AbstractNode, node2: AbstractNode): boolean => * @returns a boolean value */ export const progsEqual = (left: SubProg, right: SubProg): boolean => - isEqualWith( + _.isEqualWith( left.statements, right.statements, (node1: SubStmt, node2: SubStmt) => nodesEqual(node1, node2) @@ -482,7 +472,7 @@ export const intersection = ( left: SubProg, right: SubProg ): SubStmt[] => - intersectionWith(left.statements, right.statements, (s1, s2) => + _.intersectionWith(left.statements, right.statements, (s1, s2) => nodesEqual(s1, s2) ); @@ -494,7 +484,7 @@ export const intersection = ( export const sortStmts = (prog: SubProg): SubProg => { const { statements } = prog; // first sort by statement type, and then by lexicographic ordering of source text - const newStmts: SubStmt[] = sortBy(statements, [ + const newStmts: SubStmt[] = _.sortBy(statements, [ "tag", (s: SubStmt) => prettyStmt(s), ]); @@ -506,7 +496,7 @@ export const sortStmts = (prog: SubProg): SubProg => { // TODO: compare clean nodes instead? export const stmtExists = (stmt: SubStmt, prog: SubProg): boolean => - prog.statements.find((s) => isEqual(stmt, s)) !== undefined; + prog.statements.find((s) => _.isEqual(stmt, s)) !== undefined; export const cleanNode = (prog: AbstractNode): AbstractNode => omitDeep(prog, metaProps); @@ -524,7 +514,7 @@ export const typeOf = (id: string, env: Env): string | undefined => // helper function for omitting properties in an object const omitDeep = (originalCollection: any, excludeKeys: string[]): any => { // TODO: `omitFn` mutates the collection - const collection = cloneDeep(originalCollection); + const collection = _.cloneDeep(originalCollection); const omitFn = (value: any) => { if (value && typeof value === "object") { excludeKeys.forEach((key) => { @@ -532,7 +522,7 @@ const omitDeep = (originalCollection: any, excludeKeys: string[]): any => { }); } }; - return cloneDeepWith(collection, omitFn); + return _.cloneDeepWith(collection, omitFn); }; export type SubStmtKind = "type" | "predicate" | "constructor" | "function"; @@ -548,9 +538,9 @@ type TypeWithKind = { * Given a Substance program, find out the types, constructors, functions, and predicates used in the program. */ export const findTypes = (prog: SubProg): SubStmtKindMap => { - const typeList: TypeWithKind[] = compact(prog.statements.map(findType)); + const typeList: TypeWithKind[] = _.compact(prog.statements.map(findType)); const getNames = (ts: TypeWithKind[], k: SubStmtKind): string[] => - uniq(ts.filter((t) => t.kind === k).map((t) => t.name)); + _.uniq(ts.filter((t) => t.kind === k).map((t) => t.name)); return { type: getNames(typeList, "type"), predicate: getNames(typeList, "predicate"), diff --git a/packages/core/src/compiler/Domain.test.ts b/packages/core/src/compiler/Domain.test.ts index 72bace1318..db846cd378 100644 --- a/packages/core/src/compiler/Domain.test.ts +++ b/packages/core/src/compiler/Domain.test.ts @@ -1,7 +1,7 @@ import { examples } from "@penrose/examples"; import { compileDomain, isSubtype } from "compiler/Domain"; import * as fs from "fs"; -import * as nearley from "nearley"; +import nearley from "nearley"; import grammar from "parser/DomainParser"; import * as path from "path"; import { Env } from "types/domain"; diff --git a/packages/core/src/compiler/Domain.ts b/packages/core/src/compiler/Domain.ts index 173d909a2b..194b2ee743 100644 --- a/packages/core/src/compiler/Domain.ts +++ b/packages/core/src/compiler/Domain.ts @@ -1,5 +1,5 @@ import im from "immutable"; -import { every, keyBy, zipWith } from "lodash"; +import _ from "lodash"; import nearley from "nearley"; import domainGrammar from "parser/DomainParser"; import { idOf, lastLocation, prettyParseError } from "parser/ParserUtil"; @@ -161,7 +161,7 @@ const checkStmt = (stmt: DomainStmt, env: Env): CheckerResult => { // load params into context const localEnv: Env = { ...env, - typeVars: im.Map(keyBy(params, "name.value")), + typeVars: im.Map(_.keyBy(params, "name.value")), }; // check name duplicate const existing = env.constructors.get(name.value); @@ -183,7 +183,7 @@ const checkStmt = (stmt: DomainStmt, env: Env): CheckerResult => { // load params into context const localEnv: Env = { ...env, - typeVars: im.Map(keyBy(params, "name.value")), + typeVars: im.Map(_.keyBy(params, "name.value")), }; // check name duplicate const existing = env.functions.get(name.value); @@ -205,7 +205,7 @@ const checkStmt = (stmt: DomainStmt, env: Env): CheckerResult => { // load params into context const localEnv: Env = { ...env, - typeVars: im.Map(keyBy(params, "name.value")), + typeVars: im.Map(_.keyBy(params, "name.value")), }; // check name duplicate const existing = env.predicates.get(name.value); @@ -424,8 +424,8 @@ export const isSubtype = ( superType.tag === "TypeConstructor" ) { const argsMatch = (args1: Type[], args2: Type[]): boolean => - every( - zipWith(args1, args2, (sub: Type, sup: Type): boolean => + _.every( + _.zipWith(args1, args2, (sub: Type, sup: Type): boolean => isSubtype(sub, sup, env) ) ); diff --git a/packages/core/src/compiler/Style.ts b/packages/core/src/compiler/Style.ts index 46be825056..2ade03d6bc 100644 --- a/packages/core/src/compiler/Style.ts +++ b/packages/core/src/compiler/Style.ts @@ -1,6 +1,6 @@ import { CustomHeap } from "@datastructures-js/heap"; import { checkExpr, checkPredicate, checkVar } from "compiler/Substance"; -import consola, { LogLevel } from "consola"; +import consola from "consola"; import { constrDict } from "contrib/Constraints"; import { compDict } from "contrib/Functions"; import { objDict } from "contrib/Objectives"; @@ -8,9 +8,9 @@ import { input, ops } from "engine/Autodiff"; import { add, div, mul, neg, pow, sub } from "engine/AutodiffFunctions"; import { compileCompGraph, dummyIdentifier } from "engine/EngineUtils"; import { genOptProblem } from "engine/Optimizer"; -import { alg, Edge, Graph } from "graphlib"; +import graphlib from "graphlib"; import im from "immutable"; -import _, { range } from "lodash"; +import _ from "lodash"; import nearley from "nearley"; import { lastLocation, prettyParseError } from "parser/ParserUtil"; import styleGrammar from "parser/StyleParser"; @@ -139,7 +139,7 @@ import { import { checkTypeConstructor, isDeclaredSubtype } from "./Domain"; const log = consola - .create({ level: LogLevel.Warn }) + .create({ level: (consola as any).LogLevel.Warn }) .withScope("Style Compiler"); //#region consts @@ -154,7 +154,7 @@ const dummyId = (name: string): Identifier => dummyIdentifier(name, "SyntheticStyle"); export function numbered(xs: A[]): [A, number][] { - return zip2(xs, range(xs.length)); + return zip2(xs, _.range(xs.length)); } const safeContentsList = (x: { contents: T[] } | undefined): T[] => @@ -2912,7 +2912,7 @@ export const computeShapeOrdering = ( shapeOrdering: string[]; warning?: LayerCycleWarning; } => { - const layerGraph: Graph = new Graph(); + const layerGraph: graphlib.Graph = new graphlib.Graph(); allGPINames.forEach((name: string) => layerGraph.setNode(name)); // topsort will return the most upstream node first. Since `shapeOrdering` is consistent with the SVG drawing order, we assign edges as "below => above". partialOrderings.forEach(({ below, above }: Layer) => @@ -2920,11 +2920,11 @@ export const computeShapeOrdering = ( ); // if there are no cycles, return a global ordering from the top sort result - if (alg.isAcyclic(layerGraph)) { - const shapeOrdering: string[] = alg.topsort(layerGraph); + if (graphlib.alg.isAcyclic(layerGraph)) { + const shapeOrdering: string[] = graphlib.alg.topsort(layerGraph); return { shapeOrdering }; } else { - const cycles = alg.findCycles(layerGraph); + const cycles = graphlib.alg.findCycles(layerGraph); const shapeOrdering = pseudoTopsort(layerGraph); return { shapeOrdering, @@ -2937,7 +2937,7 @@ export const computeShapeOrdering = ( } }; -const pseudoTopsort = (graph: Graph): string[] => { +const pseudoTopsort = (graph: graphlib.Graph): string[] => { const toVisit: CustomHeap = new CustomHeap((a: string, b: string) => { const aIn = graph.inEdges(a); const bIn = graph.inEdges(b); @@ -2954,7 +2954,7 @@ const pseudoTopsort = (graph: Graph): string[] => { // remove all edges with `node` const toRemove = graph.nodeEdges(node); if (toRemove !== undefined) { - toRemove.forEach((e: Edge) => graph.removeEdge(e)); + toRemove.forEach((e: graphlib.Edge) => graph.removeEdge(e)); toVisit.fix(); } } diff --git a/packages/core/src/compiler/Substance.test.ts b/packages/core/src/compiler/Substance.test.ts index 9f032e1388..04fc1d4567 100644 --- a/packages/core/src/compiler/Substance.test.ts +++ b/packages/core/src/compiler/Substance.test.ts @@ -1,6 +1,6 @@ import { examples } from "@penrose/examples"; import * as fs from "fs"; -import * as nearley from "nearley"; +import nearley from "nearley"; import grammar from "parser/SubstanceParser"; import * as path from "path"; import { A } from "types/ast"; diff --git a/packages/core/src/compiler/Substance.ts b/packages/core/src/compiler/Substance.ts index 1b7153d8fb..c440dea945 100644 --- a/packages/core/src/compiler/Substance.ts +++ b/packages/core/src/compiler/Substance.ts @@ -1,6 +1,6 @@ import { dummyIdentifier } from "engine/EngineUtils"; import im from "immutable"; -import { findIndex } from "lodash"; +import _ from "lodash"; import nearley from "nearley"; import { idOf, lastLocation, prettyParseError } from "parser/ParserUtil"; import substanceGrammar from "parser/SubstanceParser"; @@ -683,7 +683,7 @@ const checkField = ( // get the constructor decl in Domain const [cons, consDecl] = res; // find the field index by name - const fieldIndex = findIndex( + const fieldIndex = _.findIndex( consDecl.args, (a) => a.variable.value === field.value ); diff --git a/packages/core/src/contrib/Functions.ts b/packages/core/src/contrib/Functions.ts index e240c3a50e..ef91f5b32d 100644 --- a/packages/core/src/contrib/Functions.ts +++ b/packages/core/src/contrib/Functions.ts @@ -50,8 +50,7 @@ import { trunc, } from "engine/AutodiffFunctions"; import * as BBox from "engine/BBox"; -import * as _ from "lodash"; -import { range } from "lodash"; +import _ from "lodash"; import { PathBuilder } from "renderer/PathBuilder"; import { Ellipse } from "shapes/Ellipse"; import { Line } from "shapes/Line"; @@ -1077,7 +1076,7 @@ export const compDict = { colorType: string ): ColorV => { if (colorType === "rgb") { - const rgb = range(3).map(() => + const rgb = _.range(3).map(() => makeInput({ tag: "Optimized", sampler: uniform(0.1, 0.9) }) ); diff --git a/packages/core/src/contrib/Utils.ts b/packages/core/src/contrib/Utils.ts index 13121355e8..f84b9a4ea8 100644 --- a/packages/core/src/contrib/Utils.ts +++ b/packages/core/src/contrib/Utils.ts @@ -15,7 +15,7 @@ import { sub, } from "engine/AutodiffFunctions"; import * as BBox from "engine/BBox"; -import * as _ from "lodash"; +import _ from "lodash"; import * as ad from "types/ad"; /** diff --git a/packages/core/src/engine/Autodiff.test.ts b/packages/core/src/engine/Autodiff.test.ts index 3aa85b719c..4ad249016e 100644 --- a/packages/core/src/engine/Autodiff.test.ts +++ b/packages/core/src/engine/Autodiff.test.ts @@ -7,7 +7,7 @@ import { primaryGraph, secondaryGraph, } from "engine/Autodiff"; -import * as _ from "lodash"; +import _ from "lodash"; import seedrandom from "seedrandom"; import * as ad from "types/ad"; import { eqList, randList } from "utils/Util"; diff --git a/packages/core/src/engine/Autodiff.ts b/packages/core/src/engine/Autodiff.ts index bcd5ab62e1..68a78e4607 100644 --- a/packages/core/src/engine/Autodiff.ts +++ b/packages/core/src/engine/Autodiff.ts @@ -1,6 +1,6 @@ import { Queue } from "@datastructures-js/queue"; -import consola, { LogLevel } from "consola"; -import * as _ from "lodash"; +import consola from "consola"; +import _ from "lodash"; import { EigenvalueDecomposition, Matrix } from "ml-matrix"; import * as ad from "types/ad"; import { Multidigraph } from "utils/Graph"; @@ -36,7 +36,7 @@ import { // To view logs, use LogLevel.Trace, otherwese LogLevel.Warn // const log = consola.create({ level: LogLevel.Trace }).withScope("Optimizer"); export const logAD = consola - .create({ level: LogLevel.Warn }) + .create({ level: (consola as any).LogLevel.Warn }) .withScope("Optimizer"); export const EPS_DENOM = 10e-6; // Avoid divide-by-zero in denominator diff --git a/packages/core/src/engine/EngineUtils.ts b/packages/core/src/engine/EngineUtils.ts index e0fbcff1a0..c1dd56e3e3 100644 --- a/packages/core/src/engine/EngineUtils.ts +++ b/packages/core/src/engine/EngineUtils.ts @@ -1,6 +1,6 @@ // Utils that are unrelated to the engine, but autodiff/opt/etc only -import { mapValues } from "lodash"; +import _ from "lodash"; import { ShapeDef, shapedefs } from "shapes/Shapes"; import * as ad from "types/ad"; import { @@ -204,7 +204,7 @@ export const compileCompGraph = (shapes: ShapeAD[]): ShapeFn => { const m = new Map(compGraph.secondary.map((id, i) => [id, numbers[i]])); return shapes.map((s: ShapeAD) => ({ ...s, - properties: mapValues(s.properties, (p: Value) => + properties: _.mapValues(s.properties, (p: Value) => mapValueNumeric( (x) => safe( diff --git a/packages/core/src/engine/Optimizer.ts b/packages/core/src/engine/Optimizer.ts index c879e83ad2..f46b68ea2a 100644 --- a/packages/core/src/engine/Optimizer.ts +++ b/packages/core/src/engine/Optimizer.ts @@ -1,7 +1,7 @@ -import consola, { LogLevel } from "consola"; +import consola from "consola"; import { fns, genCode, input, makeGraph, ops } from "engine/Autodiff"; import { defaultLbfgsParams, initConstraintWeight } from "engine/EngineUtils"; -import * as _ from "lodash"; +import _ from "lodash"; import { Matrix } from "ml-matrix"; import { InputMeta } from "shapes/Samplers"; import * as ad from "types/ad"; @@ -22,7 +22,9 @@ import { add, mul } from "./AutodiffFunctions"; // NOTE: to view logs, change `level` below to `LogLevel.Info`, otherwise it should be `LogLevel.Warn` // const log = consola.create({ level: LogLevel.Info }).withScope("Optimizer"); -const log = consola.create({ level: LogLevel.Warn }).withScope("Optimizer"); +const log = consola + .create({ level: (consola as any).LogLevel.Warn }) + .withScope("Optimizer"); //////////////////////////////////////////////////////////////////////////////// // Globals diff --git a/packages/core/src/parser/Domain.ne b/packages/core/src/parser/Domain.ne index 7df656b4eb..aed8a57ee2 100644 --- a/packages/core/src/parser/Domain.ne +++ b/packages/core/src/parser/Domain.ne @@ -4,8 +4,8 @@ # Lexer @{% /* eslint-disable */ -import * as moo from "moo"; -import { concat, compact, flatten, last } from 'lodash' +import moo from "moo"; +import _ from 'lodash' import { optional, tokensIn, basicSymbols, rangeOf, rangeBetween, rangeFrom, nth, convertTokenId } from 'parser/ParserUtil' import { C, ConcreteNode, StringLit } from "types/ast"; import { DomainProg, TypeDecl, PredicateDecl, FunctionDecl, ConstructorDecl, PreludeDecl, NotationDecl, SubTypeDecl, TypeConstructor, Type, Arg, Prop } from "types/domain"; @@ -202,7 +202,7 @@ type_constructor -> identifier type_arg_list:? {% # Various kinds of parameters and arguments -type_arg_list -> _ "(" _ sepBy1[type, ","] _ ")" {% ([, , , d]): Type[] => flatten(d) %} +type_arg_list -> _ "(" _ sepBy1[type, ","] _ ")" {% ([, , , d]): Type[] => _.flatten(d) %} type_params_list -> null {% d => [] %} @@ -210,7 +210,7 @@ type_params_list type_params -> sepBy1[type_var, ","] {% ([d]) => d %} args_list - -> _ "(" _ sepBy[arg, ","] _ ")" {% ([, , , d]): Arg[] => flatten(d) %} + -> _ "(" _ sepBy[arg, ","] _ ")" {% ([, , , d]): Arg[] => _.flatten(d) %} arg -> type (__ var):? {% ([type, v]): Arg => { const variable = v ? v[1] : undefined; @@ -223,7 +223,7 @@ arg -> type (__ var):? {% } %} named_args_list - -> _ "(" _ sepBy[named_arg, ","] _ ")" {% ([, , , d]): Arg[] => flatten(d) %} + -> _ "(" _ sepBy[named_arg, ","] _ ")" {% ([, , , d]): Arg[] => _.flatten(d) %} named_arg -> type __ var {% ([type, , variable]): Arg => ({ ...nodeData, diff --git a/packages/core/src/parser/DomainParser.test.ts b/packages/core/src/parser/DomainParser.test.ts index 7801e6ba1a..1e158379bd 100644 --- a/packages/core/src/parser/DomainParser.test.ts +++ b/packages/core/src/parser/DomainParser.test.ts @@ -1,6 +1,6 @@ import { examples } from "@penrose/examples"; import * as fs from "fs"; -import * as nearley from "nearley"; +import nearley from "nearley"; import * as path from "path"; import { SourceRange } from "types/ast"; import { DomainProg, PredicateDecl } from "types/domain"; diff --git a/packages/core/src/parser/ParserUtil.test.ts b/packages/core/src/parser/ParserUtil.test.ts index d8d0b88825..41c7fb70d2 100644 --- a/packages/core/src/parser/ParserUtil.test.ts +++ b/packages/core/src/parser/ParserUtil.test.ts @@ -1,4 +1,4 @@ -import * as moo from "moo"; +import moo from "moo"; import * as ParserUtil from "parser/ParserUtil"; describe("ParserUtil", () => { diff --git a/packages/core/src/parser/ParserUtil.ts b/packages/core/src/parser/ParserUtil.ts index 9fbeefa8c6..99eba21721 100644 --- a/packages/core/src/parser/ParserUtil.ts +++ b/packages/core/src/parser/ParserUtil.ts @@ -1,5 +1,5 @@ -import { compact, flatten } from "lodash"; -import * as moo from "moo"; +import _ from "lodash"; +import moo from "moo"; import { C, Identifier, NodeType, SourceLoc, SourceRange } from "types/ast"; export const basicSymbols: moo.Rules = { @@ -123,8 +123,8 @@ export const rangeFrom = (children: SourceRange[]): SourceRange => { // NOTE: use of compact to remove optional nodes return { - start: minLoc(...compact(children).map((n) => n.start)), - end: maxLoc(...compact(children).map((n) => n.end)), + start: minLoc(..._.compact(children).map((n) => n.start)), + end: maxLoc(..._.compact(children).map((n) => n.end)), // children TODO: decide if want children/parent pointers in the tree }; }; @@ -169,7 +169,7 @@ export const optional = (optionalValue: T | undefined, defaultValue: T): T => // Helper that takes in a mix of single token or list of tokens, drops all undefined (i.e. optional ealues), and finally flattten the mixture to a list of tokens. export const tokensIn = ( tokenList: (moo.Token | moo.Token[] | undefined)[] -): moo.Token[] => flatten(compact(tokenList)); +): moo.Token[] => _.flatten(_.compact(tokenList)); // HACK: locations for dummy AST nodes. Revisit if this pattern becomes widespread. export const idOf = (value: string, nodeType: NodeType): Identifier => ({ diff --git a/packages/core/src/parser/Style.ne b/packages/core/src/parser/Style.ne index 303c3f9480..be6de93cc7 100644 --- a/packages/core/src/parser/Style.ne +++ b/packages/core/src/parser/Style.ne @@ -4,8 +4,8 @@ @{% /* eslint-disable */ -import * as moo from "moo"; -import { concat, compact, flatten, last } from 'lodash' +import moo from "moo"; +import _ from 'lodash' import { basicSymbols, rangeOf, rangeBetween, rangeFrom, nth, convertTokenId } from 'parser/ParserUtil' import { C, ConcreteNode, Identifier, StringLit } from "types/ast"; import { StyT, DeclPattern, DeclPatterns, RelationPatterns, Namespace, Selector, StyProg, HeaderBlock, RelBind, RelField, RelPred, SEFuncOrValCons, SEBind, Block, AnonAssign, Delete, Override, PathAssign, StyType, BindingForm, Path, Layering, BinaryOp, Expr, BinOp, SubVar, StyVar, UOp, List, Tuple, Vector, BoolLit, Vary, Fix, CompApp, ObjFn, ConstrFn, GPIDecl, PropertyDecl, ColorLit @@ -83,7 +83,7 @@ const selector = ( ): Selector => { return { ...nodeData, - ...rangeFrom(compact([hd, wth, whr])), + ...rangeFrom(_.compact([hd, wth, whr])), tag: "Selector", head: hd, with: wth, @@ -160,7 +160,7 @@ select_with -> "with" __ decl_patterns _ml {% d => d[2] %} decl_patterns -> sepBy1[decl_list, ";"] {% ([d]): DeclPatterns => { - const contents = flatten(d) as DeclPattern[]; + const contents = _.flatten(d) as DeclPattern[]; return { ...nodeData, ...rangeFrom(contents), diff --git a/packages/core/src/parser/StyleParser.test.ts b/packages/core/src/parser/StyleParser.test.ts index 0ecf6aea7f..3050c6ee5e 100644 --- a/packages/core/src/parser/StyleParser.test.ts +++ b/packages/core/src/parser/StyleParser.test.ts @@ -1,7 +1,7 @@ import { examples } from "@penrose/examples"; import { parseStyle } from "compiler/Style"; import * as fs from "fs"; -import * as nearley from "nearley"; +import nearley from "nearley"; import * as path from "path"; import { C } from "types/ast"; import { StyProg } from "types/style"; diff --git a/packages/core/src/parser/Substance.ne b/packages/core/src/parser/Substance.ne index de23473a53..dab05b1dd2 100644 --- a/packages/core/src/parser/Substance.ne +++ b/packages/core/src/parser/Substance.ne @@ -5,8 +5,8 @@ @{% /* eslint-disable */ -import * as moo from "moo"; -import { concat, compact, flatten, last } from 'lodash' +import moo from "moo"; +import _ from 'lodash' import { optional, basicSymbols, rangeOf, rangeBetween, rangeFrom, nth, convertTokenId } from 'parser/ParserUtil' import { C, ConcreteNode, Identifier, StringLit } from "types/ast"; import { SubProg, SubStmt, Decl, Bind, ApplyPredicate, Deconstructor, Func, EqualExprs, EqualPredicates, LabelDecl, NoLabel, AutoLabel, LabelOption, TypeConsApp } from "types/substance"; @@ -45,7 +45,7 @@ const nodeData = { nodeType: "Substance" as const }; input -> statements {% ([d]): SubProg => { - const statements = flatten(d) as SubStmt[]; + const statements = _.flatten(d) as SubStmt[]; return { ...nodeData, ...rangeFrom(statements), tag: "SubProg", statements }; } %} @@ -213,7 +213,7 @@ type_constructor -> identifier type_arg_list:? {% # NOTE: only type constructors are alloed in Substance type_arg_list -> _ "(" _ sepBy1[type_constructor, ","] _ ")" {% - ([, , , d]): TypeConsApp[] => flatten(d) + ([, , , d]): TypeConsApp[] => _.flatten(d) %} # Common diff --git a/packages/core/src/parser/SubstanceParser.test.ts b/packages/core/src/parser/SubstanceParser.test.ts index 6d338587c8..73bb4431bf 100644 --- a/packages/core/src/parser/SubstanceParser.test.ts +++ b/packages/core/src/parser/SubstanceParser.test.ts @@ -1,6 +1,6 @@ import { examples } from "@penrose/examples"; import * as fs from "fs"; -import * as nearley from "nearley"; +import nearley from "nearley"; import * as path from "path"; import grammar from "./SubstanceParser"; diff --git a/packages/core/src/parser/macros.ne b/packages/core/src/parser/macros.ne index 3fa7b4efbf..80e2dd791f 100644 --- a/packages/core/src/parser/macros.ne +++ b/packages/core/src/parser/macros.ne @@ -1,7 +1,7 @@ sepBy1[ITEM, SEP] -> $ITEM (_ $SEP _ $ITEM):* (_ $SEP):? {% ([first, rest]) => { const restNodes = rest.map((ts: any[]) => ts[3]); - return concat(first, ...restNodes); + return _.concat(first, ...restNodes); } %} @@ -10,6 +10,6 @@ sepBy[ITEM, SEP] | $ITEM (_ $SEP _ $ITEM):* (_ $SEP):? {% ([first, rest]) => { const restNodes = rest.map((ts: any[]) => ts[3]); - return concat(first, ...restNodes); + return _.concat(first, ...restNodes); } %} diff --git a/packages/core/src/renderer/Path.ts b/packages/core/src/renderer/Path.ts index 630ab58190..7ed9fa5f77 100644 --- a/packages/core/src/renderer/Path.ts +++ b/packages/core/src/renderer/Path.ts @@ -1,4 +1,4 @@ -import { flatten } from "lodash"; +import _ from "lodash"; import { BoolV, ColorV, FloatV, PathCmd, StrV, SubPath } from "types/value"; import { getArrowhead, @@ -21,7 +21,7 @@ const toPathString = ( console.error("WARNING: empty path"); return ""; } - const pathStr = flatten( + const pathStr = _.flatten( // the `number[]` type annotation is necessary to ensure that a compile // error occurs here if more `SubPath` subtypes are added in the future contents.map((c: SubPath): number[] => { diff --git a/packages/core/src/synthesis/Mutation.ts b/packages/core/src/synthesis/Mutation.ts index 7b514f3514..7726f0916f 100644 --- a/packages/core/src/synthesis/Mutation.ts +++ b/packages/core/src/synthesis/Mutation.ts @@ -12,7 +12,7 @@ import { } from "analysis/SubstanceAnalysis"; import { prettyStmt, prettySubNode } from "compiler/Substance"; import { dummyIdentifier } from "engine/EngineUtils"; -import { range, without } from "lodash"; +import _ from "lodash"; import { A, Identifier } from "types/ast"; import { ApplyConstructor, @@ -588,7 +588,7 @@ const pairs = (list: T[]): [T, T][] => { export const enumSwapStmtArgs = (stmt: SubStmt): SwapStmtArgs[] => { if (stmt.tag === "ApplyPredicate" && stmt.args.length > 1) { - const indexPairs: [number, number][] = pairs(range(0, stmt.args.length)); + const indexPairs: [number, number][] = pairs(_.range(0, stmt.args.length)); return indexPairs.map(([elem1, elem2]: [number, number]) => ({ tag: "SwapStmtArgs", stmt, @@ -618,7 +618,9 @@ export const enumSwapExprArgs = (stmt: SubStmt): SwapExprArgs[] => { expr.tag === "Func") && expr.args.length > 1 ) { - const indexPairs: [number, number][] = pairs(range(0, expr.args.length)); + const indexPairs: [number, number][] = pairs( + _.range(0, expr.args.length) + ); return indexPairs.map(([elem1, elem2]: [number, number]) => ({ tag: "SwapExprArgs", stmt, @@ -653,7 +655,7 @@ export const enumReplaceStmtName = ( const matchingNames: string[] = matchSignatures(stmt, cxt.env).map( (decl) => decl.name.value ); - const options = without(matchingNames, stmt.name.value); + const options = _.without(matchingNames, stmt.name.value); return options.map((name: string) => ({ tag: "ReplaceStmtName", stmt, @@ -686,7 +688,7 @@ export const enumReplaceExprName = ( const matchingNames: string[] = matchSignatures(expr, cxt.env).map( (decl) => decl.name.value ); - const options = without(matchingNames, expr.name.value); + const options = _.without(matchingNames, expr.name.value); return options.map((name: string) => ({ tag: "ReplaceExprName", stmt, diff --git a/packages/core/src/synthesis/Search.test.ts b/packages/core/src/synthesis/Search.test.ts index 25df89a01e..789cc8e191 100644 --- a/packages/core/src/synthesis/Search.test.ts +++ b/packages/core/src/synthesis/Search.test.ts @@ -1,8 +1,8 @@ import { sortStmts, typeOf } from "analysis/SubstanceAnalysis"; import { prettyStmt } from "compiler/Substance"; -import { cloneDeep, minBy } from "lodash"; -import { createChoice } from "pandemonium/choice"; -import { applyDiff, rdiffResult } from "recursive-diff"; +import _ from "lodash"; +import pc from "pandemonium/choice"; +import rdiff from "recursive-diff"; import seedrandom from "seedrandom"; import { A } from "types/ast"; import { SubProg, SubRes } from "types/substance"; @@ -34,7 +34,7 @@ import { import { initContext } from "./Synthesizer"; const RNG = seedrandom("seed5"); -const choice: (array: Array) => T = createChoice(RNG); +const choice: (array: Array) => T = pc.createChoice(RNG); const domainSrc = ` type Set @@ -193,11 +193,11 @@ describe("AST diff tests", () => { `; const ast1: SubProg = getSubRes(domainSrc, prog1)[0].ast; const ast2: SubProg = getSubRes(domainSrc, prog2)[0].ast; - const diffs: rdiffResult[] = diffSubProgs(ast1, ast2); + const diffs: rdiff.rdiffResult[] = diffSubProgs(ast1, ast2); // because we filtered out all the noisy diffs, the exact formatting should not matter much expect(diffs).toHaveLength(2); // NOTE: `applyDiff` actually mutates the object :( - const ast2From1 = applyDiff(cloneDeep(ast1), diffs); + const ast2From1 = rdiff.applyDiff(_.cloneDeep(ast1), diffs); // the exact objects won't be equal, because the ASTs don't have the same positional info expect(ast2From1).not.toEqual(ast2); // ...but the ASTs are actually the same, which can be shown by checking the trees @@ -313,7 +313,7 @@ describe("Mutation recognition tests", () => { const ast2: SubProg = getSubRes(domainSrc, prog2)[0].ast; const ctx = initContext(env, "existing", "distinct", "test2"); const paths = enumerateMutationPaths(ast1, ast2, ctx, 5); - const shortestPath = minBy(paths, (p) => p.mutations.length); + const shortestPath = _.minBy(paths, (p) => p.mutations.length); expect(shortestPath?.mutations).toHaveLength(3); expect(shortestPath?.mutations.map((m) => m.tag)).toContain("SwapStmtArgs"); expect(shortestPath?.mutations.map((m) => m.tag)).toContain( diff --git a/packages/core/src/synthesis/Search.ts b/packages/core/src/synthesis/Search.ts index a8f25b983d..4e03efc1bc 100644 --- a/packages/core/src/synthesis/Search.ts +++ b/packages/core/src/synthesis/Search.ts @@ -9,16 +9,8 @@ import { subProg, } from "analysis/SubstanceAnalysis"; import { prettyStmt, prettySubstance } from "compiler/Substance"; -import { - cloneDeep, - difference, - get, - intersectionWith, - sortBy, - uniqBy, - zipWith, -} from "lodash"; -import { applyDiff, getDiff, rdiffResult } from "recursive-diff"; +import _ from "lodash"; +import rdiff from "recursive-diff"; import { Add, addMutation, @@ -45,7 +37,7 @@ import { type DiffType = AbstractNode["tag"]; export interface StmtDiff { - diff: rdiffResult; + diff: rdiff.rdiffResult; stmt: SubStmt; diffType?: DiffType; originalValue: any; @@ -61,7 +53,7 @@ export interface UpdateDiff { diffType: "Update"; source: SubStmt; result: SubStmt; - rawDiff: rdiffResult[]; + rawDiff: rdiff.rdiffResult[]; stmtDiff: StmtDiff[]; } @@ -84,11 +76,11 @@ export interface DeleteDiff { export const diffSubProgs = ( left: SubProg, right: SubProg -): rdiffResult[] => { - const diffs: rdiffResult[] = getDiff(left, right); +): rdiff.rdiffResult[] => { + const diffs: rdiff.rdiffResult[] = rdiff.getDiff(left, right); // remove all diffs related to meta-properties - const concreteDiffs: rdiffResult[] = diffs.filter( - (diff: rdiffResult) => + const concreteDiffs: rdiff.rdiffResult[] = diffs.filter( + (diff: rdiff.rdiffResult) => !diff.path.some((key: string | number) => metaProps.includes(key.toString()) ) @@ -110,7 +102,7 @@ export const diffSubStmts = ( // normalize the statement orderings of both ASTs first const [leftSorted, rightSorted] = [sortStmts(left), sortStmts(right)]; // compute the exact diffs between two normalized ASTs - const exactDiffs: rdiffResult[] = diffSubProgs(leftSorted, rightSorted); + const exactDiffs: rdiff.rdiffResult[] = diffSubProgs(leftSorted, rightSorted); return exactDiffs.map((d) => toStmtDiff(d, leftSorted)); }; @@ -179,14 +171,18 @@ const children = (node: SubNode): SubNode[] => { */ export const similarNodes = (left: SubNode, right: SubNode): boolean => { const equalNodes = nodesEqual(left, right); - const similarChildren = intersectionWith( + const similarChildren = _.intersectionWith( children(left), children(right), similarNodes ); - const similarLeft = intersectionWith([left], children(right), similarNodes); - const similarRight = intersectionWith(children(left), [right], similarNodes); + const similarLeft = _.intersectionWith([left], children(right), similarNodes); + const similarRight = _.intersectionWith( + children(left), + [right], + similarNodes + ); // console.log( // prettySubNode(left as any), @@ -214,10 +210,10 @@ interface SimilarMapping { export const subProgDiffs = (left: SubProg, right: SubProg): DiffSet => { const commonStmts = intersection(left, right); const leftFiltered = left.statements.filter((a) => { - return intersectionWith(commonStmts, [a], nodesEqual).length === 0; + return _.intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); const rightFiltered = right.statements.filter((a) => { - return intersectionWith(commonStmts, [a], nodesEqual).length === 0; + return _.intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); const similarMap = similarMappings(leftFiltered, rightFiltered); @@ -229,12 +225,12 @@ export const subProgDiffs = (left: SubProg, right: SubProg): DiffSet => { const deleted: DeleteDiff[] = leftFiltered .filter( - (s) => intersectionWith([s], updatedSource, nodesEqual).length === 0 + (s) => _.intersectionWith([s], updatedSource, nodesEqual).length === 0 ) .map((s) => ({ diffType: "Delete", source: s })); const add: AddDiff[] = rightFiltered .filter( - (s) => intersectionWith([s], updatedResult, nodesEqual).length === 0 + (s) => _.intersectionWith([s], updatedResult, nodesEqual).length === 0 ) .map((s) => ({ diffType: "Add", source: s })); return { update, add, delete: deleted }; @@ -272,9 +268,9 @@ const toUpdateDiff = ( picked: SubStmt[], { similarStmts, source }: SimilarMapping ): UpdateDiff | undefined => { - const result = difference(similarStmts, picked)[0]; // TODO: insert ranking algorithm here + const result = _.difference(similarStmts, picked)[0]; // TODO: insert ranking algorithm here if (result === undefined) return undefined; - const rawDiffs = getDiff(cleanNode(source), cleanNode(result)); + const rawDiffs = rdiff.getDiff(cleanNode(source), cleanNode(result)); return { diffType: "Update", source, @@ -304,18 +300,18 @@ export const similarMappings = ( mappings.push({ source: stmt, // HACK: for consistent ordering - similarStmts: sortBy(similarSet, prettyStmt), + similarStmts: _.sortBy(similarSet, prettyStmt), }); } return mappings; }; export const rawToStmtDiff = ( - diff: rdiffResult, + diff: rdiff.rdiffResult, source: SubStmt ): StmtDiff => { const { path } = diff; - const originalValue = get(source, path); + const originalValue = _.get(source, path); return { diff, stmt: source, @@ -323,11 +319,14 @@ export const rawToStmtDiff = ( originalValue, }; }; -export const toStmtDiff = (diff: rdiffResult, ast: SubProg): StmtDiff => { +export const toStmtDiff = ( + diff: rdiff.rdiffResult, + ast: SubProg +): StmtDiff => { const [, stmtIndex, ...path] = diff.path; // TODO: encode the paths to AST in a more principled way const stmt = getStmt(ast, stmtIndex as number); - const originalValue = get(stmt, path); + const originalValue = _.get(stmt, path); const stmtDiff = { ...diff, path, @@ -347,7 +346,7 @@ export const toStmtDiff = (diff: rdiffResult, ast: SubProg): StmtDiff => { * @param diff the diff defined for the node * @returns */ -const diffType = (node: AbstractNode, diff: rdiffResult): DiffType => { +const diffType = (node: AbstractNode, diff: rdiff.rdiffResult): DiffType => { let tag = undefined; let currNode: AbstractNode = node; for (const prop of diff.path) { @@ -374,7 +373,7 @@ export const applyStmtDiff = ( ...prog, statements: prog.statements.map((s: SubStmt) => { if (s === stmt) { - const res: SubStmt = applyDiff(cloneDeep(s), [diff]); + const res: SubStmt = rdiff.applyDiff(_.cloneDeep(s), [diff]); return res; } else return s; }), @@ -405,11 +404,14 @@ export const applyStmtDiffs = ( ): SubProg => ({ ...prog, statements: prog.statements.map((stmt: SubStmt) => - applyDiff(stmt, findDiffs(stmt, diffs)) + rdiff.applyDiff(stmt, findDiffs(stmt, diffs)) ), }); -export const findDiffs = (stmt: SubStmt, diffs: StmtDiff[]): rdiffResult[] => +export const findDiffs = ( + stmt: SubStmt, + diffs: StmtDiff[] +): rdiff.rdiffResult[] => diffs.filter((d) => d.stmt === stmt).map((d) => d.diff); //#endregion @@ -566,7 +568,7 @@ export const enumerateMutationPaths = ( executeMutation(m, progToGrow, cxt) ); // pack the resulting programs with their updated mutation path - return zipWith( + return _.zipWith( resultProgs, possibleMutations, (p, mutation): MutatedSubProg => ({ @@ -579,7 +581,7 @@ export const enumerateMutationPaths = ( ) .flat(); // "Observational equivalence": remove all candidates that lead to the same output - candidates = uniqBy(candidates, (c) => prettySubstance(c.prog)); + candidates = _.uniqBy(candidates, (c) => prettySubstance(c.prog)); // HACK: using string-based check instead of AST check const matches = candidates.filter( (p) => prettySubstance(p.prog) === prettySubstance(destProg) diff --git a/packages/core/src/synthesis/Synthesizer.ts b/packages/core/src/synthesis/Synthesizer.ts index eaa1cb3ad2..5e7eab4b99 100644 --- a/packages/core/src/synthesis/Synthesizer.ts +++ b/packages/core/src/synthesis/Synthesizer.ts @@ -17,12 +17,12 @@ import { } from "analysis/SubstanceAnalysis"; import { subTypesOf } from "compiler/Domain"; import { prettyStmt, prettySubstance } from "compiler/Substance"; -import consola, { LogLevel } from "consola"; +import consola from "consola"; import { dummyIdentifier } from "engine/EngineUtils"; import im from "immutable"; -import { cloneDeep, compact, range, times, without } from "lodash"; -import { createChoice } from "pandemonium/choice"; -import { createRandom } from "pandemonium/random"; +import _ from "lodash"; +import pc from "pandemonium/choice"; +import pr from "pandemonium/random"; import seedrandom from "seedrandom"; import { Add, @@ -75,7 +75,7 @@ import { type RandomFunction = (min: number, max: number) => number; const log = consola - .create({ level: LogLevel.Info }) + .create({ level: (consola as any).LogLevel.Info }) .withScope("Substance Synthesizer"); //#region Synthesizer setting types @@ -135,7 +135,7 @@ export const initContext = ( argReuse, names: im.Map(), declaredIDs: im.Map[]>(), - choice: createChoice(rng), + choice: pc.createChoice(rng), env, }; return env.varIDs.reduce((c, id) => { @@ -251,7 +251,7 @@ const findIDs = ( typeStrs: string[], excludeList?: Identifier[] ): Identifier[] => { - const possibleIDs: Identifier[] = compact( + const possibleIDs: Identifier[] = _.compact( typeStrs.flatMap((typeStr) => ctx.declaredIDs.get(typeStr)) ); const candidates = possibleIDs.filter((id) => @@ -326,7 +326,7 @@ export class Synthesizer { if (subRes) { const [subEnv, env] = subRes; this.env = env; - this.template = cloneDeep(subEnv.ast); + this.template = _.cloneDeep(subEnv.ast); log.debug(`Loaded template:\n${prettySubstance(this.template)}`); } else { this.env = env; @@ -337,17 +337,17 @@ export class Synthesizer { }; } // initialize the current program as the template - this.currentProg = cloneDeep(this.template); + this.currentProg = _.cloneDeep(this.template); this.setting = setting; this.currentMutations = []; // use the seed to create random generation functions this.rng = seedrandom(seed); - this.choice = createChoice(this.rng); - this.random = createRandom(this.rng); + this.choice = pc.createChoice(this.rng); + this.random = pr.createRandom(this.rng); } reset = (): void => { - this.currentProg = cloneDeep(this.template); + this.currentProg = _.cloneDeep(this.template); this.currentMutations = []; }; @@ -366,7 +366,7 @@ export class Synthesizer { * @returns an array of Substance programs and some metadata (e.g. mutation operation record) */ generateSubstances = (numProgs: number): SynthesizedSubstance[] => - times(numProgs, (n: number) => { + _.times(numProgs, (n: number) => { const sub = this.generateSubstance(); // DEBUG: report results log.info( @@ -381,7 +381,7 @@ export class Synthesizer { generateSubstance = (): SynthesizedSubstance => { const numStmts = this.random(...this.setting.mutationCount); - range(numStmts).reduce( + _.range(numStmts).reduce( (ctx: SynthesisContext, n: number): SynthesisContext => { const newCtx = this.mutateProgram(ctx); log.debug( @@ -449,22 +449,22 @@ export class Synthesizer { // const ops = enumerateMutations(stmt, this.currentProg, ctx); const ops: (Mutation | undefined)[] = [ checkSwapStmtArgs(stmt, (p: ApplyPredicate) => { - const indices = range(0, p.args.length); + const indices = _.range(0, p.args.length); const elem1 = this.choice(indices); - const elem2 = this.choice(without(indices, elem1)); + const elem2 = this.choice(_.without(indices, elem1)); return [elem1, elem2]; }), checkSwapExprArgs(stmt, (f: ArgExpr) => { - const indices = range(0, f.args.length); + const indices = _.range(0, f.args.length); const elem1 = this.choice(indices); - const elem2 = this.choice(without(indices, elem1)); + const elem2 = this.choice(_.without(indices, elem1)); return [elem1, elem2]; }), checkReplaceStmtName(stmt, (p: ApplyPredicate) => { const matchingNames: string[] = matchSignatures(p, ctx.env).map( (decl) => decl.name.value ); - const options = without(matchingNames, p.name.value); + const options = _.without(matchingNames, p.name.value); if (options.length > 0) { return this.choice(options); } else return undefined; @@ -473,7 +473,7 @@ export class Synthesizer { const matchingNames: string[] = matchSignatures(e, ctx.env).map( (decl) => decl.name.value ); - const options = without(matchingNames, e.name.value); + const options = _.without(matchingNames, e.name.value); if (options.length > 0) { return this.choice(options); } else return undefined; @@ -489,7 +489,7 @@ export class Synthesizer { return swapOptions ? this.choice(swapOptions) : undefined; }, (p: ApplyPredicate) => { - const indices = range(0, p.args.length); + const indices = _.range(0, p.args.length); return this.choice(indices); } ), @@ -504,7 +504,7 @@ export class Synthesizer { return swapOptions ? this.choice(swapOptions) : undefined; }, (p: ApplyFunction | ApplyConstructor | Func) => { - const indices = range(0, p.args.length); + const indices = _.range(0, p.args.length); return this.choice(indices); } ), @@ -562,7 +562,7 @@ export class Synthesizer { } ), ]; - const mutations = compact(ops); + const mutations = _.compact(ops); log.debug( `Available mutations for ${prettyStmt(stmt)}:\n${showMutations( mutations diff --git a/packages/core/src/utils/CollectLabels.ts b/packages/core/src/utils/CollectLabels.ts index 09aa38231d..143a1c3084 100644 --- a/packages/core/src/utils/CollectLabels.ts +++ b/packages/core/src/utils/CollectLabels.ts @@ -6,6 +6,8 @@ import { mathjax } from "mathjax-full/js/mathjax.js"; import { SVG } from "mathjax-full/js/output/svg.js"; import { InputMeta } from "shapes/Samplers"; import { ShapeDef, shapedefs } from "shapes/Shapes"; +// @ts-expect-error missing types +import svgflatten from "svg-flatten"; import svgpath from "svgpath"; import * as ad from "types/ad"; import { PenroseError } from "types/errors"; @@ -18,9 +20,6 @@ import { getAdValueAsNumber, getAdValueAsString, } from "./Util"; -/* eslint eslint-comments/no-use: off */ -// eslint-disable-next-line @typescript-eslint/no-var-requires -const svgflatten = require("svg-flatten"); // https://github.com/mathjax/MathJax-demos-node/blob/master/direct/tex2svg // const adaptor = chooseAdaptor(); diff --git a/packages/core/src/utils/Graph.ts b/packages/core/src/utils/Graph.ts index e961debadb..515773baab 100644 --- a/packages/core/src/utils/Graph.ts +++ b/packages/core/src/utils/Graph.ts @@ -1,4 +1,4 @@ -import * as graphlib from "graphlib"; +import graphlib from "graphlib"; export interface Edge { v: NodeId; diff --git a/packages/core/src/utils/Util.ts b/packages/core/src/utils/Util.ts index 96fd8181ba..1e329d0fab 100644 --- a/packages/core/src/utils/Util.ts +++ b/packages/core/src/utils/Util.ts @@ -1,5 +1,4 @@ -import * as _ from "lodash"; -import { times } from "lodash"; +import _ from "lodash"; import seedrandom from "seedrandom"; import { LineProps } from "shapes/Line"; import { ShapeType } from "shapes/Shapes"; @@ -119,7 +118,7 @@ export const randFloats = ( rng: seedrandom.prng, count: number, [min, max]: [number, number] -): number[] => times(count, () => randFloat(rng, min, max)); +): number[] => _.times(count, () => randFloat(rng, min, max)); /** * Generate a random float. The maximum is exclusive and the minimum is inclusive @@ -852,7 +851,6 @@ export const getAdValueAsString = ( switch (prop.tag) { case "FloatV": if (typeof prop.contents === "number") return prop.contents.toString(); - if (typeof prop.contents === "string") return prop.contents; break; case "StrV": return prop.contents; @@ -880,7 +878,6 @@ export const getAdValueAsNumber = ( switch (prop.tag) { case "FloatV": if (typeof prop.contents === "number") return prop.contents; - if (typeof prop.contents === "string") return parseFloat(prop.contents); break; case "StrV": return parseFloat(prop.contents); diff --git a/packages/core/src/utils/toCustomAD.ts b/packages/core/src/utils/toCustomAD.ts index 6098e824ce..084e032edd 100644 --- a/packages/core/src/utils/toCustomAD.ts +++ b/packages/core/src/utils/toCustomAD.ts @@ -408,4 +408,4 @@ export default function (fileInfo: FileInfo, api: API): string { } return root.toSource(); } -module.exports.parser = "ts"; +export const parser = "ts"; diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index a3e23214ab..815631221b 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -2,8 +2,8 @@ "compilerOptions": { "baseUrl": "./", "outDir": "build/dist", - "module": "es2015", - "target": "es5", + "module": "es2022", + "target": "es2017", "lib": ["es5", "es6", "es7", "esnext", "dom"], "sourceMap": true, "allowJs": true, diff --git a/packages/editor/package.json b/packages/editor/package.json index 6cae79791f..fdb4af6f98 100644 --- a/packages/editor/package.json +++ b/packages/editor/package.json @@ -75,7 +75,6 @@ "@types/uuid": "^8.3.4", "@vitejs/plugin-react": "^1.3.0", "shx": "^0.3.3", - "typescript": "^4.6.3", "vite": "^2.9.9" } } diff --git a/packages/examples/index.ts b/packages/examples/index.ts index 1371857545..20d7a042fa 100644 --- a/packages/examples/index.ts +++ b/packages/examples/index.ts @@ -1,4 +1,4 @@ import examples from "./dist/index"; -import * as registry from "./src/registry.json"; +import registry from "./src/registry.json"; export { examples, registry }; diff --git a/packages/roger/package.json b/packages/roger/package.json index e7e9be773e..900f97b28b 100644 --- a/packages/roger/package.json +++ b/packages/roger/package.json @@ -38,8 +38,7 @@ "oclif": "^3", "shx": "^0.3.3", "ts-node": "^10.2.1", - "tslib": "^2.3.1", - "typescript": "^4.4.3" + "tslib": "^2.3.1" }, "oclif": { "bin": "roger", diff --git a/packages/roger/tsconfig.json b/packages/roger/tsconfig.json index 0104922ad4..8f90b2d525 100644 --- a/packages/roger/tsconfig.json +++ b/packages/roger/tsconfig.json @@ -7,6 +7,7 @@ "module": "commonjs", "outDir": "dist", "rootDir": "src", + "skipLibCheck": true, "strict": true, "target": "es2019", "noImplicitAny": false diff --git a/packages/synthesizer-ui/package.json b/packages/synthesizer-ui/package.json index 12868bbae3..961690f08b 100644 --- a/packages/synthesizer-ui/package.json +++ b/packages/synthesizer-ui/package.json @@ -59,7 +59,6 @@ "@types/react": "^17.0.33", "@types/react-dom": "^17.0.10", "@vitejs/plugin-react": "^1.0.7", - "typescript": "^4.5.4", "vite": "^2.8.0" } } diff --git a/packages/synthesizer/index.ts b/packages/synthesizer/index.ts index 1e26cb9bdd..c3c598d304 100644 --- a/packages/synthesizer/index.ts +++ b/packages/synthesizer/index.ts @@ -1,4 +1,5 @@ -require("global-jsdom/register"); +import "global-jsdom/register"; // must be first + import { compileDomain, compileSubstance, diff --git a/packages/synthesizer/package.json b/packages/synthesizer/package.json index e4a3c70e9a..5bd6c63f23 100644 --- a/packages/synthesizer/package.json +++ b/packages/synthesizer/package.json @@ -9,6 +9,7 @@ ], "homepage": "http://penrose.cs.cmu.edu/", "license": "MIT", + "type": "module", "main": "index.ts", "directories": { "test": "__tests__" @@ -27,7 +28,7 @@ "build": ":", "build-decls": ":", "typecheck": "tsc --noEmit", - "start": "ts-node ./index.ts", + "start": "ts-node --esm ./index.ts", "set-example": "yarn start __tests__/setTheory.dsl --substance=__tests__/template.sub --style=__tests__/venn.sty --path=../automator/progs --synth-setting=__tests__/set-settings.json --num-programs=30", "collinear-example": "yarn start ../examples/src/geometry-domain/geometry.dsl --substance=../examples/src/geometry-domain/textbook_problems/c01p01.sub --style=../examples/src/geometry-domain/euclidean.sty --path=../automator/progs --synth-setting=__tests__/geo-settings.json --num-programs=30", "rect-example": "yarn start ../examples/src/geometry-domain/geometry.dsl --substance=__tests__/rect.sub --style=../examples/src/geometry-domain/euclidean.sty --path=../automator/progs --synth-setting=__tests__/rect-settings.json --num-programs=10", @@ -47,7 +48,6 @@ }, "devDependencies": { "@types/node": "^12.12.68", - "ts-node": "^9.0.0", - "typescript": "^4.1.3" + "ts-node": "^10.9.1" } } diff --git a/packages/synthesizer/tsconfig.json b/packages/synthesizer/tsconfig.json index b44e40e115..f6d67ff657 100644 --- a/packages/synthesizer/tsconfig.json +++ b/packages/synthesizer/tsconfig.json @@ -1,6 +1,8 @@ { "compilerOptions": { + "module": "es2022", "esModuleInterop": true, + "moduleResolution": "Node", "sourceMap": true } } diff --git a/yarn.lock b/yarn.lock index a6134456d4..37d008e7c8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2186,6 +2186,13 @@ dependencies: "@cspotcode/source-map-consumer" "0.8.0" +"@cspotcode/source-map-support@^0.8.0": + version "0.8.1" + resolved "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz#00629c35a688e05a88b1cda684fb9d5e73f000a1" + integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== + dependencies: + "@jridgewell/trace-mapping" "0.3.9" + "@datastructures-js/heap@^3.2.0": version "3.2.0" resolved "https://registry.yarnpkg.com/@datastructures-js/heap/-/heap-3.2.0.tgz#d8fcdbf58c462c8a3f0fdfd9c6a57ca11505321e" @@ -3110,6 +3117,14 @@ resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz#771a1d8d744eeb71b6adb35808e1a6c7b9b8c8ec" integrity sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg== +"@jridgewell/trace-mapping@0.3.9": + version "0.3.9" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@jridgewell/trace-mapping@^0.3.0": version "0.3.4" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.4.tgz#f6a0832dffd5b8a6aaa633b7d9f8e8e94c83a0c3" @@ -18890,10 +18905,10 @@ prepend-http@^2.0.0: resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= -prettier-plugin-organize-imports@^2.3.4: - version "2.3.4" - resolved "https://registry.yarnpkg.com/prettier-plugin-organize-imports/-/prettier-plugin-organize-imports-2.3.4.tgz#65473861ae5ab7960439fff270a2258558fbe9ba" - integrity sha512-R8o23sf5iVL/U71h9SFUdhdOEPsi3nm42FD/oDYIZ2PQa4TNWWuWecxln6jlIQzpZTDMUeO1NicJP6lLn2TtRw== +prettier-plugin-organize-imports@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/prettier-plugin-organize-imports/-/prettier-plugin-organize-imports-3.2.1.tgz#7e0e0a18457e0166e740daaff1aed1c08069fcb9" + integrity sha512-bty7C2Ecard5EOXirtzeCAqj4FU4epeuWrQt/Z+sh8UVEpBlBZ3m3KNPz2kFu7KgRTQx/C9o4/TdquPD1jOqjQ== prettier@2.2.1: version "2.2.1" @@ -21403,7 +21418,7 @@ source-map-resolve@^0.5.0: source-map-url "^0.4.0" urix "^0.1.0" -source-map-support@^0.5.16, source-map-support@^0.5.17, source-map-support@^0.5.6, source-map-support@~0.5.12, source-map-support@~0.5.20: +source-map-support@^0.5.16, source-map-support@^0.5.6, source-map-support@~0.5.12, source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== @@ -22584,16 +22599,23 @@ ts-node@^10.2.1: v8-compile-cache-lib "^3.0.0" yn "3.1.1" -ts-node@^9.0.0: - version "9.1.1" - resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-9.1.1.tgz#51a9a450a3e959401bda5f004a72d54b936d376d" - integrity sha512-hPlt7ZACERQGf03M253ytLY3dHbGNGrAq9qIHWUY9XHYl1z7wYngSr3OQ5xmui8o2AaxsONxIzjafLUiWBo1Fg== +ts-node@^10.9.1: + version "10.9.1" + resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.1.tgz#e73de9102958af9e1f0b168a6ff320e25adcff4b" + integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw== dependencies: + "@cspotcode/source-map-support" "^0.8.0" + "@tsconfig/node10" "^1.0.7" + "@tsconfig/node12" "^1.0.7" + "@tsconfig/node14" "^1.0.0" + "@tsconfig/node16" "^1.0.2" + acorn "^8.4.1" + acorn-walk "^8.1.1" arg "^4.1.0" create-require "^1.1.0" diff "^4.0.1" make-error "^1.1.1" - source-map-support "^0.5.17" + v8-compile-cache-lib "^3.0.1" yn "3.1.1" ts-pnp@^1.1.6: @@ -22774,20 +22796,10 @@ typedoc@^0.22.11: minimatch "^3.0.4" shiki "^0.10.0" -typescript@^4.1.3: - version "4.5.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.4.tgz#a17d3a0263bf5c8723b9c52f43c5084edf13c2e8" - integrity sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg== - -typescript@^4.4.3, typescript@^4.6.3: - version "4.6.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.4.tgz#caa78bbc3a59e6a5c510d35703f6a09877ce45e9" - integrity sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg== - -typescript@^4.4.4, typescript@^4.5.4: - version "4.5.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" - integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== +typescript@^4.9.4: + version "4.9.4" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.4.tgz#a2a3d2756c079abda241d75f149df9d561091e78" + integrity sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg== ua-parser-js@^0.7.30: version "0.7.31" @@ -23203,7 +23215,7 @@ uuid@^8.3.2: resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== -v8-compile-cache-lib@^3.0.0: +v8-compile-cache-lib@^3.0.0, v8-compile-cache-lib@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==