├── test ├── snapshots │ ├── base.spec.ts.snap │ └── base.spec.ts.md ├── json.spec.ts ├── rfc1738.spec.ts └── base.spec.ts ├── .gitignore ├── .travis.yml ├── tslint.json ├── ava.config.js ├── tsconfig.json ├── .eslintrc ├── README.md ├── sample ├── plain.js ├── group.js ├── calculator.js ├── json.ts └── rfc1738.ts ├── benchmark └── json.js ├── package.json ├── src └── parser.ts └── LICENSE /test/snapshots/base.spec.ts.snap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muzea/parser/HEAD/test/snapshots/base.spec.ts.snap -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .git 2 | .cache 3 | .nyc_output 4 | dist 5 | sample-dist 6 | benchmark-dist 7 | yarn.lock 8 | node_modules 9 | coverage.lcov 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: 2 | node_js 3 | node_js: 4 | - "10" 5 | install: 6 | - npm install 7 | script: 8 | - npm run lint 9 | - npm run test 10 | - npm run report-coverage 11 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint:latest", 4 | "tslint-config-prettier" 5 | ], 6 | "rules": { 7 | "ordered-imports": false, 8 | "no-console": false, 9 | "no-submodule-imports": false, 10 | "no-implicit-dependencies": false, 11 | "variable-name": false 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/json.spec.ts: -------------------------------------------------------------------------------- 1 | import { json, elementToValue } from "../sample/json"; 2 | import test from 'ava'; 3 | 4 | const data = JSON.stringify({ 5 | a: "213", 6 | b: [1, 2, 3], 7 | c: "\n777" 8 | }); 9 | 10 | test('json', t => { 11 | const obj = elementToValue(json[0](data)[0][0] as any) 12 | t.is(JSON.stringify(obj), data); 13 | }); 14 | -------------------------------------------------------------------------------- /ava.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | files: ["test/**/*.{js,ts}"], 3 | sources: ["src/*.{js,jsx}", "sample/*.{js,jsx}", "!dist/**/*"], 4 | cache: true, 5 | concurrency: 5, 6 | failFast: true, 7 | failWithoutAssertions: false, 8 | verbose: true, 9 | compileEnhancements: false, 10 | extensions: ["ts"], 11 | require: ["ts-node/register"] 12 | }; 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "strictNullChecks": false, 5 | "target": "es6", 6 | "skipLibCheck": true, 7 | "allowSyntheticDefaultImports": true, 8 | "lib": [ 9 | "es7", 10 | "esnext" 11 | ], 12 | "moduleResolution": "node" 13 | }, 14 | "include": [ 15 | "src" 16 | ], 17 | "exclude": [ 18 | "node_modules", 19 | "sample-dist", 20 | "dist" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parserOptions": { 3 | "ecmaVersion": 7, 4 | "sourceType": "module" 5 | }, 6 | "env": { 7 | "es6": true, 8 | "node": true 9 | }, 10 | "plugins": ["prettier"], 11 | "rules": { 12 | "space-before-function-paren": [0], 13 | "prettier/prettier": "error", 14 | "indent": [0], 15 | "no-shadow": 2, 16 | "no-undef": 2, 17 | "no-undefined": 2, 18 | "no-unused-vars": 2, 19 | "no-unreachable": 2, 20 | "no-mixed-spaces-and-tabs": 2 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 使用高阶函数开发语法分析器 2 | 3 | [![travis-ci](https://api.travis-ci.org/muzea/parser.svg?branch=master)](https://travis-ci.org/muzea/parser) [![codecov](https://img.shields.io/codecov/c/github/muzea/parser/master.svg)](https://codecov.io/gh/muzea/parser) 4 | 5 | 程序是[轮子哥博客](http://www.cppblog.com/vczh/archive/2008/05/21/50656.html)的js复刻版。 6 | 7 | 做了一些修改方便理解。~~其实是我看不懂轮子脚本的语法了~~ 8 | 9 | 示例代码 10 | 11 | - [普通的Token](/sample/plain.js) 12 | - [优先级信息](/sample/group.js) 13 | - [普通的计算](/sample/calculator.js) 14 | - [rfc1738 校验器](/sample/rfc1738.ts) 15 | - [json 解析器](/sample/json.ts) 16 | 17 | -------------------------------------------------------------------------------- /test/rfc1738.spec.ts: -------------------------------------------------------------------------------- 1 | import { isHttpurl } from '../sample/rfc1738'; 2 | import test from 'ava'; 3 | 4 | test('is-url', t => { 5 | const list = [ 6 | 'http://google.com', 7 | 'http://www.google.com', 8 | 'http://google.com/something', 9 | 'http://google.com/something?q=query', 10 | 'http://google.co.uk', 11 | 'http://www.google.co.uk', 12 | 'http://google.cat', 13 | 'http://0.0.0.0', 14 | 'http://localhost', 15 | 'http://localhost:4000', 16 | 'http://localhost:342/a/path', 17 | ]; 18 | for (const item of list) { 19 | t.is(isHttpurl(item), true); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /sample/plain.js: -------------------------------------------------------------------------------- 1 | import { 2 | createParser, 3 | setParser, 4 | regex, 5 | seq, 6 | rep, 7 | alt, 8 | ch, 9 | end 10 | } from "../dist/parser"; 11 | 12 | let Term = createParser(); 13 | let Factor = createParser(); 14 | let Exp = createParser(); 15 | let Parser = createParser(); 16 | 17 | setParser(Term, alt(regex("\\d+(\\.\\d+)?"), seq(ch("("), Exp, ch(")")))); 18 | 19 | setParser(Factor, seq(Term, rep(seq(alt(ch("*"), ch("/")), Term)))); 20 | 21 | setParser(Exp, seq(Factor, rep(seq(alt(ch("+"), ch("-")), Factor)))); 22 | 23 | setParser(Parser, seq(Exp, end())); 24 | 25 | for (const result of Parser[0]("123+321*(456+654)")) { 26 | console.log("RESULT :", result); 27 | } 28 | -------------------------------------------------------------------------------- /benchmark/json.js: -------------------------------------------------------------------------------- 1 | import Benchmark from "benchmark"; 2 | import { json, elementToValue } from "../sample/json"; 3 | 4 | const data = JSON.stringify({ 5 | a: "213", 6 | b: [1, 2, 3], 7 | c: "\n777" 8 | }); 9 | 10 | const rdata = `var a=${data}`; 11 | 12 | const suite = new Benchmark.Suite(); 13 | 14 | suite 15 | .add("parser#json", function() { 16 | elementToValue(json[0](data)[0][0]); 17 | }) 18 | .add("JSON#parse", function() { 19 | JSON.parse(data); 20 | }) 21 | .add("eval", function() { 22 | eval(rdata); 23 | }) 24 | .on("cycle", function(event) { 25 | console.log(String(event.target)); 26 | }) 27 | .on("complete", function() { 28 | console.log("Fastest is " + this.filter("fastest").map("name")); 29 | }) 30 | .run(); 31 | -------------------------------------------------------------------------------- /sample/group.js: -------------------------------------------------------------------------------- 1 | import { 2 | createParser, 3 | setParser, 4 | regex, 5 | seq, 6 | rep, 7 | alt, 8 | ch, 9 | end, 10 | using 11 | } from "../dist/parser"; 12 | 13 | let Term = createParser(); 14 | let Factor = createParser(); 15 | let Exp = createParser(); 16 | let Parser = createParser(); 17 | 18 | function group(result) { 19 | return result.map(resultItem => { 20 | return [resultItem.slice(0, -1)].concat(resultItem.slice(-1)); 21 | }); 22 | } 23 | 24 | setParser(Term, alt(regex("\\d+(\\.\\d+)?"), seq(ch("("), Exp, ch(")")))); 25 | 26 | setParser( 27 | Factor, 28 | using(seq(Term, rep(seq(alt(ch("*"), ch("/")), Term))), group) 29 | ); 30 | 31 | setParser( 32 | Exp, 33 | using(seq(Factor, rep(seq(alt(ch("+"), ch("-")), Factor))), group) 34 | ); 35 | 36 | setParser(Parser, seq(Exp, end())); 37 | 38 | for (const result of Parser[0]("123+321*(456+654)")) { 39 | console.log("RESULT :", result); 40 | } 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "parser", 3 | "version": "0.0.0-dev", 4 | "main": "dist/parser.js", 5 | "repository": "git@github.com:muzea/parser.git", 6 | "author": "muzea ", 7 | "license": "GPL-3.0-or-later", 8 | "scripts": { 9 | "build": "parcel build src/* --target node", 10 | "build:sample": "parcel build sample/* -d sample-dist --target node", 11 | "build:debug": "parcel build src/* --target node --no-minify && parcel build sample/* -d sample-dist --target node --no-minify && parcel build benchmark/* -d benchmark-dist --target node --no-minify", 12 | "test": "nyc ava --color", 13 | "lint": "yarn tslint -p . && yarn eslint sample/*.js && yarn tslint sample/*.ts", 14 | "benchmark": "node ./benchmark-dist/json.js", 15 | "benchmark:build": "parcel build benchmark/* -d benchmark-dist --target node", 16 | "report-coverage": "nyc ava --color && nyc report --reporter=text-lcov > coverage.lcov && codecov" 17 | }, 18 | "nyc": { 19 | "include": [ 20 | "src/parser.ts" 21 | ], 22 | "extension": [ 23 | ".ts" 24 | ], 25 | "cache": true 26 | }, 27 | "devDependencies": { 28 | "ava": "1.2", 29 | "benchmark": "^2.1.4", 30 | "codecov": "^3.2.0", 31 | "eslint": "^5.9.0", 32 | "eslint-plugin-prettier": "^3.0.0", 33 | "microtime": "^2.1.8", 34 | "nyc": "^13.2.0", 35 | "parcel-bundler": "^1.10.3", 36 | "prettier": "^1.15.2", 37 | "ts-node": "^7.0.1", 38 | "tslint": "^5.11.0", 39 | "tslint-config-prettier": "^1.16.0", 40 | "typescript": "2.9" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /sample/calculator.js: -------------------------------------------------------------------------------- 1 | import { 2 | createParser, 3 | setParser, 4 | regex, 5 | seq, 6 | rep, 7 | alt, 8 | ch, 9 | end, 10 | using 11 | } from "../dist/parser"; 12 | 13 | let Term = createParser(); 14 | let Factor = createParser(); 15 | let Exp = createParser(); 16 | let Parser = createParser(); 17 | 18 | function passBracket(result) { 19 | return result.map(resultItem => { 20 | const [, exp, , ...rest] = resultItem; 21 | return [exp].concat(rest); 22 | }); 23 | } 24 | 25 | const calculatorMap = { 26 | "+": function(left, right) { 27 | return parseInt(left) + parseInt(right); 28 | }, 29 | "-": function(left, right) { 30 | return parseInt(left) - parseInt(right); 31 | }, 32 | "*": function(left, right) { 33 | return parseInt(left) * parseInt(right); 34 | }, 35 | "/": function(left, right) { 36 | return parseInt(left) / parseInt(right); 37 | } 38 | }; 39 | 40 | let calculator = result => { 41 | return result.map(resultItem => { 42 | if (resultItem.length < 3) { 43 | return resultItem; 44 | } 45 | const [left, operator, right, ...rest] = resultItem; 46 | return [`${calculatorMap[operator](left, right)}`].concat(rest); 47 | }); 48 | }; 49 | 50 | setParser( 51 | Term, 52 | alt(regex("\\d+(\\.\\d+)?"), using(seq(ch("("), Exp, ch(")")), passBracket)) 53 | ); 54 | 55 | setParser( 56 | Factor, 57 | using(seq(Term, rep(seq(alt(ch("*"), ch("/")), Term))), calculator) 58 | ); 59 | 60 | setParser( 61 | Exp, 62 | using(seq(Factor, rep(seq(alt(ch("+"), ch("-")), Factor))), calculator) 63 | ); 64 | 65 | setParser(Parser, seq(Exp, end())); 66 | 67 | for (const result of Parser[0]("123+321*(456+654)")) { 68 | console.log("RESULT :", result); 69 | } 70 | -------------------------------------------------------------------------------- /test/base.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | last, 3 | fail, 4 | ch, 5 | end, 6 | regex, 7 | seq, 8 | alt, 9 | any, 10 | opt, 11 | rep, 12 | using, 13 | } from '../src/parser'; 14 | import test from 'ava'; 15 | 16 | const testStr = '23333'; 17 | 18 | test('last', t => { 19 | t.snapshot(last(['2', '3', '3', '3'])); 20 | }); 21 | 22 | test('fail', t => { 23 | t.snapshot(fail[0](testStr)); 24 | }); 25 | 26 | test('ch', t => { 27 | const emptyParser = ch(''); 28 | const charParser = ch('2'); 29 | t.snapshot(emptyParser[0](testStr)); 30 | t.snapshot(charParser[0](testStr)); 31 | }); 32 | 33 | test('end', t => { 34 | const emptyParser = end(); 35 | t.snapshot(emptyParser[0](testStr)); 36 | t.snapshot(emptyParser[0]('')); 37 | }); 38 | 39 | test('regex', t => { 40 | const shouldMatchParser = regex('2'); 41 | const shouldNotMatchParser = regex('3'); 42 | t.snapshot(shouldMatchParser[0](testStr)); 43 | t.snapshot(shouldNotMatchParser[0](testStr)); 44 | }); 45 | 46 | test('seq', t => { 47 | const match2Parser = ch('2'); 48 | const match3Parser = ch('3'); 49 | const shouldMatchParser = seq(match2Parser, match3Parser); 50 | const shouldNotMatchParser = seq(match2Parser, match2Parser); 51 | t.snapshot(shouldMatchParser[0](testStr)); 52 | t.snapshot(shouldNotMatchParser[0](testStr)); 53 | }); 54 | 55 | test('alt', t => { 56 | const match1Parser = ch('1'); 57 | const match2Parser = ch('2'); 58 | const match3Parser = ch('3'); 59 | const shouldMatchParser = alt(match1Parser, match2Parser, match3Parser); 60 | const shouldNotMatchParser = alt(match1Parser, match3Parser); 61 | t.snapshot(shouldMatchParser[0](testStr)); 62 | t.snapshot(shouldNotMatchParser[0](testStr)); 63 | }); 64 | 65 | test('any', t => { 66 | const match2Parser = ch('2'); 67 | const match3Parser = ch('3'); 68 | const matchOnceParser = any(match2Parser, 3); 69 | const matchTwiceParser = seq(match2Parser, any(match3Parser, 2)); 70 | const matchMaxParser = seq(match2Parser, any(match3Parser, 4)); 71 | t.snapshot(matchOnceParser[0](testStr)); 72 | t.snapshot(matchTwiceParser[0](testStr)); 73 | t.snapshot(matchMaxParser[0](testStr)); 74 | }); 75 | 76 | test('opt', t => { 77 | const match2Parser = ch('2'); 78 | const match3Parser = ch('3'); 79 | const shouldMatchParser = opt(match2Parser); 80 | const shouldNotMatchParser = opt(match3Parser); 81 | t.snapshot(shouldMatchParser[0](testStr)); 82 | t.snapshot(shouldNotMatchParser[0](testStr)); 83 | }); 84 | 85 | test('rep', t => { 86 | const match2Parser = ch('2'); 87 | const match3Parser = ch('3'); 88 | const matchOnceParser = rep(match2Parser); 89 | const matchMaxParser = seq(match2Parser, rep(match3Parser)); 90 | const shouldNotMatchParser = rep(match3Parser); 91 | t.snapshot(matchOnceParser[0](testStr)); 92 | t.snapshot(matchMaxParser[0](testStr)); 93 | t.snapshot(shouldNotMatchParser[0](testStr)); 94 | }); 95 | 96 | test('using', t => { 97 | let usingFunc = (result) => { 98 | return result; 99 | }; 100 | const match2Parser = using(ch('2'), usingFunc); 101 | t.snapshot(match2Parser[0](testStr)); 102 | }); 103 | 104 | 105 | -------------------------------------------------------------------------------- /test/snapshots/base.spec.ts.md: -------------------------------------------------------------------------------- 1 | # Snapshot report for `test/base.spec.ts` 2 | 3 | The actual snapshot is saved in `base.spec.ts.snap`. 4 | 5 | Generated by [AVA](https://ava.li). 6 | 7 | ## alt 8 | 9 | > Snapshot 1 10 | 11 | [ 12 | [ 13 | '2', 14 | '3333', 15 | ], 16 | ] 17 | 18 | > Snapshot 2 19 | 20 | [] 21 | 22 | ## any 23 | 24 | > Snapshot 1 25 | 26 | [ 27 | [ 28 | '23333', 29 | ], 30 | [ 31 | '2', 32 | '3333', 33 | ], 34 | ] 35 | 36 | > Snapshot 2 37 | 38 | [ 39 | [ 40 | '2', 41 | '3333', 42 | ], 43 | [ 44 | '2', 45 | '3', 46 | '333', 47 | ], 48 | [ 49 | '2', 50 | '3', 51 | '3', 52 | '33', 53 | ], 54 | ] 55 | 56 | > Snapshot 3 57 | 58 | [ 59 | [ 60 | '2', 61 | '3333', 62 | ], 63 | [ 64 | '2', 65 | '3', 66 | '333', 67 | ], 68 | [ 69 | '2', 70 | '3', 71 | '3', 72 | '33', 73 | ], 74 | [ 75 | '2', 76 | '3', 77 | '3', 78 | '3', 79 | '3', 80 | ], 81 | [ 82 | '2', 83 | '3', 84 | '3', 85 | '3', 86 | '3', 87 | '', 88 | ], 89 | ] 90 | 91 | ## ch 92 | 93 | > Snapshot 1 94 | 95 | [ 96 | [ 97 | '', 98 | '23333', 99 | ], 100 | ] 101 | 102 | > Snapshot 2 103 | 104 | [ 105 | [ 106 | '2', 107 | '3333', 108 | ], 109 | ] 110 | 111 | ## end 112 | 113 | > Snapshot 1 114 | 115 | [] 116 | 117 | > Snapshot 2 118 | 119 | [ 120 | [ 121 | '', 122 | ], 123 | ] 124 | 125 | ## fail 126 | 127 | > Snapshot 1 128 | 129 | [] 130 | 131 | ## last 132 | 133 | > Snapshot 1 134 | 135 | '3' 136 | 137 | ## opt 138 | 139 | > Snapshot 1 140 | 141 | [ 142 | [ 143 | '23333', 144 | ], 145 | [ 146 | '2', 147 | '3333', 148 | ], 149 | ] 150 | 151 | > Snapshot 2 152 | 153 | [ 154 | [ 155 | '23333', 156 | ], 157 | ] 158 | 159 | ## regex 160 | 161 | > Snapshot 1 162 | 163 | [ 164 | [ 165 | '2', 166 | '3333', 167 | ], 168 | ] 169 | 170 | > Snapshot 2 171 | 172 | [] 173 | 174 | ## rep 175 | 176 | > Snapshot 1 177 | 178 | [ 179 | [ 180 | '23333', 181 | ], 182 | [ 183 | '2', 184 | '3333', 185 | ], 186 | ] 187 | 188 | > Snapshot 2 189 | 190 | [ 191 | [ 192 | '2', 193 | '3333', 194 | ], 195 | [ 196 | '2', 197 | '3', 198 | '333', 199 | ], 200 | [ 201 | '2', 202 | '3', 203 | '3', 204 | '33', 205 | ], 206 | [ 207 | '2', 208 | '3', 209 | '3', 210 | '3', 211 | '3', 212 | ], 213 | [ 214 | '2', 215 | '3', 216 | '3', 217 | '3', 218 | '3', 219 | '', 220 | ], 221 | ] 222 | 223 | > Snapshot 3 224 | 225 | [ 226 | [ 227 | '23333', 228 | ], 229 | ] 230 | 231 | ## seq 232 | 233 | > Snapshot 1 234 | 235 | [ 236 | [ 237 | '2', 238 | '3', 239 | '333', 240 | ], 241 | ] 242 | 243 | > Snapshot 2 244 | 245 | [] 246 | 247 | ## using 248 | 249 | > Snapshot 1 250 | 251 | [ 252 | [ 253 | '2', 254 | '3333', 255 | ], 256 | ] 257 | -------------------------------------------------------------------------------- /src/parser.ts: -------------------------------------------------------------------------------- 1 | type IResult = string[][]; 2 | type IParserFunc = (input?: string) => IResult; 3 | type IHParserFunc = [IParserFunc] 4 | 5 | type ILast = (array: string[]) => string 6 | 7 | const last: ILast = arr => arr[arr.length - 1]; 8 | 9 | type IFail = [IParserFunc] 10 | const fail: IFail = [() => []]; 11 | 12 | // const isDebug = false 13 | 14 | type ICh = (expected: string) => [IParserFunc] 15 | 16 | const ch: ICh = c => [ 17 | input => { 18 | // if (isDebug) { 19 | // console.log('ch') 20 | // console.log('expected ', c) 21 | // console.log('input', input) 22 | // } 23 | if (c === '') { 24 | return [['', input]] 25 | } 26 | if (input && input.length >= c.length) { 27 | if (input.substr(0, c.length) === c) { 28 | return [[c, input.substr(c.length)]]; 29 | } 30 | } 31 | return fail[0](); 32 | } 33 | ]; 34 | 35 | type IEnd = () => [IParserFunc] 36 | 37 | const end: IEnd = () => [ 38 | input => { 39 | if (input === "") { 40 | return [[input]]; 41 | } 42 | return fail[0](); 43 | } 44 | ]; 45 | 46 | type IRegex = (expectedRegExp: string) => [IParserFunc] 47 | 48 | const regex: IRegex = expectedRegExp => { 49 | const expression = new RegExp(expectedRegExp, "u"); 50 | return [ 51 | input => { 52 | // if (isDebug) { 53 | // console.log('regex') 54 | // console.log('expected ', expectedRegExp) 55 | // console.log('input', input) 56 | // } 57 | const match = expression.exec(input); 58 | if (match && match.index === 0) { 59 | return [[match[0], input.substr(match[0].length)]]; 60 | } 61 | return fail[0](); 62 | } 63 | ]; 64 | }; 65 | 66 | const mergeResult = (result: IResult, resultItem: string[], parseResult: IResult) => { 67 | const cacheResultItem = resultItem.slice(0, -1); 68 | if (parseResult.length) { 69 | for (const parseResultItem of parseResult) { 70 | if (parseResultItem.length) { 71 | result.push(cacheResultItem.concat(parseResultItem)); 72 | } 73 | } 74 | } 75 | }; 76 | 77 | type ISeq = (...expectedSequenceList: IHParserFunc[]) => [IParserFunc] 78 | 79 | const seq: ISeq = (...parserList) => [ 80 | input => { 81 | // if (isDebug) { 82 | // console.log('seq') 83 | // console.log('input', input) 84 | // } 85 | let result = [[input]]; 86 | for (const parser of parserList) { 87 | const nextResult = []; 88 | for (const resultItem of result) { 89 | const parseResult = parser[0](last(resultItem)); 90 | mergeResult(nextResult, resultItem, parseResult); 91 | } 92 | result = nextResult; 93 | } 94 | return result; 95 | } 96 | ]; 97 | 98 | type IAlt = (...expectedBranchList: IHParserFunc[]) => [IParserFunc] 99 | 100 | const alt: IAlt = (...parserList) => [ 101 | input => { 102 | // if (isDebug) { 103 | // console.log('alt') 104 | // console.log('input', input) 105 | // } 106 | const result = []; 107 | for (const parser of parserList) { 108 | const parseResult = parser[0](input); 109 | if (parseResult.length) { 110 | for (const parseResultItem of parseResult) { 111 | if (parseResultItem.length) { 112 | result.push(parseResultItem); 113 | } 114 | } 115 | } 116 | } 117 | return result; 118 | } 119 | ]; 120 | 121 | type IAny = (expected: IHParserFunc, maxRepeatTimes: number) => [IParserFunc] 122 | 123 | const any: IAny = (parser, max) => [ 124 | input => { 125 | // if (isDebug) { 126 | // console.log('any') 127 | // console.log('input', input) 128 | // } 129 | let result = [[input]]; 130 | let current = 0; 131 | let prevResult = [[input]]; 132 | do { 133 | if (current === max) { 134 | break; 135 | } 136 | 137 | const nextPrevResult = []; 138 | for (const prevResultItem of prevResult) { 139 | const parseResult = parser[0](last(prevResultItem)); 140 | mergeResult(nextPrevResult, prevResultItem, parseResult); 141 | } 142 | prevResult = nextPrevResult; 143 | result = result.concat(prevResult); 144 | current = current + 1; 145 | } while (prevResult.length); 146 | return result; 147 | } 148 | ]; 149 | 150 | type IOptOrRep = (expected: IHParserFunc) => [IParserFunc] 151 | const opt: IOptOrRep = parser => any(parser, 1); 152 | const rep: IOptOrRep = parser => any(parser, 998); 153 | 154 | 155 | type IUsing = (parser: IHParserFunc, handler: (result: IResult) => IResult) => [IParserFunc] 156 | 157 | const using: IUsing = (parser, handler) => [input => handler(parser[0](input))]; 158 | 159 | const createParser = () => ([] as any as [IParserFunc]); 160 | const setParser = (object: [IParserFunc], parser: [IParserFunc]) => { 161 | object[0] = parser[0]; 162 | }; 163 | 164 | export { 165 | last, 166 | fail, 167 | ch, 168 | end, 169 | regex, 170 | seq, 171 | alt, 172 | any, 173 | opt, 174 | rep, 175 | using, 176 | createParser, 177 | setParser 178 | }; 179 | -------------------------------------------------------------------------------- /sample/json.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createParser, 3 | setParser, 4 | ch, 5 | regex, 6 | seq, 7 | alt, 8 | end, 9 | using 10 | } from '../src/parser' 11 | 12 | 13 | const json = createParser(); 14 | const element = createParser(); 15 | const value = createParser(); 16 | const object = createParser(); 17 | const members = createParser(); 18 | const member = createParser(); 19 | const array = createParser(); 20 | const elements = createParser(); 21 | const string = createParser(); 22 | const characters = createParser(); 23 | const character = createParser(); 24 | const escape = createParser(); 25 | const hex = createParser(); 26 | const number = createParser(); 27 | const int = createParser(); 28 | const digits = createParser(); 29 | const digit = createParser(); 30 | const onenine = createParser(); 31 | const frac = createParser(); 32 | const exp = createParser(); 33 | const sign = createParser(); 34 | const ws = createParser(); 35 | 36 | function group(type) { 37 | return (result) => { 38 | return result.map(resultItem => { 39 | return [{ 40 | type, 41 | value: resultItem.slice(0, -1) 42 | }].concat(resultItem.slice(-1)); 43 | }); 44 | } 45 | } 46 | 47 | 48 | setParser( 49 | value, 50 | using( 51 | alt( 52 | object, 53 | array, 54 | string, 55 | number, 56 | ch("true"), 57 | ch("false"), 58 | ch("null") 59 | ), 60 | group('value') 61 | ) 62 | ) 63 | 64 | setParser( 65 | object, 66 | using( 67 | alt( 68 | seq( 69 | ch("{"), 70 | ws, 71 | ch("}") 72 | ), 73 | seq( 74 | ch("{"), 75 | members, 76 | ch("}") 77 | ) 78 | ), 79 | group('object') 80 | ) 81 | ) 82 | 83 | setParser( 84 | members, 85 | using( 86 | alt( 87 | member, 88 | seq( 89 | member, 90 | ch(","), 91 | members 92 | ) 93 | ), 94 | group('members') 95 | ) 96 | ) 97 | 98 | setParser( 99 | member, 100 | using( 101 | seq( 102 | ws, 103 | string, 104 | ws, 105 | ch(":"), 106 | element 107 | ), 108 | group('member') 109 | ) 110 | ) 111 | 112 | setParser( 113 | array, 114 | using( 115 | alt( 116 | seq( 117 | ch("["), 118 | ws, 119 | ch("]") 120 | ), 121 | seq( 122 | ch("["), 123 | elements, 124 | ch("]") 125 | ) 126 | ), 127 | group('array') 128 | ) 129 | ) 130 | 131 | setParser( 132 | elements, 133 | using( 134 | alt( 135 | element, 136 | seq( 137 | element, 138 | ch(","), 139 | elements 140 | ) 141 | ), 142 | group('elements') 143 | ) 144 | ) 145 | 146 | setParser( 147 | element, 148 | using( 149 | seq( 150 | ws, 151 | value, 152 | ws 153 | ), 154 | group('element') 155 | ) 156 | ) 157 | 158 | setParser( 159 | string, 160 | using( 161 | seq( 162 | ch('"'), 163 | characters, 164 | ch('"') 165 | ), 166 | group('string') 167 | ) 168 | ) 169 | 170 | 171 | setParser( 172 | characters, 173 | using( 174 | alt( 175 | ch(""), 176 | seq( 177 | character, 178 | characters 179 | ) 180 | ), 181 | group('characters') 182 | ) 183 | ) 184 | 185 | 186 | setParser( 187 | character, 188 | using( 189 | alt( 190 | regex("^[\\u{0020}\\u{0021}\\u{0023}-\\u{005b}\\u{005d}-\\u{10FFFF}]+"), 191 | seq( 192 | ch("\\"), 193 | escape 194 | ) 195 | ), 196 | group('character') 197 | ) 198 | ) 199 | 200 | setParser( 201 | escape, 202 | using( 203 | alt( 204 | ch('"'), 205 | ch('\\'), 206 | ch('/'), 207 | ch('b'), 208 | ch('n'), 209 | ch('r'), 210 | ch('t'), 211 | seq( 212 | ch("u"), 213 | hex, 214 | hex, 215 | hex, 216 | hex 217 | ) 218 | ), 219 | group('escape') 220 | ) 221 | ) 222 | 223 | 224 | setParser( 225 | hex, 226 | using( 227 | alt( 228 | digit, 229 | regex("[A-F]"), 230 | regex("[a-f]") 231 | ), 232 | group('hex') 233 | ) 234 | ) 235 | 236 | setParser( 237 | number, 238 | using( 239 | seq( 240 | int, 241 | frac, 242 | exp 243 | ), 244 | group('number') 245 | ) 246 | ) 247 | 248 | 249 | setParser( 250 | int, 251 | using( 252 | alt( 253 | digit, 254 | seq( 255 | onenine, 256 | digits 257 | ), 258 | seq( 259 | ch("-"), 260 | digits 261 | ), 262 | seq( 263 | ch("-"), 264 | onenine, 265 | digits 266 | ) 267 | ), 268 | group('int') 269 | ) 270 | ) 271 | 272 | 273 | setParser( 274 | digits, 275 | using( 276 | alt( 277 | digit, 278 | seq( 279 | digit, 280 | digits 281 | ) 282 | ), 283 | group('digits') 284 | ) 285 | ) 286 | 287 | 288 | setParser( 289 | digit, 290 | using( 291 | alt( 292 | ch("0"), 293 | onenine 294 | ), 295 | group('digit') 296 | ) 297 | ) 298 | 299 | setParser( 300 | onenine, 301 | using( 302 | regex("[1-9]"), 303 | group('onenine') 304 | ) 305 | ) 306 | 307 | 308 | setParser( 309 | frac, 310 | using( 311 | alt( 312 | ch(""), 313 | seq( 314 | ch("."), 315 | digits 316 | ) 317 | ), 318 | group('frac') 319 | ) 320 | ) 321 | 322 | 323 | setParser( 324 | exp, 325 | using( 326 | alt( 327 | ch(""), 328 | seq( 329 | ch("E"), 330 | sign, 331 | digits 332 | ), 333 | seq( 334 | ch("e"), 335 | sign, 336 | digits 337 | ) 338 | ), 339 | group('exp') 340 | ) 341 | ) 342 | 343 | setParser( 344 | sign, 345 | using( 346 | alt( 347 | ch(""), 348 | ch("+"), 349 | ch("-") 350 | ), 351 | group('sign') 352 | ) 353 | ) 354 | 355 | setParser( 356 | ws, 357 | using( 358 | alt( 359 | ch(""), 360 | ch("\u0009"), 361 | ch("\u000a"), 362 | ch("\u0020") 363 | ), 364 | group('ws') 365 | ) 366 | ) 367 | 368 | 369 | setParser(json, seq(element, end())) 370 | 371 | 372 | interface Item { 373 | type: string; 374 | value: Array 375 | } 376 | 377 | function pass(obj: Item, index: number): Item|string { 378 | return obj.value[index] 379 | } 380 | 381 | function objectToValue(obj: Item): object { 382 | const valueItem = pass(obj, 1) as Item 383 | if (valueItem.type === 'ws') { 384 | return {} 385 | } 386 | const ret: any = {} 387 | let membersItem = valueItem 388 | let memberItem = pass(membersItem, 0) as Item 389 | while (true) { 390 | const key = stringToValue(pass(memberItem, 1) as Item) 391 | const objValue = elementToValue(pass(memberItem, 4) as Item) 392 | ret[key] = objValue 393 | if (membersItem.value.length === 1) { 394 | break 395 | } 396 | membersItem = pass(membersItem, 2) as Item 397 | memberItem = pass(membersItem, 0) as Item 398 | } 399 | return ret 400 | } 401 | 402 | function arrayToValue(obj: Item): any[] { 403 | const valueItem = pass(obj, 1) as Item 404 | if (valueItem.type === 'ws') { 405 | return [] 406 | } 407 | const ret: any = [] 408 | let elementsItem = valueItem 409 | let elementItem = pass(elementsItem, 0) as Item 410 | while (true) { 411 | ret.push(elementToValue(elementItem)) 412 | if (elementsItem.value.length === 1) { 413 | break 414 | } 415 | elementsItem = pass(elementsItem, 2) as Item 416 | elementItem = pass(elementsItem, 0) as Item 417 | } 418 | return ret 419 | } 420 | 421 | function digitToValue(obj: Item): number { 422 | if (typeof obj.value[0] === 'string') { 423 | return parseInt(obj.value[0] as string, 10) 424 | } 425 | return parseInt((obj.value[0] as Item).value[0] as string, 10) 426 | } 427 | 428 | function digitsToValue(obj: Item): number { 429 | let digitsItem = obj 430 | let ret = 0 431 | let digitItem = pass(digitsItem, 0) as Item 432 | while (true) { 433 | ret = 10 * ret + digitToValue(digitItem) 434 | if (digitsItem.value.length === 1) { 435 | break 436 | } 437 | digitsItem = pass(digitsItem, 1) as Item 438 | digitItem = pass(digitsItem, 0) as Item 439 | } 440 | return ret 441 | } 442 | 443 | function hexToValue(obj: Item): string { 444 | if (typeof obj.value[0] === 'string') { 445 | return obj.value[0] as string 446 | } 447 | return digitToValue(obj.value[0] as Item).toString() 448 | } 449 | 450 | const codeMap = { 451 | '"': '\"', 452 | '/': '\/', 453 | '\\': '\\', 454 | 'b': '\b', 455 | 'n': '\n', 456 | 'r': '\r', 457 | 't': '\t', 458 | } 459 | 460 | function escapeToValue(obj: Item): string { 461 | if (obj.value.length === 1) { 462 | return codeMap[obj.value[0] as string] 463 | } 464 | const code = parseInt(`${hexToValue(obj.value[1] as Item)}${hexToValue(obj.value[2] as Item)}${hexToValue(obj.value[3] as Item)}${hexToValue(obj.value[4] as Item)}`, 16); 465 | return String.fromCharCode(code) 466 | } 467 | 468 | function stringToValue(obj: Item): string { 469 | let charactersItem = pass(obj, 1) as Item 470 | let ret = '' 471 | let characterItem = pass(charactersItem, 0) 472 | while (true) { 473 | if (characterItem as string === '') { 474 | break 475 | } 476 | if ((characterItem as Item).value.length === 1) { 477 | ret += (characterItem as Item).value[0] 478 | } else { 479 | ret += escapeToValue((characterItem as Item).value[1] as Item) 480 | } 481 | if (charactersItem.value.length === 1) { 482 | break 483 | } 484 | charactersItem = pass(charactersItem, 1) as Item 485 | characterItem = pass(charactersItem, 0) as Item 486 | } 487 | return ret 488 | } 489 | 490 | function intToValue(obj: Item): number { 491 | switch (obj.value.length) { 492 | case 1: return digitToValue(obj.value[0] as Item) 493 | case 2: { 494 | if (obj.value[0] === '-') { 495 | return -1 * digitsToValue(obj.value[1] as Item) 496 | } 497 | return 10 * parseInt((obj.value[0] as Item).value[0] as string, 10) + digitsToValue(obj.value[1] as Item) 498 | } 499 | case 3: return -1 * (10 * parseInt((obj.value[1] as Item).value[0] as string, 10) + digitsToValue(obj.value[2] as Item)) 500 | } 501 | } 502 | 503 | function fracToValue(obj: Item): number { 504 | if (obj.value.length === 1) { 505 | return 0 506 | } 507 | const num = digitsToValue(pass(obj, 1) as Item) 508 | return parseFloat(`0.${num}`) 509 | // :) 510 | } 511 | 512 | function expToValue(obj: Item): number { 513 | if (obj.value.length === 1) { 514 | return 0 515 | } 516 | const num = digitsToValue(pass(obj, 2) as Item) 517 | if ((obj.value[1] as Item).value[0] === '-') { 518 | return -num 519 | } 520 | return num 521 | } 522 | 523 | function numberToValue(obj: Item): number { 524 | const [intItem, fracItem, expItem] = obj.value 525 | const intValue = intToValue(intItem as Item) 526 | const fracValue = fracToValue(fracItem as Item) 527 | const expValue = expToValue(expItem as Item) 528 | return (intValue + fracValue) * Math.pow(10, expValue) 529 | } 530 | 531 | function elementToValue(obj: Item): any { 532 | const valueItem = pass(obj, 1) 533 | const rawValue = pass(valueItem as Item, 0) 534 | switch (rawValue) { 535 | case 'true': return true 536 | case 'false': return false 537 | case 'null': return null 538 | } 539 | switch ((rawValue as Item).type) { 540 | case 'object': return objectToValue(rawValue as Item) 541 | case 'array': return arrayToValue(rawValue as Item) 542 | case 'string': return stringToValue(rawValue as Item) 543 | case 'number': return numberToValue(rawValue as Item) 544 | } 545 | } 546 | 547 | export { 548 | json, 549 | elementToValue, 550 | Item 551 | } 552 | 553 | // const data = JSON.stringify({ 554 | // a: '213', 555 | // b: [1, 2, 3], 556 | // c: "\n777" 557 | // }) 558 | 559 | // for (const result of json[0](data)) { 560 | // // console.log("RESULT :", JSON.stringify(result, null, 2)); 561 | // const r = elementToValue(result[0] as any as Item) 562 | // console.log(JSON.stringify(r, null, 2)) 563 | // } 564 | -------------------------------------------------------------------------------- /sample/rfc1738.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createParser, 3 | setParser, 4 | regex, 5 | seq, 6 | rep, 7 | alt, 8 | ch, 9 | opt, 10 | end 11 | } from "../src/parser"; 12 | 13 | const genericurl = createParser(); 14 | const url = createParser(); 15 | const _scheme = createParser(); 16 | const scheme = createParser(); 17 | const schemepart = createParser(); 18 | const ipSchemepart = createParser(); 19 | const login = createParser(); 20 | const hostport = createParser(); 21 | const host = createParser(); 22 | const hostname = createParser(); 23 | const domainlabel = createParser(); 24 | const toplabel = createParser(); 25 | const alphadigit = createParser(); 26 | const hostnumber = createParser(); 27 | const port = createParser(); 28 | const otherurl = createParser(); 29 | const user = createParser(); 30 | const password = createParser(); 31 | const urlpath = createParser(); 32 | const ftpurl = createParser(); 33 | const newsurl = createParser(); 34 | const nntpurl = createParser(); 35 | const telneturl = createParser(); 36 | const gopherurl = createParser(); 37 | const waisurl = createParser(); 38 | const mailtourl = createParser(); 39 | const prosperourl = createParser(); 40 | const fpath = createParser(); 41 | const fsegment = createParser(); 42 | const ftptype = createParser(); 43 | const fileurl = createParser(); 44 | const httpurl = createParser(); 45 | const hpath = createParser(); 46 | const hsegment = createParser(); 47 | const search = createParser(); 48 | const lowalpha = createParser(); 49 | const hialpha = createParser(); 50 | const alpha = createParser(); 51 | const digit = createParser(); 52 | const safe = createParser(); 53 | const extra = createParser(); 54 | const national = createParser(); 55 | const punctuation = createParser(); 56 | const reserved = createParser(); 57 | const hex = createParser(); 58 | const escape = createParser(); 59 | const unreserved = createParser(); 60 | const uchar = createParser(); 61 | const xchar = createParser(); 62 | const digits = createParser(); 63 | const gtype = createParser(); 64 | const selector = createParser(); 65 | const gopher_string = createParser(); 66 | const encoded822addr = createParser(); 67 | const grouppart = createParser(); 68 | const group = createParser(); 69 | const _articlePart = createParser(); 70 | const article = createParser(); 71 | const waisdatabase = createParser(); 72 | const waisindex = createParser(); 73 | const waisdoc = createParser(); 74 | const database = createParser(); 75 | const wpath = createParser(); 76 | const wtype = createParser(); 77 | const ppath = createParser(); 78 | const fieldspec = createParser(); 79 | const psegment = createParser(); 80 | const fieldname = createParser(); 81 | const fieldvalue = createParser(); 82 | // const fieldspec = createParser(); 83 | 84 | // ; The generic form of a URL is: 85 | 86 | // genericurl = scheme ":" schemepart 87 | 88 | setParser(genericurl, seq(scheme, ch(":"), schemepart)); 89 | 90 | // ; Specific predefined schemes are defined here; new schemes 91 | // ; may be registered with IANA 92 | 93 | // url = httpurl | ftpurl | newsurl | 94 | // nntpurl | telneturl | gopherurl | 95 | // waisurl | mailtourl | fileurl | 96 | // prosperourl | otherurl 97 | 98 | setParser( 99 | url, 100 | alt( 101 | httpurl, 102 | ftpurl, 103 | newsurl, 104 | nntpurl, 105 | telneturl, 106 | gopherurl, 107 | waisurl, 108 | mailtourl, 109 | fileurl, 110 | prosperourl, 111 | otherurl, 112 | ) 113 | ); 114 | 115 | // ; new schemes follow the general syntax 116 | // otherurl = genericurl 117 | 118 | setParser(otherurl, genericurl); 119 | 120 | // ; the scheme is in lower case; interpreters should use case-ignore 121 | // scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] 122 | 123 | setParser(_scheme, alt(lowalpha, digit, ch("+"), ch("-"), ch("."))); 124 | 125 | setParser(scheme, seq(_scheme, rep(_scheme))); 126 | 127 | // schemepart = *xchar | ip-schemepart 128 | 129 | setParser(schemepart, alt(rep(xchar), ipSchemepart)); 130 | 131 | // ; URL schemeparts for ip based protocols: 132 | 133 | // ip-schemepart = "//" login [ "/" urlpath ] 134 | 135 | setParser(ipSchemepart, seq(ch("//"), login, opt(seq(ch("/"), urlpath)))); 136 | 137 | // login = [ user [ ":" password ] "@" ] hostport 138 | 139 | setParser( 140 | login, 141 | seq(opt(seq(user, opt(seq(ch(":"), password)), ch("@"))), hostport) 142 | ); 143 | 144 | // hostport = host [ ":" port ] 145 | 146 | setParser(hostport, seq(host, opt(seq(ch(":"), port)))); 147 | 148 | // host = hostname | hostnumber 149 | 150 | setParser(host, alt(hostname, hostnumber)); 151 | 152 | // hostname = *[ domainlabel "." ] toplabel 153 | 154 | setParser( 155 | hostname, 156 | seq( 157 | rep( 158 | seq( 159 | domainlabel, 160 | ch(".") 161 | ) 162 | ), 163 | toplabel 164 | ) 165 | ); 166 | 167 | // domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit 168 | 169 | setParser( 170 | domainlabel, 171 | alt(alphadigit, seq(alphadigit, rep(alt(alphadigit, ch("-"))), alphadigit)) 172 | ); 173 | 174 | // toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit 175 | 176 | setParser( 177 | toplabel, 178 | alt(alpha, seq(alpha, rep(alt(alphadigit, ch("-"))), alphadigit)) 179 | ); 180 | 181 | // alphadigit = alpha | digit 182 | 183 | setParser(alphadigit, alt(alpha, digit)); 184 | 185 | // hostnumber = digits "." digits "." digits "." digits 186 | 187 | setParser( 188 | hostnumber, 189 | seq(digits, ch("."), digits, ch("."), digits, ch("."), digits) 190 | ); 191 | 192 | // port = digits 193 | 194 | // If set directly, it will be [[ undefined ]] 195 | setParser(port, seq(digit, rep(digit))); 196 | 197 | // user = *[ uchar | ";" | "?" | "&" | "=" ] 198 | 199 | setParser(user, rep(alt(uchar, ch(";"), ch("?"), ch("&"), ch("=")))); 200 | 201 | // password = *[ uchar | ";" | "?" | "&" | "=" ] 202 | 203 | setParser(password, rep(alt(uchar, ch(";"), ch("?"), ch("&"), ch("=")))); 204 | 205 | // urlpath = *xchar ; depends on protocol see section 3.1 206 | 207 | setParser(urlpath, rep(xchar)); 208 | 209 | // ; The predefined schemes: 210 | 211 | // ; FTP (see also RFC959) 212 | 213 | // ftpurl = "ftp://" login [ "/" fpath [ ";type=" ftptype ]] 214 | 215 | setParser( 216 | ftpurl, 217 | seq( 218 | ch("ftp://"), 219 | login, 220 | opt( 221 | seq( 222 | ch("/"), 223 | fpath, 224 | opt( 225 | seq( 226 | ch(";type="), 227 | ftptype 228 | ) 229 | ) 230 | ) 231 | ) 232 | ) 233 | ); 234 | 235 | // fpath = fsegment *[ "/" fsegment ] 236 | 237 | setParser(fpath, seq(fsegment, rep(seq(ch("/"), fsegment)))); 238 | 239 | // fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] 240 | 241 | setParser( 242 | fsegment, 243 | rep(alt(uchar, ch("?"), ch(":"), ch("@"), ch("&"), ch("="))) 244 | ); 245 | 246 | // ftptype = "A" | "I" | "D" | "a" | "i" | "d" 247 | 248 | setParser(ftptype, alt(ch("A"), ch("I"), ch("D"), ch("a"), ch("i"), ch("d"))); 249 | 250 | // ; FILE 251 | 252 | // fileurl = "file://" [ host | "localhost" ] "/" fpath 253 | 254 | setParser( 255 | ftpurl, 256 | seq(ch("file://"), opt(alt(host, ch("localhost"))), ch("/"), fpath) 257 | ); 258 | 259 | // ; HTTP 260 | 261 | // httpurl = "http://" hostport [ "/" hpath [ "?" search ]] 262 | 263 | setParser( 264 | httpurl, 265 | seq( 266 | ch("http://"), 267 | hostport, 268 | opt(seq(ch("/"), hpath, opt(seq(ch("?"), search)))) 269 | ) 270 | ); 271 | 272 | // hpath = hsegment *[ "/" hsegment ] 273 | 274 | setParser(hpath, seq(hsegment, rep(seq(ch("/"), hsegment)))); 275 | 276 | // hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ] 277 | 278 | setParser( 279 | hsegment, 280 | rep(alt(uchar, ch(";"), ch(":"), ch("@"), ch("&"), ch("="))) 281 | ); 282 | 283 | // search = *[ uchar | ";" | ":" | "@" | "&" | "=" ] 284 | 285 | setParser(search, rep(alt(uchar, ch(";"), ch(":"), ch("@"), ch("&"), ch("=")))); 286 | 287 | // ; GOPHER (see also RFC1436) 288 | 289 | // gopherurl = "gopher://" hostport [ / [ gtype [ selector 290 | // [ "%09" search [ "%09" gopher+_string ] ] ] ] ] 291 | 292 | // "gopher://" hostport [ / [ gtype [ selector [ "%09" search [ "%09" gopher+_string ] ] ] ] ] 293 | 294 | setParser( 295 | gopherurl, 296 | seq( 297 | ch("gopher://"), 298 | hostport, 299 | opt( 300 | seq( 301 | ch("/"), 302 | opt( 303 | seq( 304 | gtype, 305 | opt( 306 | seq( 307 | selector, 308 | opt( 309 | seq( 310 | ch("%09"), 311 | search, 312 | opt( 313 | seq( 314 | ch("%09"), 315 | gopher_string 316 | ) 317 | ) 318 | ) 319 | ) 320 | ) 321 | ) 322 | ) 323 | ) 324 | ) 325 | ) 326 | ) 327 | ); 328 | 329 | // gtype = xchar 330 | 331 | setParser(gtype, alt(unreserved, reserved, escape)); 332 | 333 | // selector = *xchar 334 | 335 | setParser(selector, rep(xchar)); 336 | 337 | // gopher+_string = *xchar 338 | 339 | setParser(gopher_string, rep(xchar)); 340 | 341 | // ; MAILTO (see also RFC822) 342 | 343 | // mailtourl = "mailto:" encoded822addr 344 | 345 | setParser(mailtourl, seq(ch("mailto:"), encoded822addr)); 346 | 347 | // encoded822addr = 1*xchar ; further defined in RFC822 348 | 349 | setParser(encoded822addr, seq(xchar, rep(xchar))); 350 | 351 | // ; NEWS (see also RFC1036) 352 | 353 | // newsurl = "news:" grouppart 354 | 355 | setParser(newsurl, seq(ch("news:"), grouppart)); 356 | 357 | // grouppart = "*" | group | article 358 | 359 | setParser(grouppart, alt(ch("*"), group, article)); 360 | 361 | // group = alpha *[ alpha | digit | "-" | "." | "+" | "_" ] 362 | 363 | setParser(group, seq(alpha, rep(alt( 364 | alpha, 365 | digit, 366 | ch("-"), 367 | ch("."), 368 | ch("+"), 369 | ch("_"), 370 | )))); 371 | 372 | // article = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host 373 | 374 | setParser( 375 | _articlePart, 376 | alt( 377 | uchar, 378 | ch(";"), 379 | ch("/"), 380 | ch("?"), 381 | ch(":"), 382 | ch("&"), 383 | ch("="), 384 | ) 385 | ); 386 | 387 | setParser( 388 | article, 389 | seq( 390 | _articlePart, 391 | rep(_articlePart), 392 | ch("@"), 393 | host 394 | ) 395 | ); 396 | 397 | // ; NNTP (see also RFC977) 398 | 399 | // nntpurl = "nntp://" hostport "/" group [ "/" digits ] 400 | 401 | setParser(nntpurl, seq(ch("nntp:"), hostport, ch("/"), group, opt(seq(ch("/"), digits)))); 402 | 403 | // ; TELNET 404 | 405 | // telneturl = "telnet://" login [ "/" ] 406 | 407 | setParser(telneturl, seq(ch("telnet:"), login, opt(ch("/")))); 408 | 409 | // ; WAIS (see also RFC1625) 410 | 411 | // waisurl = waisdatabase | waisindex | waisdoc 412 | 413 | setParser( 414 | waisurl, 415 | alt( 416 | waisdatabase, 417 | waisindex, 418 | waisdoc 419 | ) 420 | ); 421 | 422 | // waisdatabase = "wais://" hostport "/" database 423 | 424 | setParser(waisdatabase, seq(ch("wais://"), hostport, ch("/"), database)); 425 | 426 | // waisindex = "wais://" hostport "/" database "?" search 427 | 428 | setParser(waisindex, seq(ch("wais://"), hostport, ch("/"), database, ch("?"), search)); 429 | 430 | // waisdoc = "wais://" hostport "/" database "/" wtype "/" wpath 431 | 432 | setParser(waisindex, seq(ch("wais://"), hostport, ch("/"), database, ch("?"), search)); 433 | 434 | // database = *uchar 435 | 436 | setParser(database, rep(uchar)); 437 | 438 | // wtype = *uchar 439 | 440 | setParser(wtype, rep(uchar)); 441 | 442 | // wpath = *uchar 443 | 444 | setParser(wpath, rep(uchar)); 445 | 446 | // ; PROSPERO 447 | 448 | // prosperourl = "prospero://" hostport "/" ppath *[ fieldspec ] 449 | 450 | setParser(prosperourl, seq(ch("prospero://"), hostport, ch("/"), ppath, rep(fieldspec))); 451 | 452 | // ppath = psegment *[ "/" psegment ] 453 | 454 | setParser(ppath, seq(psegment, rep(seq(ch("/"), psegment)))); 455 | 456 | // psegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] 457 | 458 | setParser(psegment, rep( 459 | alt( 460 | uchar, 461 | ch("?"), 462 | ch(":"), 463 | ch("@"), 464 | ch("&"), 465 | ch("="), 466 | ) 467 | )); 468 | 469 | // fieldspec = ";" fieldname "=" fieldvalue 470 | 471 | setParser(fieldspec, seq(ch(";"), fieldname, ch("="), fieldvalue)); 472 | 473 | // fieldname = *[ uchar | "?" | ":" | "@" | "&" ] 474 | 475 | setParser(fieldname, rep( 476 | alt( 477 | uchar, 478 | ch("?"), 479 | ch(":"), 480 | ch("@"), 481 | ch("&") 482 | ) 483 | )); 484 | 485 | // fieldvalue = *[ uchar | "?" | ":" | "@" | "&" ] 486 | 487 | setParser(fieldvalue, rep( 488 | alt( 489 | uchar, 490 | ch("?"), 491 | ch(":"), 492 | ch("@"), 493 | ch("&") 494 | ) 495 | )); 496 | 497 | 498 | // ; Miscellaneous definitions 499 | 500 | // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | 501 | // "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | 502 | // "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | 503 | // "y" | "z" 504 | 505 | setParser(lowalpha, regex("[a-z]")); 506 | 507 | // hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | 508 | // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | 509 | // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" 510 | 511 | setParser(hialpha, regex("[A-Z]")); 512 | 513 | // alpha = lowalpha | hialpha 514 | 515 | setParser(alpha, alt(lowalpha, hialpha)); 516 | 517 | // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | 518 | // "8" | "9" 519 | 520 | setParser(digit, regex("[0-9]")); 521 | 522 | // safe = "$" | "-" | "_" | "." | "+" 523 | 524 | setParser(safe, alt(ch("$"), ch("-"), ch("_"), ch("."), ch("+"))); 525 | 526 | // extra = "!" | "*" | "'" | "(" | ")" | "," 527 | 528 | setParser(extra, alt(ch("!"), ch("*"), ch("'"), ch("("), ch(")"), ch(","))); 529 | 530 | // national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`" 531 | 532 | setParser( 533 | national, 534 | alt( 535 | ch("{"), 536 | ch("}"), 537 | ch("|"), 538 | ch("\\"), 539 | ch("^"), 540 | ch("~"), 541 | ch("["), 542 | ch("]"), 543 | ch("`") 544 | ) 545 | ); 546 | 547 | // punctuation = "<" | ">" | "#" | "%" | <"> 548 | 549 | setParser(punctuation, alt(ch("<"), ch(">"), ch("#"), ch("%"), ch('"'))); 550 | 551 | // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" 552 | 553 | setParser( 554 | reserved, 555 | alt(ch(";"), ch("/"), ch("?"), ch(":"), ch("@"), ch("&"), ch("=")) 556 | ); 557 | 558 | // hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | 559 | // "a" | "b" | "c" | "d" | "e" | "f" 560 | 561 | setParser(hex, alt(digit, regex("[A-F]"), regex("[a-f]"))); 562 | 563 | // escape = "%" hex hex 564 | 565 | setParser(escape, seq(ch("%"), hex, hex)); 566 | 567 | // unreserved = alpha | digit | safe | extra 568 | 569 | setParser(unreserved, alt(alpha, digit, safe, extra)); 570 | 571 | // uchar = unreserved | escape 572 | 573 | setParser(uchar, alt(unreserved, escape)); 574 | 575 | // xchar = unreserved | reserved | escape 576 | 577 | setParser(xchar, alt(unreserved, reserved, escape)); 578 | 579 | // digits = 1*digit 580 | 581 | setParser(digits, seq(digit, rep(digit))); 582 | 583 | 584 | const genericurlParser = createParser(); 585 | setParser(genericurlParser, seq(genericurl, end())); 586 | 587 | function isGenericurl(input: string) { 588 | const result = genericurlParser[0](input); 589 | if (result.length) { 590 | return true; 591 | } 592 | return false; 593 | } 594 | 595 | 596 | const urlParser = createParser(); 597 | setParser(urlParser, seq(url, end())); 598 | 599 | function isUrl(input: string) { 600 | const result = urlParser[0](input); 601 | if (result.length) { 602 | return true; 603 | } 604 | return false; 605 | } 606 | 607 | 608 | const httpurlParser = createParser(); 609 | setParser(httpurlParser, seq(httpurl, end())); 610 | 611 | function isHttpurl(input: string) { 612 | const result = httpurlParser[0](input); 613 | if (result.length) { 614 | return true; 615 | } 616 | return false; 617 | } 618 | 619 | 620 | const ftpurlParser = createParser(); 621 | setParser(ftpurlParser, seq(ftpurl, end())); 622 | 623 | function isFtpurl(input: string) { 624 | const result = ftpurlParser[0](input); 625 | if (result.length) { 626 | return true; 627 | } 628 | return false; 629 | } 630 | 631 | 632 | const newsurlParser = createParser(); 633 | setParser(newsurlParser, seq(newsurl, end())); 634 | 635 | function isNewsurl(input: string) { 636 | const result = newsurlParser[0](input); 637 | if (result.length) { 638 | return true; 639 | } 640 | return false; 641 | } 642 | 643 | 644 | const nntpurlParser = createParser(); 645 | setParser(nntpurlParser, seq(nntpurl, end())); 646 | 647 | function isNntpurl(input: string) { 648 | const result = nntpurlParser[0](input); 649 | if (result.length) { 650 | return true; 651 | } 652 | return false; 653 | } 654 | 655 | 656 | const telneturlParser = createParser(); 657 | setParser(telneturlParser, seq(telneturl, end())); 658 | 659 | function isTelneturl(input: string) { 660 | const result = telneturlParser[0](input); 661 | if (result.length) { 662 | return true; 663 | } 664 | return false; 665 | } 666 | 667 | 668 | const gopherurlParser = createParser(); 669 | setParser(gopherurlParser, seq(gopherurl, end())); 670 | 671 | function isGopherurl(input: string) { 672 | const result = gopherurlParser[0](input); 673 | if (result.length) { 674 | return true; 675 | } 676 | return false; 677 | } 678 | 679 | 680 | const waisurlParser = createParser(); 681 | setParser(waisurlParser, seq(waisurl, end())); 682 | 683 | function isWaisurl(input: string) { 684 | const result = waisurlParser[0](input); 685 | if (result.length) { 686 | return true; 687 | } 688 | return false; 689 | } 690 | 691 | 692 | const mailtourlParser = createParser(); 693 | setParser(mailtourlParser, seq(mailtourl, end())); 694 | 695 | function isMailtourl(input: string) { 696 | const result = mailtourlParser[0](input); 697 | if (result.length) { 698 | return true; 699 | } 700 | return false; 701 | } 702 | 703 | 704 | const fileurlParser = createParser(); 705 | setParser(fileurlParser, seq(fileurl, end())); 706 | 707 | function isFileurl(input: string) { 708 | const result = fileurlParser[0](input); 709 | if (result.length) { 710 | return true; 711 | } 712 | return false; 713 | } 714 | 715 | 716 | const prosperourlParser = createParser(); 717 | setParser(prosperourlParser, seq(prosperourl, end())); 718 | 719 | function isProsperourl(input: string) { 720 | const result = prosperourlParser[0](input); 721 | if (result.length) { 722 | return true; 723 | } 724 | return false; 725 | } 726 | 727 | 728 | const otherurlParser = createParser(); 729 | setParser(otherurlParser, seq(otherurl, end())); 730 | 731 | function isOtherurl(input: string) { 732 | const result = otherurlParser[0](input); 733 | if (result.length) { 734 | return true; 735 | } 736 | return false; 737 | } 738 | 739 | 740 | export { 741 | isGenericurl, 742 | isUrl, 743 | isHttpurl, 744 | isFtpurl, 745 | isNewsurl, 746 | isNntpurl, 747 | isTelneturl, 748 | isGopherurl, 749 | isWaisurl, 750 | isMailtourl, 751 | isFileurl, 752 | isProsperourl, 753 | isOtherurl, 754 | }; 755 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------