# @cjting/logic-parser

> A simple library to parse logic expression to AST

Latest version **0.2.1** (published 2022-12-20) · ISC license · 0 weekly downloads

## Install

```sh
npm install @cjting/logic-parser
pnpm add @cjting/logic-parser
yarn add @cjting/logic-parser
bun add @cjting/logic-parser
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2.1 |
| Published | 2022-12-20 |
| First published | 2021-10-26 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 18.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | CJ |
| Maintainers | cjting |

## Links

- npm: https://www.npmjs.com/package/@cjting/logic-parser
- Repository: https://github.com/cj1128/logic-parser
- Homepage: https://github.com/cj1128/logic-parser#readme
- Issues: https://github.com/cj1128/logic-parser/issues
- npm.io page: https://npm.io/package/@cjting/logic-parser

## Recent versions

- 0.2.1 (latest) — 2022-12-20
- 0.2.0 — 2022-12-14
- 0.1.1 — 2021-10-26
- 0.1.0 — 2021-10-26

## README

# Logic Parser

A simple library to parse _logic expression_ to AST.

## Install && Use

The package is on NPM and in CJS format: `npm install @cjting/logic-parser`

```javascript
import LogicParser from '@cjting/logic-parser'

// @param unitRegexp: a regexp to define what unit is like
const parser = new LogicParser(/\d+/)

// return AST if input is valid, throw error otherwise
parser.parse('1 && 2 || !3')

// `left` and `right` are either object or simple strings captured by `unitRegexp`
/*
{
  type: 'or',
  left: {
    type: 'and',
    left: '1',
    right: '2',
  },
  right: {
    type: 'not',
    op: '3',
  },
}
*/
```

## Grammar

Formal definition:

```
# _ means arbitrary amount of whitespace
expr -> expr _ "||" _ term | term
term -> term _ "&&" _ not | not
not -> "!" _ not | factor
factor -> unit | "(" _ expr _ ")"
```

`unit` is user defined token, it can be anything defined by a regexp.

Based on the grammar, we can know that

- operator precedence: `!` > `&&` > `||`
- both `&&` and `||` are left associative

Examples (suppose `unit=\d+`):

- `1`
- `1 && !2`
- `1 && 2 && 3`
- `1 && 2 || 3`
- `1 && (2 || !3)`
- `!!1`
- `1 && !(2 || 3 && 4 || 5)`

## Dev

- Write grammar in `lib/logic.ne`
- `pnpm run gen` generates grammar file
- Copy `lib/logic.js` into `lib/logic.modified.js` and then modify it to support passing of unit regexp

---
_Source: https://npm.io/package/@cjting/logic-parser · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
