简体   繁体   中英

How to differentiate between operators and numbers

I'm creating a simple query language to generate signals for stockmarket events.

eg

//Get notified when the RSI(14) falls below 25
bnbCache.onCondition("rsi(14) < 25", (args) => console.log(args))

//Get notified when the SMA(7) crosses the SMA(25)
bnbCache.onCondition("last(sma(7) > sma(25)) AND (sma(7) < sma(25))", (args) => console.log(args))

//Get notified when the SMA(14) drops 2 within the last 15m candle.
bnbCache.onCondition("change(period, sma(14)) < -2", (res, interval, condition) => {
    if (interval === '15m')
        logger.warning`Condition '${condition}' matched for interval ${interval} ${res}`;
});

The (most probably well known) problem is that I need to disambiguate the number -2 from an operation 4-2 . The lexical analysis should return a token of type number in the first case, and three tokens [number, sub, number] in the latter. What's the most straightforward solution to this problem?

The most straightforward and most common solution is to have the lexer generate a sub token (though I would rename it to minus) for - either way and have the parser parse number minus number as a subtraction and minus number as a negative number.

Don't do this as part of the lexical analysis - parse - as one token and the integer as another.

The parser will the decide whether it is a unary operator (meaning negation) or a binary operator (meaning subtraction).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM