Repository navigation
Expand file tree
/
Copy pathmathjs.js
More file actions
376 lines (316 loc) · 11 KB
/
Copy pathmathjs.js
File metadata and controls
376 lines (316 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import {
LRLanguage,
LanguageSupport,
foldInside,
foldNodeProp,
syntaxTree
} from '@codemirror/language'
import { styleTags, tags as t } from '@lezer/highlight'
import { parser } from './lib/mathjs-parser.js'
const KEYWORDS = ['to', 'in', 'and', 'not', 'or', 'xor', 'mod']
const IDENTIFIER_START = /[_A-Za-z\xa1-\uffff]/
const IDENTIFIER_BODY = /^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*$/
const mathjsParser = parser.configure({
props: [
foldNodeProp.add({
Group: foldInside
}),
styleTags({
Number: t.number,
String: t.string,
Keyword: t.keyword,
BooleanLiteral: t.bool,
NullLiteral: t.null,
UndefinedLiteral: t.null,
Identifier: t.variableName,
PropertyName: t.propertyName,
PrefixOp: t.operator,
PostfixOp: t.operator,
PowOp: t.operator,
MultiplyOp: t.operator,
AddOp: t.operator,
RelOp: t.compareOperator,
ShiftOp: t.operator,
AndOp: t.logicOperator,
OrOp: t.logicOperator,
XorOp: t.logicOperator,
ConversionOp: t.operator,
ModOp: t.operator,
NotOp: t.logicOperator,
Operator: t.operator,
LineComment: t.lineComment,
BlockComment: t.blockComment
})
]
})
export const mathjsLanguage = LRLanguage.define({
name: 'mathjs',
parser: mathjsParser,
languageData: {
closeBrackets: {
brackets: ['(', '[', '{', '"', "'"]
},
commentTokens: {
line: '#',
block: { open: '#{', close: '#}' }
},
indentOnInput: /^\s*[\]\)\}]$/,
// Math.js identifiers support '$', and expressions commonly use these as symbol suffixes.
wordChars: '$'
}
})
/**
* Create a CodeMirror 6 language support extension for mathjs
*
* @param {function} getWorkerState - A function that gets a mathjs instance properties for the parser.
* @param {function} getParserState - A function that returns a mathjs scope.
* @returns {LanguageSupport} A CodeMirror 6 language support extension.
*/
export function mathjs(getWorkerState, getParserState) {
let cachedWorkerState = null
let cachedWorkerData = null
const autocompleteSource = (context) => {
if (isBlockedContext(context)) {
return null
}
const completionContext = getCompletionContext(context)
if (!completionContext) {
return null
}
const { from, prefix, propertyPath } = completionContext
if (prefix.length > 0 && !IDENTIFIER_START.test(prefix[0])) {
return null
}
const workerData = getWorkerData()
const parserState = getParserState()
const parserSymbols = Object.keys(parserState)
const optionsByLabel = new Map()
const pushOption = (label, type, boost = 0) => {
if (!IDENTIFIER_BODY.test(label) || !label.startsWith(prefix)) {
return
}
const existing = optionsByLabel.get(label)
if (!existing || boost > (existing.boost || 0)) {
optionsByLabel.set(label, { label, type, boost })
}
}
if (propertyPath) {
const target = resolvePropertyTarget(parserState, propertyPath)
const propertyKeys = getObjectCompletionKeys(target)
propertyKeys.forEach((key) => pushOption(key, 'property', 140))
} else {
KEYWORDS.forEach((keyword) => pushOption(keyword, 'keyword', 20))
parserSymbols.forEach((symbol) => pushOption(symbol, 'property', 100))
workerData.mathFunctions.forEach((func) => pushOption(func, 'function', 70))
workerData.mathPhysicalConstants.forEach((constant) => pushOption(constant, 'constant', 60))
workerData.numberLiterals.forEach((number) => pushOption(number, 'variable', 30))
workerData.listOfUnits.forEach((unit) => pushOption(unit, 'enum', 40))
}
const options = Array.from(optionsByLabel.values())
if (options.length === 0) {
return null
}
return {
from,
options,
validFor: /^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*$/
}
}
return new LanguageSupport(mathjsLanguage, [
mathjsLanguage.data.of({
autocomplete: autocompleteSource
})
])
function isBlockedContext(context) {
const nodeName = syntaxTree(context.state).resolveInner(context.pos, -1).name
if (nodeName === 'LineComment' || nodeName === 'BlockComment' || nodeName === 'String') {
return true
}
return false
}
function getCompletionContext(context) {
const word = context.matchBefore(/[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*/)
const line = context.state.doc.lineAt(context.pos)
const linePrefix = line.text.slice(0, context.pos - line.from)
if (word && (word.from !== word.to || context.explicit)) {
const from = word.from
const prefix = word.text
const beforeWord = line.text.slice(0, from - line.from)
const propertyPath = extractPropertyPath(beforeWord)
return { from, prefix, propertyPath }
}
if (!context.explicit) {
return null
}
const propertyPath = extractPropertyPath(linePrefix)
if (!propertyPath) {
return null
}
return {
from: context.pos,
prefix: '',
propertyPath
}
}
function extractPropertyPath(textBeforeCursor) {
const normalized = textBeforeCursor.replace(/\s+$/, '')
if (!normalized.endsWith('.') && !normalized.endsWith('?.')) {
return null
}
const markerLength = normalized.endsWith('?.') ? 2 : 1
const expression = normalized.slice(0, -markerLength)
return parseResolvablePropertyExpression(expression)
}
function parseResolvablePropertyExpression(expression) {
let pos = 0
const parts = []
const skipSpaces = () => {
while (pos < expression.length && /\s/.test(expression[pos])) {
pos++
}
}
const parseIdentifierAt = () => {
const remaining = expression.slice(pos)
const match = remaining.match(/^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*/)
if (!match) {
return null
}
pos += match[0].length
return match[0]
}
const parseQuotedString = (quote) => {
let value = ''
pos++
while (pos < expression.length) {
const char = expression[pos]
if (char === '\\') {
if (pos + 1 >= expression.length) {
return null
}
value += expression[pos + 1]
pos += 2
continue
}
if (char === quote) {
pos++
return value
}
value += char
pos++
}
return null
}
skipSpaces()
const first = parseIdentifierAt()
if (!first) {
return null
}
parts.push(first)
while (pos < expression.length) {
skipSpaces()
if (pos >= expression.length) {
break
}
if (expression.startsWith('?.', pos)) {
pos += 2
skipSpaces()
const id = parseIdentifierAt()
if (!id) {
return null
}
parts.push(id)
continue
}
if (expression[pos] === '.') {
pos++
skipSpaces()
const id = parseIdentifierAt()
if (!id) {
return null
}
parts.push(id)
continue
}
if (expression[pos] === '[') {
pos++
skipSpaces()
const quote = expression[pos]
if (quote !== '"' && quote !== "'") {
return null
}
const key = parseQuotedString(quote)
if (key === null) {
return null
}
skipSpaces()
if (expression[pos] !== ']') {
return null
}
pos++
if (!IDENTIFIER_BODY.test(key)) {
return null
}
parts.push(key)
continue
}
return null
}
return parts
}
function resolvePropertyTarget(scope, path) {
let target = scope
for (const segment of path) {
if (!isObjectLike(target) || !hasOwnPropertySafe(target, segment)) {
return null
}
target = target[segment]
}
return target
}
function getObjectCompletionKeys(value) {
if (!isObjectLike(value)) {
return []
}
return Object.keys(value).filter((key) => IDENTIFIER_BODY.test(key))
}
function isObjectLike(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function')
}
function getWorkerData() {
const workerState = getWorkerState()
if (workerState === cachedWorkerState && cachedWorkerData !== null) {
return cachedWorkerData
}
const mathFunctions = workerState.functions || []
const mathPhysicalConstants = workerState.physicalConstants || []
const numberLiterals = workerState.numberLiterals || []
const listOfUnits = new Set()
const prefixes = workerState.prefixes || []
const units = workerState.units || {}
for (const unitName in units) {
if (!hasOwnPropertySafe(units, unitName)) {
continue
}
const unitPrefixes = units[unitName] || []
unitPrefixes.forEach((prefixIndex) => {
const prefix = prefixes[prefixIndex]
if (typeof prefix === 'string') {
listOfUnits.add(prefix + unitName)
}
})
}
cachedWorkerState = workerState
cachedWorkerData = {
mathFunctions,
mathPhysicalConstants,
numberLiterals,
listOfUnits: Array.from(listOfUnits)
}
return cachedWorkerData
}
}
// helper function to safely check whether an object has a property
// copy from the function in object.js which is ES6
function hasOwnPropertySafe(object, property) {
return object && Object.hasOwnProperty.call(object, property)
}