Merge katex and page evaluation in; resolve conflicts

This commit is contained in:
2022-04-09 02:53:08 -05:00
6 changed files with 539 additions and 0 deletions

View File

@@ -1,5 +1,12 @@
<script setup lang="ts">
import Home from './components/Home.vue'
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from './components/HelloWorld.vue'
import { MathStatement } from './support/parse'
import { MathPage } from './support/page'
(window as any).Stmt = MathStatement
;(window as any).Pg = MathPage
</script>
<template>

105
src/support/page.ts Normal file
View File

@@ -0,0 +1,105 @@
import {MathStatement} from './parse'
import * as math from 'mathjs'
import {DepGraph} from 'dependency-graph'
import { v4 as uuidv4 } from 'uuid'
import {EvaluationResult, StatementID, VariableName} from '../types'
/**
* Wrapper for a page containing multiple interrelated mathematical statements.
*/
export class MathPage {
/** The statements on the page. */
protected statements: Record<StatementID, MathStatement> = {}
constructor(
/** Unique page ID. */
public readonly id: string,
) {}
/** Add a statement to this page. */
addStatement(statement: MathStatement): this {
this.statements[statement.id] = statement
return this
}
/** Parse the math expression and add it to the page as a statement. */
addRaw(statement: string): this {
return this.addStatement(new MathStatement(uuidv4() as StatementID, statement))
}
/** Get all symbols referenced by statements on this page. */
symbols(): math.SymbolNode[] {
return Object.values(this.statements)
.map(x => x.symbols())
.reduce((carry, current) => current.concat(carry), [])
}
/** Get all symbols defined on this page. */
defines(): math.SymbolNode[] {
return Object.values(this.statements)
.map(x => x.defines())
.reduce((carry, current) => current.concat(carry), [])
}
/** Get all symbols used on this page. */
uses(): math.SymbolNode[] {
return Object.values(this.statements)
.map(x => x.uses())
.reduce((carry, current) => current.concat(carry), [])
}
/** Get a mapping of symbol names to the statements where they are defined. */
definers(): Record<VariableName, MathStatement> {
const definers: Record<VariableName, MathStatement> = {}
for ( const statement of Object.values(this.statements) ) {
for ( const symbol of statement.defines() ) {
definers[symbol.name as VariableName] = statement
}
}
return definers
}
/** Get the dependency graph of variable declarations between statements on this page. */
dependencies(): DepGraph<MathStatement> {
const graph = new DepGraph<MathStatement>()
const defined: Record<VariableName, MathStatement> = this.definers()
for ( const statement of Object.values(this.statements) ) {
graph.addNode(statement.id, statement)
}
for ( const statement of Object.values(this.statements) ) {
for ( const symbol of statement.uses() ) {
const provider = defined[symbol.name as VariableName]
if ( !provider ) {
throw new Error('No provider for undefined symbol: ' + symbol.name)
}
graph.addDependency(statement.id, provider.id)
}
}
return graph
}
/** Evaluate the current state of the page and get the result. */
evaluate(): EvaluationResult {
const evaluations: Record<StatementID, any> = {}
const scope: Record<VariableName, any> = {}
const graph = this.dependencies()
for ( const node of graph.overallOrder() ) {
const stmt = this.statements[node as StatementID]
evaluations[stmt.id] = stmt.parse()
.compile()
.evaluate(scope)
}
return {
variables: scope,
statements: evaluations,
}
}
}

309
src/support/parse.ts Normal file
View File

@@ -0,0 +1,309 @@
import * as math from 'mathjs'
import katex from 'katex'
import {HTMLString, LaTeXString, StatementID} from '../types'
/** Base class for walks over MathNode trees. */
export abstract class MathNodeWalk<TReturn> {
walk(node: math.MathNode): TReturn {
if ( math.isAccessorNode(node) ) {
return this.walkAccessorNode(node)
} else if ( math.isArrayNode(node) ) {
return this.walkArrayNode(node)
} else if ( math.isAssignmentNode(node) ) {
return this.walkAssignmentNode(node)
} else if ( math.isBlockNode(node) ) {
return this.walkBlockNode(node)
} else if ( math.isConditionalNode(node) ) {
return this.walkConditionalNode(node)
} else if ( math.isConstantNode(node) ) {
return this.walkConstantNode(node)
} else if ( math.isFunctionAssignmentNode(node) ) {
return this.walkFunctionAssignmentNode(node)
} else if ( math.isFunctionNode(node) ) {
return this.walkFunctionNode(node)
} else if ( math.isIndexNode(node) ) {
return this.walkIndexNode(node)
} else if ( math.isObjectNode(node) ) {
return this.walkObjectNode(node)
} else if ( math.isOperatorNode(node) ) {
return this.walkOperatorNode(node)
} else if ( math.isParenthesisNode(node) ) {
return this.walkParenthesisNode(node)
} else if ( math.isRangeNode(node) ) {
return this.walkRangeNode(node)
} else if ( (node as unknown as any).isRelationalNode ) {
return this.walkRelationalNode(node as unknown as any)
} else if ( math.isSymbolNode(node) ) {
return this.walkSymbolNode(node)
}
throw new TypeError('Invalid MathNode: ' + node)
}
abstract walkAccessorNode(node: math.AccessorNode): TReturn
abstract walkArrayNode(node: math.ArrayNode): TReturn
abstract walkAssignmentNode(node: math.AssignmentNode): TReturn
abstract walkBlockNode(node: math.BlockNode): TReturn
abstract walkConditionalNode(node: math.ConditionalNode): TReturn
abstract walkConstantNode(node: math.ConstantNode): TReturn
abstract walkFunctionAssignmentNode(node: math.FunctionAssignmentNode): TReturn
abstract walkFunctionNode(node: math.FunctionNode): TReturn
abstract walkIndexNode(node: math.IndexNode): TReturn
abstract walkObjectNode(node: math.ObjectNode): TReturn
abstract walkOperatorNode(node: math.OperatorNode): TReturn
abstract walkParenthesisNode(node: math.ParenthesisNode): TReturn
abstract walkRangeNode(node: math.RangeNode): TReturn
abstract walkRelationalNode(node: math.RelationalNode): TReturn
abstract walkSymbolNode(node: math.SymbolNode): TReturn
}
/** A walk that accumulates all different SymbolNode instances in a tree. */
export class SymbolWalk extends MathNodeWalk<math.SymbolNode[]> {
walkAccessorNode(node: math.AccessorNode): math.SymbolNode[] {
return [
...this.walk(node.object),
...this.walk(node.index),
]
}
walkArrayNode(node: math.ArrayNode): math.SymbolNode[] {
return node.items
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), [])
}
walkAssignmentNode(node: math.AssignmentNode): math.SymbolNode[] {
return [
...this.walk(node.object),
...this.walk(node.value),
...(node.index ? this.walk(node.index) : []),
]
}
walkBlockNode(node: math.BlockNode): math.SymbolNode[] {
return node.blocks
.map(x => x.node)
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), [])
}
walkConditionalNode(node: math.ConditionalNode): math.SymbolNode[] {
return [
...this.walk(node.condition),
...this.walk(node.trueExpr),
...this.walk(node.falseExpr),
]
}
walkConstantNode(): math.SymbolNode[] {
return []
}
walkFunctionAssignmentNode(node: math.FunctionAssignmentNode): math.SymbolNode[] {
return this.walk(node.expr)
}
walkFunctionNode(node: math.FunctionNode): math.SymbolNode[] {
return [
...this.walk(node.fn),
...node.args
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), []),
]
}
walkIndexNode(node: math.IndexNode): math.SymbolNode[] {
return node.dimensions
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), [])
}
walkObjectNode(node: math.ObjectNode): math.SymbolNode[] {
return Object.values(node.properties)
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), [])
}
walkOperatorNode(node: math.OperatorNode): math.SymbolNode[] {
return node.args
.map(x => this.walk(x))
.reduce((carry, current) => carry.concat(current), [])
}
walkParenthesisNode(node: math.ParenthesisNode): math.SymbolNode[] {
return this.walk(node.content)
}
walkRangeNode(node: math.RangeNode): math.SymbolNode[] {
return [
...this.walk(node.start),
...this.walk(node.end),
...(node.step ? this.walk(node.step) : []),
]
}
walkRelationalNode(node: math.RelationalNode): math.SymbolNode[] {
return node.params
.map(x => this.walk(x))
.reduce((carry, current) => carry.concat(current), [])
}
walkSymbolNode(node: math.SymbolNode): math.SymbolNode[] {
return [node]
}
}
/** A walk that accumulates all SymbolNode instances used on the RHS of expressions. */
export class RValSymbolWalk extends SymbolWalk {
walkAssignmentNode(node: math.AssignmentNode): math.SymbolNode[] {
return this.walk(node.value)
}
walkFunctionNode(node: math.FunctionNode): math.SymbolNode[] {
return [
...this.walk(node.fn), // FIXME should this be removed? Not sure if this is rval or lval
...node.args
.map(x => this.walk(x))
.reduce((carry, current) => current.concat(carry), []),
]
}
}
/** A walk that accumulates SymbolNode instances used on the LHS of assignments. */
export class LValSymbolWalk extends SymbolWalk {
walkAccessorNode(): math.SymbolNode[] {
return []
}
walkArrayNode(): math.SymbolNode[] {
return []
}
walkAssignmentNode(node: math.AssignmentNode): math.SymbolNode[] {
if ( math.isSymbolNode(node.object) ) {
return super.walkSymbolNode(node.object)
}
return super.walkAccessorNode(node.object)
}
walkBlockNode(node: math.BlockNode): math.SymbolNode[] {
return node.blocks
.map(x => this.walk(x.node))
.reduce((carry, current) => current.concat(carry), [])
}
walkConditionalNode(): math.SymbolNode[] {
return []
}
walkConstantNode(): math.SymbolNode[] {
return []
}
walkFunctionAssignmentNode(): math.SymbolNode[] {
return []
}
walkFunctionNode(): math.SymbolNode[] {
return []
}
walkIndexNode(): math.SymbolNode[] {
return []
}
walkObjectNode(): math.SymbolNode[] {
return []
}
walkOperatorNode(): math.SymbolNode[] {
return []
}
walkParenthesisNode(node: math.ParenthesisNode): math.SymbolNode[] {
return this.walk(node.content)
}
walkRangeNode(): math.SymbolNode[] {
return []
}
walkRelationalNode(): math.SymbolNode[] {
return []
}
walkSymbolNode(): math.SymbolNode[] {
return []
}
}
/** A single mathematical statement. */
export class MathStatement {
constructor(
/** Unique ID of this statement. */
public readonly id: StatementID,
/** The raw statement input by the user. */
public readonly raw: string,
) {}
/** Parse the raw statement to an AST. */
parse(): math.MathNode {
return math.parse(this.raw)
}
/** Convert the statement to its equivalent LaTeX code. */
toLaTeX(): LaTeXString {
return this.parse().toTex() as LaTeXString
}
/** Render the statement as HTML string. */
toHTMLString(): HTMLString {
return katex.renderToString(this.toLaTeX(), {
output: 'mathml',
}) as HTMLString
}
/** Render the statement to a DOM element. */
toDOM(): HTMLSpanElement {
const node = document.createElement('span')
katex.render(this.toLaTeX(), node, {
output: 'mathml',
})
return node
}
/** Get all symbols referenced in this statement. */
symbols(): math.SymbolNode[] {
return (new SymbolWalk()).walk(this.parse())
}
/** Get all symbols defined on the LHS of this statement. */
defines(): math.SymbolNode[] {
return (new LValSymbolWalk()).walk(this.parse())
}
/** Get all symbols used on the RHS of this statement. */
uses(): math.SymbolNode[] {
return (new RValSymbolWalk()).walk(this.parse())
}
}

View File

@@ -80,3 +80,13 @@ export type Integer = TypeTag<'@app.Integer'> & number
export function isInteger(num: number): num is Integer {
return !isNaN(num) && parseInt(String(num), 10) === num
}
export type LaTeXString = TypeTag<'@app.LaTeXString'> & string
export type HTMLString = TypeTag<'@app.HTMLString'> & string
export type StatementID = TypeTag<'@app.StatementID'> & string
export type VariableName = TypeTag<'@app.VariableName'> & string
export interface EvaluationResult {
variables: Record<VariableName, any>
statements: Record<StatementID, any>
}