Skip to content

Commit

Permalink
typing nonsense
Browse files Browse the repository at this point in the history
  • Loading branch information
dhowe committed Dec 13, 2023
1 parent 67882f1 commit d3b4086
Show file tree
Hide file tree
Showing 10 changed files with 145 additions and 208 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
"build": "rm -rf ./dist/ && npx tsup && npm run types",
"pub": "./npnb/source/cli.js --no-release-draft --test-script test:dist patch",
"prepub": "npm version patch && npm run build",
"types": "npx tsc",
"posttypes": "cp types/riscript.d.ts types/rigrammar.d.ts dist/"
"types": "rm -rf ./types/ && npx tsc",
"Xposttypes": "cp types/riscript.d.ts types/rigrammar.d.ts dist/"
},
"main": "./dist/riscript.js",
"browser": "./dist/riscript.min.js",
Expand Down
1 change: 1 addition & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/** @module riscript */

// @ts-nocheck
import { CstParser } from "chevrotain"
Expand Down
2 changes: 2 additions & 0 deletions src/rigrammar.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/** @module riscript */

import { RiScript } from './riscript.js'

/**
Expand Down
81 changes: 53 additions & 28 deletions src/riscript.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/** @module riscript */

import he from 'he';
import { Query } from 'mingo';
import { Lexer } from 'chevrotain';
Expand All @@ -13,13 +15,12 @@ const Vowels = /[aeiou]/;
const HtmlEntities = /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi;
const { escapeText, charCount, slashEscapesToEntities, escapeMarkdownLink, escapeJSONRegex } = Util;

/**@ignore */
/** @private */
class RiQuery extends Query {

constructor(scripting, condition, options) {
if (typeof condition === 'string') {
let raw = condition; // eslint-disable-line
condition = scripting.parseJSOL(condition);
// console.log('RAW: ', raw, 'parsed', condition);
}
super(condition, options);
}
Expand All @@ -41,7 +42,6 @@ class RiQuery extends Query {
const currentObj = stack.pop();
Object.keys(currentObj).forEach((key) => {
const value = currentObj[key];
// console.log(`key: ${ key }, value: ${ value } `);
if (!key.startsWith('$')) keys.add(key);
if (typeof value === 'object' && value !== null) {
const eles = Array.isArray(value) ? value : [value];
Expand All @@ -54,8 +54,8 @@ class RiQuery extends Query {
}

/**
* The RiScript interpreter, responsible for lexing, parsing and evaluating
* RiScript and RiGrammar expressions
* The RiScript interpreter, responsible for lexing, parsing and evaluating
* RiScript and RiGrammar expressions
* @class
*/
class RiScript {
Expand Down Expand Up @@ -86,10 +86,10 @@ class RiScript {
/** @type {Object.<string, any>} */ this.Escaped = undefined
/** @type {Object.<string, string>} */ this.Symbols = undefined;

/** @type {RiScriptVisitor} */
this.visitor = undefined; // created in evaluate() or passed in here
// created in evaluate() or passed as arg here
/** @type {RiScriptVisitor} */this.visitor = undefined;

this.v2Compatible = opts.compatibility === 2;
/** @type {boolean} */ this.v2Compatible = (opts.compatibility === 2);

const { Constants, tokens } = getTokens(this.v2Compatible);
({ Escaped: this.Escaped, Symbols: this.Symbols } = Constants);
Expand All @@ -114,6 +114,7 @@ class RiScript {
this.parser = new RiScriptParser(tokens, TextTypes);
}

/** @private */
lex(opts) {
if (!opts.input) throw Error('no input');
const lexResult = this.lexer.tokenize(opts.input);
Expand All @@ -126,10 +127,12 @@ class RiScript {
// return lexResult;
}

/** @private */
parse(opts) {
opts.cst = this.parser.parse(opts);
}

/** @private */
visit(opts) {
// @ts-ignore
return this.visitor.start(opts);
Expand All @@ -151,7 +154,7 @@ class RiScript {
return this._evaluate(opts);
}


/** @private */
lexParseVisit(opts = {}) {
this.lex(opts);
this.parse(opts);
Expand Down Expand Up @@ -190,15 +193,16 @@ class RiScript {
///////////////////////////////////// End API //////////////////////////////////////

/**
* Private version of evaluate taking all arguments in an options object
* @param {object} [options] - options for the evaluation
* @param {string} [options.input] - the script to evaluate
* @param {object} [options.visitor] - the visitor to use for the evaluation
* @param {boolean} [options.trace] - whether to trace the evaluation
* @param {boolean} [options.onepass] - whether to only do one pass
* @param {boolean} [options.silent] - whether to suppress warnings
* @returns {string} - the evaluated script's output text
*/
* Private version of evaluate taking all arguments in the options object
* @param {object} options - options for the evaluation
* @param {string} options.input - the script to evaluate
* @param {object} options.visitor - the visitor to use for the evaluation
* @param {boolean} [options.trace] - whether to trace the evaluation
* @param {boolean} [options.onepass] - whether to only do one pass
* @param {boolean} [options.silent] - whether to suppress warnings
* @returns {string} - the evaluated script's output text
* @package
*/
_evaluate(options) {

const { input, visitor, trace, onepass, silent } = options;
Expand Down Expand Up @@ -251,10 +255,6 @@ class RiScript {
return this._postParse(expr, options) + (endingBreak ? '\n' : '');
}

/** @private */
_query(rawQuery, opts) {
return new RiQuery(this, rawQuery, opts);
}
/** @private */
_printTokens(tokens) {
let s = tokens.reduce((str, t) => {
Expand All @@ -269,6 +269,7 @@ class RiScript {
console.log('\nTokens: [ ' + s + ' ] Context:',
this.visitor.lookupsToString());
}

/** @private */
_preParse(script, opts) {
if (typeof script !== 'string') return '';
Expand Down Expand Up @@ -320,6 +321,15 @@ class RiScript {

return result;
}

/**
* Creates a new RiQuery object from the raw query string
* @package
*/
createQuery(rawQuery, opts) {
return new RiQuery(this, rawQuery, opts);
}

/** @private */
_postParse(input, opts) {
if (typeof input !== 'string') return '';
Expand Down Expand Up @@ -456,7 +466,10 @@ class RiScript {

// ========================= statics ===============================

// Default transform that adds an article
/**
* Default transform that adds an article
* @private
*/
static articlize(s, RiTa) {
if (!s || !s.length) return '';

Expand All @@ -479,22 +492,34 @@ class RiScript {
);
}

// Default transform that capitalizes the first character
/**
* Default transform that uppercases the first character of the string
* @private
*/
static capitalize(s) {
return s ? s[0].toUpperCase() + s.substring(1) : '';
}

// Default transform that capitalizes the string
/**
* Default transform that capitalizes the string
* @private
*/
static uppercase(s) {
return s ? s.toUpperCase() : '';
}

// Default transform that wraps the string in (smart) quotes.
/**
* Default transform that wraps the string in (smart) quotes.
* @private
*/
static quotify(s) {
return '&#8220;' + (s || '') + '&#8221;';
}

// Default transform that pluralizes a string (requires RiTa)
/**
* Default transform that pluralizes a string (requires RiTa)
* @private
*/
static pluralize(s, RiTa) {
if (!RiTa?.pluralize) {
if (!RiScript.RiTaWarnings.plurals && !RiScript.RiTaWarnings.silent) {
Expand Down
2 changes: 2 additions & 0 deletions src/tokens.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/** @module riscript */

import { createToken } from "chevrotain"

function getTokens(v2Compatible) {
Expand Down
2 changes: 2 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/** @module riscript */

class Util {

///////////////////////// CONSTANTS /////////////////////////
Expand Down
38 changes: 21 additions & 17 deletions src/visitor.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/** @module riscript */

import { Util } from './util.js';

const { escapeText, stringHash } = Util;
Expand Down Expand Up @@ -44,7 +46,7 @@ class BaseVisitor {
this.path += name + '.';
}

//if (this.trace) console.log('CALLING: ' + name + '()');
//if (this.trace) console.log('CALL: ' + name + '()');

return this[name](cstNode.children, param);
}
Expand All @@ -57,11 +59,13 @@ class RiScriptVisitor extends BaseVisitor {
super(riScript);
this.context = context;

this.order = 0;
this.trace = 0;
this.choices = {};
this.isNoRepeat = false;
this.symbols = this.scripting.Symbols;
this.escaped = this.scripting.Escaped;

this.Symbols = this.scripting.Symbols;
this.Escaped = this.scripting.Escaped;

// lookups
this.statics = {};
Expand Down Expand Up @@ -137,16 +141,16 @@ class RiScriptVisitor extends BaseVisitor {
}

gate(ctx) {
// returns { decision: [accept | reject] } or { decision: 'defer', operands: [] }
// returns { decision: [accept|reject] } or { decision: 'defer', operands: [] }

if (ctx.Gate.length !== 1) throw Error('Invalid gate: ' + ctx.Gate);

let raw = ctx.Gate[0].image, mingoQuery;
if (raw.startsWith('@')) {//this.Symbols.OPEN_GATE)) {
if (raw.startsWith(this.Symbols.OPEN_GATE)) {
raw = raw.substring(1);
}
try {
mingoQuery = this.scripting._query(raw);
mingoQuery = this.scripting.createQuery(raw);
} catch (e) {
if (!this.warnOnInvalidGates) {
throw Error(`Invalid gate[2]: "@${raw}@"\n\nRootCause -> ${e}`);
Expand Down Expand Up @@ -204,7 +208,7 @@ class RiScriptVisitor extends BaseVisitor {

const sym = ctx.Symbol[0].image;
const ident = sym.replace(this.scripting.regex.AnySymbol, '');
const isStatic = sym.startsWith(this.symbols.STATIC);
const isStatic = sym.startsWith(this.Symbols.STATIC);

let value, info;
if (isStatic) {
Expand Down Expand Up @@ -283,7 +287,7 @@ class RiScriptVisitor extends BaseVisitor {
if (!isStatic && this.scripting.regex.StaticSymbol.test(symbol)) {
if (!this.scripting.regex.Entity.test(symbol)) {
throw Error(`Attempt to refer to dynamic symbol '${ident}' as` +
` ${this.symbols.STATIC}${ident}, did you mean $${ident}?`);
` ${this.Symbols.STATIC}${ident}, did you mean $${ident}?`);
}
}

Expand All @@ -297,9 +301,9 @@ class RiScriptVisitor extends BaseVisitor {
this.isNoRepeat = false;
const msg = 'Attempt to call norepeat() on ' + (isStatic
? "static symbol '" + symbol + "'. Did you mean to use '" +
this.symbols.DYNAMIC + ident + "' ?"
this.Symbols.DYNAMIC + ident + "' ?"
: "non-dynamic symbol '" + ident + "'. Did you mean to define '" +
this.symbols.DYNAMIC + ident + "' in riscript?");
this.Symbols.DYNAMIC + ident + "' in riscript?");
throw Error(msg);
}

Expand Down Expand Up @@ -356,7 +360,7 @@ class RiScriptVisitor extends BaseVisitor {

// new RegExp(`^${this.symbols.PENDING_GATE}`
const original = this.nodeText;
const ident = original.replace(this.symbols.PENDING_GATE, '');
const ident = original.replace(this.Symbols.PENDING_GATE, '');
const lookup = this.pendingGates[ident];

if (!lookup) {
Expand Down Expand Up @@ -388,7 +392,7 @@ class RiScriptVisitor extends BaseVisitor {
}

choice(ctx, opts) {
const $ = this.symbols;
const $ = this.Symbols;
const original = this.nodeText;
const choiceKey = stringHash(original + ' #' + this.choiceId(ctx));

Expand Down Expand Up @@ -504,7 +508,7 @@ class RiScriptVisitor extends BaseVisitor {
isUser = true; // found user symbol
} else {
// check for user-defined dynamic? context[$var]
result = this.context[this.symbols.DYNAMIC + ident];
result = this.context[this.Symbols.DYNAMIC + ident];
if (typeof result !== 'undefined') {
// no static
// note: treat as normal dynamic, isUser = false
Expand All @@ -519,7 +523,7 @@ class RiScriptVisitor extends BaseVisitor {
}

inlineAssignment(ident, tfs, result) {
const $ = this.symbols;
const $ = this.Symbols;
const lhs = $.STATIC + ident;
const rhs = this.restoreTransforms(result, tfs);
result = $.OPEN_CHOICE + (lhs + '=' + rhs) + $.CLOSE_CHOICE;
Expand All @@ -546,7 +550,7 @@ class RiScriptVisitor extends BaseVisitor {
let mult = 1;
try {
mult = parseInt(
this.symbols.CLOSE_WEIGHT.length
this.Symbols.CLOSE_WEIGHT.length
? weight[0].image.trim().slice(1, -1)
: weight[0].image.trim().slice(1)
);
Expand Down Expand Up @@ -614,11 +618,11 @@ class RiScriptVisitor extends BaseVisitor {
restoreTransforms(value, txs) {
if (typeof value === 'string') {
const patt = new RegExp(
'^' + this.escaped.OPEN_CHOICE + '.*' + this.escaped.CLOSE_CHOICE + '$'
'^' + this.Escaped.OPEN_CHOICE + '.*' + this.Escaped.CLOSE_CHOICE + '$'
);
if (!patt.test(value)) {
// wrap in choice to preserve
value = this.symbols.OPEN_CHOICE + value + this.symbols.CLOSE_CHOICE;
value = this.Symbols.OPEN_CHOICE + value + this.Symbols.CLOSE_CHOICE;
}
if (txs) {
txs.forEach((tx) => (value += tx.image)); // append transform strings
Expand Down
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"include": ["src/*.js"],
"include": ["src/index.js"],
"compilerOptions": {
"outDir": "./types",
"allowJs": true,
"checkJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"declarationMap": false,
"outDir": "./types",
"emitDeclarationOnly": true,
"moduleResolution": "NodeNext",
"module": "NodeNext",
"target": "es6",
Expand Down
Loading

0 comments on commit d3b4086

Please sign in to comment.