├── README.md ├── code2ast.js ├── config ├── dataset │ └── dataset.yaml └── tools │ ├── conkas.yaml │ ├── honeybadger.yaml │ ├── maian.yaml │ ├── manticore.yaml │ ├── mythril.yaml │ ├── osiris.yaml │ ├── oyente.yaml │ ├── securify.yaml │ ├── slither.yaml │ ├── smartcheck.yaml │ └── solhint.yaml ├── dataset_vul.tar.gz ├── entropy_compute.py ├── genetic.py ├── main.py ├── multistep_RLRep.py ├── node_modules ├── @solidity-parser │ └── parser │ │ ├── CHANGES.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── dist │ │ ├── Solidity-JSLPOCIO.tokens │ │ ├── Solidity-WDNIKDDG.tokens │ │ ├── antlr │ │ │ ├── Solidity.tokens │ │ │ └── SolidityLexer.tokens │ │ ├── index.cjs.js │ │ ├── index.cjs.js.map │ │ ├── index.iife.js │ │ ├── index.iife.js.map │ │ ├── src │ │ │ ├── ASTBuilder.d.ts │ │ │ ├── ErrorListener.d.ts │ │ │ ├── antlr │ │ │ │ ├── SolidityLexer.d.ts │ │ │ │ ├── SolidityListener.d.ts │ │ │ │ ├── SolidityParser.d.ts │ │ │ │ └── SolidityVisitor.d.ts │ │ │ ├── ast-types.d.ts │ │ │ ├── index.d.ts │ │ │ ├── parser.d.ts │ │ │ ├── tokens-string.d.ts │ │ │ ├── tokens.d.ts │ │ │ └── types.d.ts │ │ └── test │ │ │ ├── ast.d.ts │ │ │ ├── index.d.ts │ │ │ └── utils.d.ts │ │ ├── package.json │ │ └── src │ │ ├── ASTBuilder.ts │ │ ├── ErrorListener.ts │ │ ├── antlr │ │ ├── Solidity.interp │ │ ├── Solidity.tokens │ │ ├── SolidityLexer.interp │ │ ├── SolidityLexer.tokens │ │ ├── SolidityLexer.ts │ │ ├── SolidityListener.ts │ │ ├── SolidityParser.ts │ │ └── SolidityVisitor.ts │ │ ├── ast-types.ts │ │ ├── declarations.d.ts │ │ ├── index.ts │ │ ├── parser.ts │ │ ├── tokens-string.js │ │ ├── tokens.ts │ │ └── types.ts └── solidity-parser-antlr │ ├── CHANGES.md │ ├── LICENSE │ ├── README.md │ ├── dist │ ├── ASTBuilder.js │ ├── ErrorListener.js │ ├── antlr4 │ │ ├── BufferedTokenStream.js │ │ ├── CharStreams.js │ │ ├── CommonTokenFactory.js │ │ ├── CommonTokenStream.js │ │ ├── FileStream.js │ │ ├── InputStream.js │ │ ├── IntervalSet.js │ │ ├── LL1Analyzer.js │ │ ├── Lexer.js │ │ ├── Parser.js │ │ ├── ParserRuleContext.js │ │ ├── PredictionContext.js │ │ ├── Recognizer.js │ │ ├── RuleContext.js │ │ ├── Token.js │ │ ├── Utils.js │ │ ├── atn │ │ │ ├── ATN.js │ │ │ ├── ATNConfig.js │ │ │ ├── ATNConfigSet.js │ │ │ ├── ATNDeserializationOptions.js │ │ │ ├── ATNDeserializer.js │ │ │ ├── ATNSimulator.js │ │ │ ├── ATNState.js │ │ │ ├── ATNType.js │ │ │ ├── LexerATNSimulator.js │ │ │ ├── LexerAction.js │ │ │ ├── LexerActionExecutor.js │ │ │ ├── ParserATNSimulator.js │ │ │ ├── PredictionMode.js │ │ │ ├── SemanticContext.js │ │ │ ├── Transition.js │ │ │ └── index.js │ │ ├── dfa │ │ │ ├── DFA.js │ │ │ ├── DFASerializer.js │ │ │ ├── DFAState.js │ │ │ └── index.js │ │ ├── error │ │ │ ├── DiagnosticErrorListener.js │ │ │ ├── ErrorListener.js │ │ │ ├── ErrorStrategy.js │ │ │ ├── Errors.js │ │ │ └── index.js │ │ ├── index.js │ │ ├── polyfills │ │ │ ├── codepointat.js │ │ │ └── fromcodepoint.js │ │ └── tree │ │ │ ├── Tree.js │ │ │ ├── Trees.js │ │ │ └── index.js │ ├── index.js │ ├── lib │ │ ├── SolidityLexer.js │ │ ├── SolidityListener.js │ │ └── SolidityParser.js │ └── tokens.js │ ├── index.d.ts │ ├── package.json │ └── tslint.json ├── requirements.txt ├── similarity_compute.py ├── smartBugs.py ├── solidity-extractor ├── extractor.js ├── function.js └── function_faultline.js ├── solidityparser ├── Solidity.interp ├── Solidity.tokens ├── SolidityLexer.interp ├── SolidityLexer.py ├── SolidityLexer.tokens ├── SolidityListener.py └── SolidityParser.py ├── src ├── docker_api │ └── docker_api.py ├── exception │ └── VulnerabilityNotFoundException.py ├── interface │ └── cli.py └── output_parser │ ├── Conkas.py │ ├── HoneyBadger.py │ ├── Maian.py │ ├── Manticore.py │ ├── Mythril.py │ ├── Osiris.py │ ├── Oyente.py │ ├── Parser.py │ ├── SarifHolder.py │ ├── Securify.py │ ├── Slither.py │ ├── Smartcheck.py │ ├── Solhint.py │ ├── __init__.py │ └── sarif_vulnerability_mapping.csv ├── top300_identifier_dict.txt ├── utils ├── docker │ ├── smartbugs-maian │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── requirements.txt │ │ └── scripts │ │ │ ├── printContractNames.py │ │ │ ├── runMAIANall.sh │ │ │ └── test_runner.py │ └── smartbugs-manticore │ │ ├── Dockerfile │ │ ├── README.md │ │ └── scripts │ │ ├── printContractNames.py │ │ └── runManticore.sh ├── scripts │ └── get_vulns_lines.js └── vagrant │ ├── README.md │ ├── Vagrantfile │ ├── provision.sh │ └── vagrant-box-screenshot.png └── utils2.py /README.md: -------------------------------------------------------------------------------- 1 | # RLRep 2 | 3 | 4 | RLRep is a project to automatically generate program repair recommendation in the field of smart contracts for given code snippets with their contexts. 5 | The source code and dataset are opened. 6 | 7 | ## Introduction 8 | 9 | `multistep_RLRep.py`: the model framework for reinforcement learning and its implementation 10 | 11 | `src/`, `config/`, `utils/` and `smartBugs.py`: integrated the *smartBugs* tool ([Ferreira et al.](https://dl.acm.org/doi/abs/10.1145/3324884.3415298)). 12 | 13 | `similarity_compute.py` and `FastText/`(download from [Zenodo](https://zenodo.org/records/15039940) because of Github upload size limit): by *FastText* library, compute the *similarity* (proposed by [Gao et al.](https://ieeexplore.ieee.org/abstract/document/8979435/)) between the generated contract and the buggy contract. (one of the modules that make up the reward function) 14 | 15 | `entropy_compute.py` and `entropy_compute/`(download from [Zenodo](https://zenodo.org/records/15039940) because of Github upload size limit): by the concept of *entropy* proposed by [Ray et al.](https://ieeexplore.ieee.org/abstract/document/7886923), compute the entropy of the generated contract. (one of the modules that make up the reward function as well) 16 | 17 | `utils2.py`: some useful methods of reward function and reinforcement learning. 18 | 19 | `top300_identifier_dict.txt`: top-300 most frequent tokens in the source code. 20 | 21 | `solidityparser/`: the Solidity lexer and parser built on top of ANTLR. 22 | 23 | `code2ast.js` and `node_modules/`: convert source code to a preorder traversal sequence of AST. 24 | 25 | `genetic.py`: the implement of the search-and-genetic-algorithm-based smart contract repair approach proposed by [Yu et al.](https://dl.acm.org/doi/abs/10.1145/3402450) 26 | 27 | `dataset_vul.tar.gz`: unzip it to get the folder `dataset_vul/`. It includes `full_contract_dataset/` (853 vulnerable smart contracts), `contract/`(the source code of the buggy contract labeled with fault location), `ast/`(the preorder sequence of the abstract syntax tree of the buggy function), `threelines-tokenseq/`(the previous line, the next line and the buggy line) and `repair_contract/` (the correct generated patches). 28 | 29 | `requirements.txt`: a file listing all the dependencies for RLRepair 30 | 31 | ## Usage 32 | 33 | 1. Install packages needed using pip: 34 | 35 | ``` 36 | pip install -r requirements.txt 37 | ``` 38 | 39 | 2. Unzip `dataset_vul.tar.gz` 40 | 41 | 3. make sure that all input files are ready: (you can refer to the format of our input files in `dataset_vul/newALLBUGS/`) 42 | 43 | - mapping (map source token to index): `code_w2i.pkl`, `code_i2w.pkl`, `ast_w2i.pkl` and `ast_i2w.pkl` 44 | - first input: `threelines-tokenseq/` 45 | - second input: `ast/` 46 | - data for pretraining: `pretrain/` and `pretrain_label/` 47 | - data for validation: `validation/` 48 | 49 | 4. Add new methods 50 | 51 | Enter the `antlr4` package and find the `RuleContext.py` and `Trees.py` (Some IDEs such as PyCharm can implement this process). 52 | 53 | Add the method code below in the `RuleContext` class in `RuleContext.py`. 54 | ``` 55 | def toCodeSequence(self, ruleNames:list=None, recog:Parser=None): 56 | return Trees.toCodeSequence(self, ruleNames=ruleNames, recog=recog) 57 | ``` 58 | 59 | Add the method code below in the `Trees` class in `Trees.py`. 60 | ``` 61 | @classmethod 62 | def toCodeSequence(cls, t:Tree, ruleNames:list=None, recog:Parser=None): 63 | if recog is not None: 64 | ruleNames = recog.ruleNames 65 | s = escapeWhitespace(cls.getNodeText(t, ruleNames), False) 66 | if t.getChildCount()==0: 67 | return s 68 | with StringIO() as buf: 69 | buf.write(s) 70 | buf.write(' ') 71 | for i in range(0, t.getChildCount()): 72 | if i > 0: 73 | buf.write(' ') 74 | buf.write(cls.toCodeSequence(t.getChild(i), ruleNames)) 75 | 76 | return buf.getvalue() 77 | ``` 78 | 79 | 80 | 5. training and validation 81 | 82 | ```shell 83 | python main.py [model_name] [dataset_path] 84 | # for example: 85 | python main.py multistep_RLRep dataset_vul/newALLBUGS 86 | # or 87 | python main.py mutation dataset_vul/newALLBUGS 88 | ``` 89 | 90 | 6. result 91 | 92 | At last, result can be got in `dataset_vul/newALLBUGS/validation/result/`. 93 | 94 | -------------------------------------------------------------------------------- /config/dataset/dataset.yaml: -------------------------------------------------------------------------------- 1 | # SB Curated (local) 2 | access_control: dataset/access_control 3 | arithmetic: dataset/arithmetic 4 | bad_randomness: dataset/bad_randomness 5 | denial_of_service: dataset/denial_of_service 6 | front_running: dataset/front_running 7 | reentrancy: dataset/reentrancy 8 | short_addresses: dataset/short_addresses 9 | time_manipulation: dataset/time_manipulation 10 | unchecked_ll_calls: dataset/unchecked_low_level_calls 11 | 12 | # External datasets 13 | solidiFI: 14 | - url: https://github.com/smartbugs/SolidiFI-benchmark.git 15 | - local_dir: dataset/solidiFI 16 | - subsets: # Accessed as solidiFI/name 17 | - overflow_underflow: buggy_contracts/Overflow-Underflow 18 | - reentrancy: buggy_contracts/Re-entrancy 19 | - tod: buggy_contracts/TOD 20 | - timestamp_dependency: buggy_contracts/Timestamp-Dependency 21 | - unchecked_send: buggy_contracts/Unchecked-Send 22 | - unhandled_exceptions: buggy_contracts/Unhandled-Exceptions 23 | - tx_origin: buggy_contracts/tx.origin 24 | -------------------------------------------------------------------------------- /config/tools/conkas.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: nveloso/conkas 3 | cmd: -fav -s 4 | info: Conkas is based on symbolic execution, determines which inputs cause which program branches to execute, to find potential security vulnerabilities. Conkas uses rattle to lift bytecode to a high level representation. 5 | -------------------------------------------------------------------------------- /config/tools/honeybadger.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: christoftorres/honeybadger 3 | cmd: python honeybadger/honeybadger.py -glt 250 -t 1000 -ll 20 -s 4 | info: An analysis tool to detect honeypots in Ethereum smart contracts -------------------------------------------------------------------------------- /config/tools/maian.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: smartbugs/maian:solc5.10 3 | solc<5: smartbugs/maian:solc4.25 4 | cmd: /runMAIANall.sh 5 | info: Maian is a tool for automatic detection of buggy Ethereum smart contracts of three different types prodigal, suicidal and greedy. 6 | -------------------------------------------------------------------------------- /config/tools/manticore.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: smartbugs/manticore 3 | cmd: /runManticore.sh 4 | output_in_files: 5 | folder: /results 6 | info: Manticore is a symbolic execution tool for analysis of smart contracts and binaries. 7 | -------------------------------------------------------------------------------- /config/tools/mythril.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: qspprotocol/mythril-usolc 3 | solc<5: qspprotocol/mythril-0.4.25 4 | cmd: -xo json 5 | info: Mythril analyses EVM bytecode using symbolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. 6 | -------------------------------------------------------------------------------- /config/tools/osiris.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: christoftorres/osiris 3 | cmd: python osiris/osiris.py -s 4 | info: Osiris is an analysis tool to detect integer bugs in Ethereum smart contracts. Osiris is based on Oyente. 5 | -------------------------------------------------------------------------------- /config/tools/oyente.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: qspprotocol/oyente-0.4.25 3 | cmd: -s 4 | info: Oyente runs on symbolic execution, determines which inputs cause which program branches to execute, to find potential security vulnerabilities. Oyente works directly with EVM bytecode without access high level representation and does not provide soundness nor completeness. 5 | -------------------------------------------------------------------------------- /config/tools/securify.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: qspprotocol/securify-usolc 3 | solc<5: qspprotocol/securify-0.4.25 4 | cmd: --livestatusfile /results/live.json --output /results/results.json -fs 5 | output_in_files: 6 | folder: /results/ 7 | info: Securify uses formal verification, also relying on static analysis checks. Securify’s analysis consists of two steps. First, it symbolically analyzes the contract’s dependency graph to extract precise semantic information from the code. Then, it checks compliance and violation patterns that capture sufficient conditions for proving if a property holds or not. 8 | -------------------------------------------------------------------------------- /config/tools/slither.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: trailofbits/slither 3 | cmd: slither {contract} --json /output.json 4 | output_in_files: 5 | folder: /output.json 6 | info: Slither is a Solidity static analysis framework written in Python 3. It runs a suite of vulnerability detectors and prints visual information about contract details. Slither enables developers to find vulnerabilities, enhance their code comphrehension, and quickly prototype custom analyses. 7 | -------------------------------------------------------------------------------- /config/tools/smartcheck.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: smartbugs/smartcheck 3 | cmd: -p 4 | info: Securify automatically checks for vulnerabilities and bad coding practices. It runs lexical and syntactical analysis on Solidity source code. 5 | -------------------------------------------------------------------------------- /config/tools/solhint.yaml: -------------------------------------------------------------------------------- 1 | docker_image: 2 | default: smartbugs/solhint 3 | cmd: solhint -f unix -q 4 | info: Open source project for linting solidity code. This project provide both security and style guide validations. 5 | -------------------------------------------------------------------------------- /dataset_vul.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anonymous123xx/RLRep/a06f64caa153e22494f5e063dde965044f9b8baf/dataset_vul.tar.gz -------------------------------------------------------------------------------- /entropy_compute.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import subprocess 4 | from antlr4 import * 5 | from solidityparser.SolidityLexer import SolidityLexer 6 | from solidityparser.SolidityParser import SolidityParser 7 | 8 | def get_entropy(contract_path, use_cache): 9 | if use_cache == False: 10 | options = '-ENTROPY -BACKOFF -TEST -FILES' 11 | else: 12 | options = '-ENTROPY -BACKOFF -TEST -CACHE -CACHE_ORDER 3 -CACHE_DYNAMIC_LAMBDA -FILE_CACHE -FILES' 13 | # options_window5000 = '-ENTROPY -BACKOFF -TEST -CACHE -CACHE_ORDER 3 -CACHE_DYNAMIC_LAMBDA -WINDOW_CACHE -WINDOW_SIZE 5000 -FILES' 14 | 15 | completion = 'entropy_compute/code/completion' 16 | scope_file = 'entropy_compute/data/trainset/fold0.train.scope' 17 | grams_file = 'entropy_compute/data/trainset/fold0.train.3grams' # n-grams file 18 | 19 | tmp_dir = "dataset_vul/newALLBUGS/tmp/tmp_function/" 20 | tmp_test = "dataset_vul/newALLBUGS/tmp/test_function/" 21 | os.makedirs(tmp_dir, exist_ok=True) 22 | os.makedirs(tmp_test, exist_ok=True) 23 | parser_js = "solidity-extractor/function.js" 24 | 25 | cp = subprocess.run("cd {} && node ../../../../{} {} >/dev/null".format(tmp_dir, parser_js, contract_path), shell=True, stdout=subprocess.PIPE) 26 | if cp.returncode: 27 | return -9999 28 | name = contract_path.split('/')[-1] 29 | tmp_path = tmp_dir + name 30 | with open(tmp_path) as f: 31 | codestring = f.read() 32 | 33 | tree = SolidityParser(CommonTokenStream(SolidityLexer(InputStream(codestring)))).functionDefinition() 34 | output = tree.toCodeSequence() 35 | regex = r'(\[)[0-9\s]*(\])' 36 | output2 = re.sub(regex, '', output) 37 | output3 = output2.split(' ') 38 | tokens = [char for char in output3 if char != '' and char != ''] 39 | sourceCode = " ".join(tokens) 40 | with open(tmp_path, 'w') as f: 41 | f.write(sourceCode) 42 | 43 | test_file = tmp_test + name 44 | with open(test_file, 'w') as f2: 45 | f2.write(tmp_path) 46 | 47 | # compute entropy 48 | order = 3 49 | cp2 = subprocess.run('{} {} -NGRAM_FILE {} -NGRAM_ORDER {} -SCOPE_FILE {} -INPUT_FILE {}'.format 50 | (completion, options, grams_file, order, scope_file, test_file), shell=True, stdout=subprocess.PIPE) 51 | if cp2.returncode: 52 | raise (IOError, 'code/completion fail') 53 | lines = cp2.stdout.decode().split('\n') 54 | for line in lines: 55 | if 'Entropy: ' in line: 56 | return float(line.strip('Entropy: ')) 57 | 58 | 59 | if __name__ == '__main__': 60 | pass 61 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/CHANGES.md: -------------------------------------------------------------------------------- 1 | ### 0.5.0 (Unreleased) 2 | 3 | * Remove `ParameterList` and `Parameter` node types. Parameters are now always 4 | of type `VariableDeclaration` and lists of parameters are represented as 5 | lists of nodes of type `VariableDeclaration`. This is a breaking change. 6 | 7 | ### 0.4.12 (Unreleased) 8 | 9 | * Fix type name expressions to also support user-defined type names. 10 | 11 | ### 0.4.11 12 | 13 | * Bugfix release 14 | 15 | ### 0.4.9 16 | 17 | * Fix parsing of inheritance specifier with no arguments. 18 | 19 | ### 0.4.8 20 | 21 | * Fix parsing of string literals with escaped characters. 22 | 23 | ### 0.4.7 24 | 25 | * Fix parsing of underscores in number literals. 26 | 27 | ### 0.4.6 28 | 29 | * Add support for the `type` keyword. 30 | * Add support for underscores in number literals. 31 | 32 | ### 0.4.5 33 | 34 | * Improve TypeScript type definitions. 35 | 36 | ### 0.4.4 37 | 38 | * Add missing `storageLocation` to variables in VariableDeclarationStatement. 39 | * Return `null` for `arguments` instead of `[]` when `ModifierInvocation` 40 | contains no arguments and no parentheses to distinguish the two cases. 41 | * Improve TypeScript type definitions. 42 | 43 | ### 0.4.3 44 | 45 | * Improve TypeScript type definitions, thanks @Leeleo3x and @yxliang01. 46 | 47 | ### 0.4.2 48 | 49 | * Fix parsing of assembly function definitions with no args or return args. 50 | 51 | ### 0.4.1 52 | 53 | * Fix parsing of for loops with missing initial and condition statements. 54 | 55 | ### 0.4.0 56 | 57 | * Correctly handle non-existent tuple components. Thanks @maxsam4 58 | * Accept calldata as identifier 59 | 60 | ### 0.3.3 61 | 62 | * Add support for `address payable` typename. 63 | 64 | ### 0.3.2 65 | 66 | * Fix parsing of hex numbers with uppercase X. 67 | 68 | ### 0.3.1 69 | 70 | * Fix parsing of zero-component tuples. 71 | 72 | ### 0.3.0 73 | 74 | * Use `components` for all `TupleExpression` nodes. Earlier versions 75 | incorrectly stored tuple components under the `elements` key. 76 | * Fix parsing of decimal literals without integer part. 77 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017-2018 Federico Bond 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/README.md: -------------------------------------------------------------------------------- 1 | # Solidity Parser for JavaScript 2 | 3 | [![npm version](https://badge.fury.io/js/%40solidity-parser%2Fparser.svg)](https://badge.fury.io/js/%40solidity-parser%2Fparser) 4 | 5 | A JavaScript package for parsing [Solidity](https://solidity.readthedocs.io/) code using [ANTLR (ANother Tool for Language Recognition)](https://www.antlr.org/) grammar. 6 | 7 | This is a fork of [@federicobond](https://github.com/federicobond)'s original [repo](https://github.com/federicobond/solidity-parser-antlr), 8 | with some extra features taken from [Consensys Diligence's alternative fork](https://github.com/consensys/solidity-parser-antlr). 9 | 10 | ## Installation 11 | 12 | The following installation options assume [Node.js](https://nodejs.org/en/download/) has already been installed. 13 | 14 | Using [Node Package Manager (npm)](https://www.npmjs.com/). 15 | 16 | ``` 17 | npm install @solidity-parser/parser 18 | ``` 19 | 20 | Using [yarn](https://yarnpkg.com/) 21 | 22 | ``` 23 | yarn add @solidity-parser/parser 24 | ``` 25 | 26 | ## Usage 27 | 28 | ```javascript 29 | const parser = require('@solidity-parser/parser'); 30 | 31 | const input = ` 32 | contract test { 33 | uint256 a; 34 | function f() {} 35 | } 36 | ` 37 | try { 38 | const ast = parser.parse(input) 39 | console.log(ast) 40 | } catch (e) { 41 | if (e instanceof parser.ParserError) { 42 | console.error(e.errors) 43 | } 44 | } 45 | ``` 46 | 47 | The `parse` method also accepts a second argument which lets you specify the 48 | following options, in a style similar to the _esprima_ API: 49 | 50 | | Key | Type | Default | Description | 51 | |----------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 52 | | tolerant | Boolean | false | When set to `true` it will collect syntax errors and place them in a list under the key `errors` inside the root node of the returned AST. Otherwise, it will raise a `parser.ParserError`. | 53 | | loc | Boolean | false | When set to `true`, it will add location information to each node, with start and stop keys that contain the corresponding line and column numbers. Column numbers start from 0, lines start from 1. | 54 | | range | Boolean | false | When set to `true`, it will add range information to each node, which consists of a two-element array with start and stop character indexes in the input. | 55 | 56 | 57 | ### Example with location information 58 | 59 | ```javascript 60 | parser.parse('contract test { uint a; }', { loc: true }) 61 | 62 | // { type: 'SourceUnit', 63 | // children: 64 | // [ { type: 'ContractDefinition', 65 | // name: 'test', 66 | // baseContracts: [], 67 | // subNodes: [Array], 68 | // kind: 'contract', 69 | // loc: [Object] } ], 70 | // loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 24 } } } 71 | 72 | ``` 73 | 74 | ### Example using a visitor to walk over the AST 75 | 76 | ```javascript 77 | var ast = parser.parse('contract test { uint a; }') 78 | 79 | // output the path of each import found 80 | parser.visit(ast, { 81 | ImportDirective: function(node) { 82 | console.log(node.path) 83 | } 84 | }) 85 | ``` 86 | 87 | ## Usage in the browser 88 | 89 | A browser-friendly version is available in `dist/index.iife.js` (along with its sourcemaps file) in the published version. 90 | 91 | If you are using webpack, keep in mind that minimizing your bundle will mangle function names, breaking the parser. To fix this you can just set `optimization.minimize` to `false`. 92 | 93 | ## Contribution 94 | 95 | This project is dependant on the [@solidity-parser/antlr](https://github.com/solidity-parser/antlr) repository via a git submodule. To clone this repository and the submodule, run 96 | 97 | ``` 98 | git clone --recursive 99 | ``` 100 | 101 | If you have already cloned this repo, you can load the submodule with 102 | 103 | ``` 104 | git submodule update --init 105 | ``` 106 | 107 | This project can be linked to a forked `@solidity-parser/antlr` project by editing the url in the [.gitmodules](.gitmodules) file to point to the forked repo and running 108 | 109 | ``` 110 | git submodule sync 111 | ``` 112 | 113 | The Solidity ANTLR file [Solidity.g4](./antlr/Solidity.g4) can be built with the following. This will also download the ANTLR Java Archive (jar) file to `antlr/antlr4.jar` if it doesn't already exist. The generated ANTLR tokens and JavaScript files are copied the [src](./src) folder. 114 | 115 | ``` 116 | yarn run antlr 117 | ``` 118 | 119 | The files to be distributed with the npm package are in the `dist` folder and built by running 120 | 121 | ``` 122 | yarn run build 123 | ``` 124 | 125 | The [mocha](https://mochajs.org/) tests under the [test](./test) folder can be run with the following. This includes parsing the [test.sol](./test/test.sol) Solidity file. 126 | 127 | ``` 128 | yarn run test 129 | ``` 130 | 131 | ## Used by 132 | 133 | * [Hardhat](https://hardhat.org/) 134 | * [sol2uml](https://github.com/naddison36/sol2uml) 135 | * [Solhint](https://github.com/protofire/solhint/) 136 | * [solidity-coverage](https://github.com/sc-forks/solidity-coverage) 137 | * [prettier-solidity](https://github.com/prettier-solidity/prettier-plugin-solidity/) 138 | * [eth-gas-reporter](https://github.com/cgewecke/eth-gas-reporter) 139 | 140 | ## License 141 | 142 | [MIT](./LICENSE) 143 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/Solidity-JSLPOCIO.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/Solidity-WDNIKDDG.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | Int=96 97 | Uint=97 98 | Byte=98 99 | Fixed=99 100 | Ufixed=100 101 | BooleanLiteral=101 102 | DecimalNumber=102 103 | HexNumber=103 104 | NumberUnit=104 105 | HexLiteralFragment=105 106 | ReservedKeyword=106 107 | AnonymousKeyword=107 108 | BreakKeyword=108 109 | ConstantKeyword=109 110 | ImmutableKeyword=110 111 | ContinueKeyword=111 112 | LeaveKeyword=112 113 | ExternalKeyword=113 114 | IndexedKeyword=114 115 | InternalKeyword=115 116 | PayableKeyword=116 117 | PrivateKeyword=117 118 | PublicKeyword=118 119 | VirtualKeyword=119 120 | PureKeyword=120 121 | TypeKeyword=121 122 | ViewKeyword=122 123 | ConstructorKeyword=123 124 | FallbackKeyword=124 125 | ReceiveKeyword=125 126 | Identifier=126 127 | StringLiteralFragment=127 128 | VersionLiteral=128 129 | WS=129 130 | COMMENT=130 131 | LINE_COMMENT=131 132 | 'pragma'=1 133 | ';'=2 134 | '||'=3 135 | '^'=4 136 | '~'=5 137 | '>='=6 138 | '>'=7 139 | '<'=8 140 | '<='=9 141 | '='=10 142 | 'as'=11 143 | 'import'=12 144 | '*'=13 145 | 'from'=14 146 | '{'=15 147 | ','=16 148 | '}'=17 149 | 'abstract'=18 150 | 'contract'=19 151 | 'interface'=20 152 | 'library'=21 153 | 'is'=22 154 | '('=23 155 | ')'=24 156 | 'using'=25 157 | 'for'=26 158 | 'struct'=27 159 | 'modifier'=28 160 | 'function'=29 161 | 'returns'=30 162 | 'event'=31 163 | 'enum'=32 164 | '['=33 165 | ']'=34 166 | 'address'=35 167 | '.'=36 168 | 'mapping'=37 169 | '=>'=38 170 | 'memory'=39 171 | 'storage'=40 172 | 'calldata'=41 173 | 'if'=42 174 | 'else'=43 175 | 'try'=44 176 | 'catch'=45 177 | 'while'=46 178 | 'unchecked'=47 179 | 'assembly'=48 180 | 'do'=49 181 | 'return'=50 182 | 'throw'=51 183 | 'emit'=52 184 | 'var'=53 185 | 'bool'=54 186 | 'string'=55 187 | 'byte'=56 188 | '++'=57 189 | '--'=58 190 | 'new'=59 191 | ':'=60 192 | '+'=61 193 | '-'=62 194 | 'after'=63 195 | 'delete'=64 196 | '!'=65 197 | '**'=66 198 | '/'=67 199 | '%'=68 200 | '<<'=69 201 | '>>'=70 202 | '&'=71 203 | '|'=72 204 | '=='=73 205 | '!='=74 206 | '&&'=75 207 | '?'=76 208 | '|='=77 209 | '^='=78 210 | '&='=79 211 | '<<='=80 212 | '>>='=81 213 | '+='=82 214 | '-='=83 215 | '*='=84 216 | '/='=85 217 | '%='=86 218 | 'let'=87 219 | ':='=88 220 | '=:'=89 221 | 'switch'=90 222 | 'case'=91 223 | 'default'=92 224 | '->'=93 225 | 'callback'=94 226 | 'override'=95 227 | 'anonymous'=107 228 | 'break'=108 229 | 'constant'=109 230 | 'immutable'=110 231 | 'continue'=111 232 | 'leave'=112 233 | 'external'=113 234 | 'indexed'=114 235 | 'internal'=115 236 | 'payable'=116 237 | 'private'=117 238 | 'public'=118 239 | 'virtual'=119 240 | 'pure'=120 241 | 'type'=121 242 | 'view'=122 243 | 'constructor'=123 244 | 'fallback'=124 245 | 'receive'=125 246 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/antlr/Solidity.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/antlr/SolidityLexer.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/ErrorListener.d.ts: -------------------------------------------------------------------------------- 1 | import antlr4 from 'antlr4'; 2 | declare class ErrorListener extends antlr4.error.ErrorListener { 3 | private _errors; 4 | constructor(); 5 | syntaxError(recognizer: any, offendingSymbol: any, line: number, column: number, message: string): void; 6 | getErrors(): any[]; 7 | hasErrors(): boolean; 8 | } 9 | export default ErrorListener; 10 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/index.d.ts: -------------------------------------------------------------------------------- 1 | export * from "./parser"; 2 | export type { ParseOptions } from "./types"; 3 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/parser.d.ts: -------------------------------------------------------------------------------- 1 | import { ASTNode, ASTVisitor, SourceUnit } from './ast-types'; 2 | import { ParseOptions, Token, TokenizeOptions } from './types'; 3 | interface ParserErrorItem { 4 | message: string; 5 | line: number; 6 | column: number; 7 | } 8 | declare type ParseResult = SourceUnit & { 9 | errors?: any[]; 10 | tokens?: Token[]; 11 | }; 12 | export declare class ParserError extends Error { 13 | errors: ParserErrorItem[]; 14 | constructor(args: { 15 | errors: ParserErrorItem[]; 16 | }); 17 | } 18 | export declare function tokenize(input: string, options?: TokenizeOptions): any; 19 | export declare function parse(input: string, options?: ParseOptions): ParseResult; 20 | export declare function visit(node: unknown, visitor: ASTVisitor, nodeParent?: ASTNode): void; 21 | export {}; 22 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/tokens-string.d.ts: -------------------------------------------------------------------------------- 1 | declare const _exports: any; 2 | export = _exports; 3 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/tokens.d.ts: -------------------------------------------------------------------------------- 1 | import { Token, AntlrToken, TokenizeOptions } from './types'; 2 | export declare function buildTokenList(tokensArg: AntlrToken[], options: TokenizeOptions): Token[]; 3 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/src/types.d.ts: -------------------------------------------------------------------------------- 1 | import { Token as Antlr4TsToken } from "antlr4ts"; 2 | export interface Node { 3 | type: string; 4 | } 5 | export declare type AntlrToken = Antlr4TsToken; 6 | export interface TokenizeOptions { 7 | range?: boolean; 8 | loc?: boolean; 9 | } 10 | export interface ParseOptions extends TokenizeOptions { 11 | tokens?: boolean; 12 | tolerant?: boolean; 13 | } 14 | export interface Token { 15 | type: string; 16 | value: string | undefined; 17 | range?: [number, number]; 18 | loc?: { 19 | start: { 20 | line: number; 21 | column: number; 22 | }; 23 | end: { 24 | line: number; 25 | column: number; 26 | }; 27 | }; 28 | } 29 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/test/ast.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/test/index.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/dist/test/utils.d.ts: -------------------------------------------------------------------------------- 1 | import { ParseOptions } from '../src/types'; 2 | export declare function parseContract(source: string, options?: ParseOptions): any; 3 | export declare function parseNode(source: string, options?: {}): any; 4 | export declare function parseStatement(source: string, options?: {}): any; 5 | export declare function parseExpression(source: string, options?: {}): any; 6 | export declare function parseAssembly(source: string, options?: {}): any; 7 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "_from": "@solidity-parser/parser", 3 | "_id": "@solidity-parser/parser@0.14.0", 4 | "_inBundle": false, 5 | "_integrity": "sha512-cX0JJRcmPtNUJpzD2K7FdA7qQsTOk1UZnFx2k7qAg9ZRvuaH5NBe5IEdBMXGlmf2+FmjhqbygJ26H8l2SV7aKQ==", 6 | "_location": "/@solidity-parser/parser", 7 | "_phantomChildren": {}, 8 | "_requested": { 9 | "type": "tag", 10 | "registry": true, 11 | "raw": "@solidity-parser/parser", 12 | "name": "@solidity-parser/parser", 13 | "escapedName": "@solidity-parser%2fparser", 14 | "scope": "@solidity-parser", 15 | "rawSpec": "", 16 | "saveSpec": null, 17 | "fetchSpec": "latest" 18 | }, 19 | "_requiredBy": [ 20 | "#USER", 21 | "/" 22 | ], 23 | "_resolved": "https://registry.npmjs.org/@solidity-parser/parser/-/parser-0.14.0.tgz", 24 | "_shasum": "d51f074efb0acce0e953ec48133561ed710cebc0", 25 | "_spec": "@solidity-parser/parser", 26 | "_where": "/home/chenyy/learning_code_change/dataset2_med/solidity-extractor", 27 | "authors": [ 28 | "Franco Victorio", 29 | "Nick Addison", 30 | "Gonçalo Sá ", 31 | "Federico Bond " 32 | ], 33 | "browser": { 34 | "fs": false, 35 | "path": false 36 | }, 37 | "bugs": { 38 | "url": "https://github.com/solidity-parser/parser/issues" 39 | }, 40 | "bundleDependencies": false, 41 | "dependencies": { 42 | "antlr4ts": "^0.5.0-alpha.4" 43 | }, 44 | "deprecated": false, 45 | "description": "A Solidity parser built from a robust ANTLR 4 grammar", 46 | "devDependencies": { 47 | "@types/chai": "^4.2.16", 48 | "@types/mocha": "^8.2.2", 49 | "@types/node": "^14.14.41", 50 | "@typescript-eslint/eslint-plugin": "^4.9.0", 51 | "@typescript-eslint/parser": "^4.9.0", 52 | "antlr4": "^4.9.0", 53 | "antlr4ts-cli": "^0.5.0-alpha.4", 54 | "assert": "^2.0.0", 55 | "chai": "^4.2.0", 56 | "esbuild": "^0.11.13", 57 | "esbuild-register": "^2.5.0", 58 | "eslint": "^7.15.0", 59 | "eslint-plugin-import": "^2.18.2", 60 | "eslint-plugin-node": "^9.2.0", 61 | "eslint-plugin-promise": "^4.2.1", 62 | "eslint-plugin-standard": "^4.0.1", 63 | "karma": "^6.3.2", 64 | "karma-chrome-launcher": "^3.1.0", 65 | "karma-mocha": "^2.0.1", 66 | "mocha": "^6.2.0", 67 | "nyc": "^14.1.1", 68 | "prettier": "^2.2.1", 69 | "puppeteer": "^9.0.0", 70 | "shx": "^0.3.3", 71 | "ts-node": "^9.1.1", 72 | "typescript": "^4.1.2", 73 | "util": "^0.12.3", 74 | "yarn": "^1.17.3" 75 | }, 76 | "files": [ 77 | "dist/**/*", 78 | "src/**/*" 79 | ], 80 | "homepage": "https://github.com/solidity-parser/parser", 81 | "license": "MIT", 82 | "main": "dist/index.cjs.js", 83 | "name": "@solidity-parser/parser", 84 | "nyc": { 85 | "extension": [ 86 | ".ts" 87 | ] 88 | }, 89 | "repository": { 90 | "type": "git", 91 | "url": "git+https://github.com/solidity-parser/parser.git" 92 | }, 93 | "scripts": { 94 | "antlr": "antlr4ts -visitor antlr/Solidity.g4 -o src", 95 | "build": "npm run build:node && npm run build:browser && npm run generate-types && npm run copy-files", 96 | "build:browser": "esbuild src/index.ts --outfile=dist/index.iife.js --bundle --loader:.tokens=file --sourcemap --format=iife --global-name=SolidityParser --define:__dirname=true --define:BROWSER=true --inject:./process-shim.js", 97 | "build:node": "esbuild src/index.ts --outfile=dist/index.cjs.js --bundle --loader:.tokens=file --sourcemap --format=cjs --platform=node --target=node12", 98 | "copy-files": "shx mkdir -p dist/antlr && shx cp './src/antlr/*tokens' dist/antlr", 99 | "generate-types": "tsc", 100 | "lint": "eslint src test", 101 | "prepack": "npm run build", 102 | "prettier": "prettier --write 'src/**/*' 'test/**/*'", 103 | "test": "npm run test:node && npm run test:browser", 104 | "test:browser": "karma start karma.conf.js", 105 | "test:coverage": "nyc mocha", 106 | "test:integration": "mocha --config ./.mocharc-integration.js test-integration", 107 | "test:node": "mocha" 108 | }, 109 | "types": "dist/src/index.d.ts", 110 | "version": "0.14.0" 111 | } 112 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/ErrorListener.ts: -------------------------------------------------------------------------------- 1 | import antlr4 from 'antlr4' 2 | 3 | class ErrorListener extends antlr4.error.ErrorListener { 4 | private _errors: any[] 5 | 6 | constructor() { 7 | super() 8 | 9 | this._errors = [] 10 | } 11 | 12 | syntaxError( 13 | recognizer: any, 14 | offendingSymbol: any, 15 | line: number, 16 | column: number, 17 | message: string 18 | ) { 19 | this._errors.push({ message, line, column }) 20 | } 21 | 22 | getErrors(): any[] { 23 | return this._errors 24 | } 25 | 26 | hasErrors() { 27 | return this._errors.length > 0 28 | } 29 | } 30 | 31 | export default ErrorListener 32 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/antlr/Solidity.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/antlr/SolidityLexer.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/declarations.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'antlr4' 2 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./parser"; 2 | 3 | export type { ParseOptions } from "./types"; 4 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/parser.ts: -------------------------------------------------------------------------------- 1 | import { ANTLRInputStream, CommonTokenStream } from 'antlr4ts' 2 | 3 | import { SolidityLexer } from './antlr/SolidityLexer' 4 | import { SolidityParser } from './antlr/SolidityParser' 5 | import { ASTNode, astNodeTypes, ASTNodeTypeString, ASTVisitor, SourceUnit } from './ast-types' 6 | import { ASTBuilder } from './ASTBuilder' 7 | import ErrorListener from './ErrorListener' 8 | import { buildTokenList } from './tokens' 9 | import { ParseOptions, Token, TokenizeOptions } from './types' 10 | 11 | interface ParserErrorItem { 12 | message: string 13 | line: number 14 | column: number 15 | } 16 | 17 | type ParseResult = SourceUnit & { 18 | errors?: any[] 19 | tokens?: Token[] 20 | } 21 | 22 | export class ParserError extends Error { 23 | public errors: ParserErrorItem[] 24 | 25 | constructor(args: { errors: ParserErrorItem[] }) { 26 | super() 27 | const { message, line, column } = args.errors[0] 28 | this.message = `${message} (${line}:${column})` 29 | this.errors = args.errors 30 | 31 | if (Error.captureStackTrace !== undefined) { 32 | Error.captureStackTrace(this, this.constructor) 33 | } else { 34 | this.stack = new Error().stack 35 | } 36 | } 37 | } 38 | 39 | export function tokenize(input: string, options: TokenizeOptions = {}): any { 40 | const inputStream = new ANTLRInputStream(input) 41 | const lexer = new SolidityLexer(inputStream) 42 | 43 | return buildTokenList(lexer.getAllTokens(), options) 44 | } 45 | 46 | export function parse( 47 | input: string, 48 | options: ParseOptions = {} 49 | ): ParseResult { 50 | const inputStream = new ANTLRInputStream(input) 51 | const lexer = new SolidityLexer(inputStream) 52 | const tokenStream = new CommonTokenStream(lexer) 53 | const parser = new SolidityParser(tokenStream) 54 | 55 | const listener = new ErrorListener() 56 | lexer.removeErrorListeners() 57 | lexer.addErrorListener(listener) 58 | 59 | parser.removeErrorListeners() 60 | parser.addErrorListener(listener) 61 | parser.buildParseTree = true 62 | 63 | const sourceUnit = parser.sourceUnit() 64 | 65 | const astBuilder = new ASTBuilder(options) 66 | 67 | astBuilder.visit(sourceUnit) 68 | 69 | const ast: ParseResult | null = astBuilder.result as any 70 | 71 | if (ast === null) { 72 | throw new Error('ast should never be null') 73 | } 74 | 75 | let tokenList: Token[] = [] 76 | if (options.tokens === true) { 77 | tokenList = buildTokenList(tokenStream.getTokens(), options) 78 | } 79 | 80 | if (options.tolerant !== true && listener.hasErrors()) { 81 | throw new ParserError({ errors: listener.getErrors() }) 82 | } 83 | if (options.tolerant === true && listener.hasErrors()) { 84 | ast.errors = listener.getErrors() 85 | } 86 | if (options.tokens === true) { 87 | ast.tokens = tokenList 88 | } 89 | 90 | return ast 91 | } 92 | 93 | function _isASTNode(node: unknown): node is ASTNode { 94 | if (typeof node !== 'object' || node === null) { 95 | return false 96 | } 97 | 98 | const nodeAsAny: any = node 99 | 100 | if (Object.prototype.hasOwnProperty.call(nodeAsAny, 'type') && typeof nodeAsAny.type === "string") { 101 | return astNodeTypes.includes(nodeAsAny.type) 102 | } 103 | 104 | return false; 105 | } 106 | 107 | export function visit(node: unknown, visitor: ASTVisitor, nodeParent?: ASTNode): void { 108 | if (Array.isArray(node)) { 109 | node.forEach((child) => visit(child, visitor, nodeParent)) 110 | } 111 | 112 | if (!_isASTNode(node)) return 113 | 114 | let cont = true 115 | 116 | if (visitor[node.type] !== undefined) { 117 | // TODO can we avoid this `as any` 118 | cont = visitor[node.type]!(node as any, nodeParent) 119 | } 120 | 121 | if (cont === false) return 122 | 123 | for (const prop in node) { 124 | if (Object.prototype.hasOwnProperty.call(node, prop)) { 125 | // TODO can we avoid this `as any` 126 | visit((node as any)[prop], visitor, node) 127 | } 128 | } 129 | 130 | const selector = (node.type + ':exit') as `${ASTNodeTypeString}:exit` 131 | if (visitor[selector] !== undefined) { 132 | // TODO can we avoid this `as any` 133 | visitor[selector]!(node as any, nodeParent) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/tokens-string.js: -------------------------------------------------------------------------------- 1 | // This is an indirect file to import the tokens string 2 | // It needs to be a js file so that tsc doesn't complain 3 | 4 | if (typeof BROWSER !== "undefined") { 5 | module.exports = require('./antlr/Solidity.tokens') 6 | } else { 7 | module.exports = require('fs') 8 | .readFileSync(require('path').join(__dirname, './antlr/Solidity.tokens')) 9 | .toString() 10 | } 11 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/tokens.ts: -------------------------------------------------------------------------------- 1 | import { Token, AntlrToken, TokenizeOptions } from './types' 2 | import untypedTokens from './tokens-string' 3 | 4 | const tokens = untypedTokens as string 5 | 6 | const TYPE_TOKENS = [ 7 | 'var', 8 | 'bool', 9 | 'address', 10 | 'string', 11 | 'Int', 12 | 'Uint', 13 | 'Byte', 14 | 'Fixed', 15 | 'UFixed', 16 | ] 17 | 18 | function rsplit(str: string, value: string) { 19 | const index = str.lastIndexOf(value) 20 | return [str.substring(0, index), str.substring(index + 1, str.length)] 21 | } 22 | 23 | function normalizeTokenType(value: string) { 24 | if (value.endsWith("'")) { 25 | value = value.substring(0, value.length - 1) 26 | } 27 | if (value.startsWith("'")) { 28 | value = value.substring(1, value.length) 29 | } 30 | return value 31 | } 32 | 33 | function getTokenType(value: string) { 34 | if (value === 'Identifier' || value === 'from') { 35 | return 'Identifier' 36 | } else if (value === 'TrueLiteral' || value === 'FalseLiteral') { 37 | return 'Boolean' 38 | } else if (value === 'VersionLiteral') { 39 | return 'Version' 40 | } else if (value === 'StringLiteral') { 41 | return 'String' 42 | } else if (TYPE_TOKENS.includes(value)) { 43 | return 'Type' 44 | } else if (value === 'NumberUnit') { 45 | return 'Subdenomination' 46 | } else if (value === 'DecimalNumber') { 47 | return 'Numeric' 48 | } else if (value === 'HexLiteral') { 49 | return 'Hex' 50 | } else if (value === 'ReservedKeyword') { 51 | return 'Reserved' 52 | } else if (/^\W+$/.test(value)) { 53 | return 'Punctuator' 54 | } else { 55 | return 'Keyword' 56 | } 57 | } 58 | 59 | function getTokenTypeMap() { 60 | return tokens 61 | .split('\n') 62 | .map((line) => rsplit(line, '=')) 63 | .reduce((acum: any, [value, key]) => { 64 | acum[parseInt(key, 10)] = normalizeTokenType(value) 65 | return acum 66 | }, {}) 67 | } 68 | 69 | export function buildTokenList( 70 | tokensArg: AntlrToken[], 71 | options: TokenizeOptions 72 | ): Token[] { 73 | const tokenTypes = getTokenTypeMap() 74 | 75 | const result = tokensArg.map((token) => { 76 | const type = getTokenType(tokenTypes[token.type]) 77 | const node: Token = { type, value: token.text } 78 | if (options.range === true) { 79 | node.range = [token.startIndex, token.stopIndex + 1] 80 | } 81 | if (options.loc === true) { 82 | node.loc = { 83 | start: { line: token.line, column: token.charPositionInLine }, 84 | end: { line: token.line, column: token.charPositionInLine + (token.text?.length ?? 0) }, 85 | } 86 | } 87 | return node 88 | }) 89 | 90 | return result 91 | } 92 | -------------------------------------------------------------------------------- /node_modules/@solidity-parser/parser/src/types.ts: -------------------------------------------------------------------------------- 1 | import { Token as Antlr4TsToken } from "antlr4ts"; 2 | export interface Node { 3 | type: string 4 | } 5 | 6 | export type AntlrToken = Antlr4TsToken; 7 | 8 | export interface TokenizeOptions { 9 | range?: boolean 10 | loc?: boolean 11 | } 12 | 13 | export interface ParseOptions extends TokenizeOptions { 14 | tokens?: boolean 15 | tolerant?: boolean 16 | } 17 | 18 | export interface Token { 19 | type: string 20 | value: string | undefined 21 | range?: [number, number] 22 | loc?: { 23 | start: { 24 | line: number 25 | column: number 26 | } 27 | end: { 28 | line: number 29 | column: number 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/CHANGES.md: -------------------------------------------------------------------------------- 1 | ### 0.5.0 (Unreleased) 2 | 3 | * Remove `ParameterList` and `Parameter` node types. Parameters are now always 4 | of type `VariableDeclaration` and lists of parameters are represented as 5 | lists of nodes of type `VariableDeclaration`. This is a breaking change. 6 | 7 | ### 0.4.9 8 | 9 | * Fix parsing of inheritance specifier with no arguments. 10 | 11 | ### 0.4.8 12 | 13 | * Fix parsing of string literals with escaped characters. 14 | 15 | ### 0.4.7 16 | 17 | * Fix parsing of underscores in number literals. 18 | 19 | ### 0.4.6 20 | 21 | * Add support for the `type` keyword. 22 | * Add support for underscores in number literals. 23 | 24 | ### 0.4.5 25 | 26 | * Improve TypeScript type definitions. 27 | 28 | ### 0.4.4 29 | 30 | * Add missing `storageLocation` to variables in VariableDeclarationStatement. 31 | * Return `null` for `arguments` instead of `[]` when `ModifierInvocation` 32 | contains no arguments and no parentheses to distinguish the two cases. 33 | * Improve TypeScript type definitions. 34 | 35 | ### 0.4.3 36 | 37 | * Improve TypeScript type definitions, thanks @Leeleo3x and @yxliang01. 38 | 39 | ### 0.4.2 40 | 41 | * Fix parsing of assembly function definitions with no args or return args. 42 | 43 | ### 0.4.1 44 | 45 | * Fix parsing of for loops with missing initial and condition statements. 46 | 47 | ### 0.4.0 48 | 49 | * Correctly handle non-existent tuple components. Thanks @maxsam4 50 | * Accept calldata as identifier 51 | 52 | ### 0.3.3 53 | 54 | * Add support for `address payable` typename. 55 | 56 | ### 0.3.2 57 | 58 | * Fix parsing of hex numbers with uppercase X. 59 | 60 | ### 0.3.1 61 | 62 | * Fix parsing of zero-component tuples. 63 | 64 | ### 0.3.0 65 | 66 | * Use `components` for all `TupleExpression` nodes. Earlier versions 67 | incorrectly stored tuple components under the `elements` key. 68 | * Fix parsing of decimal literals without integer part. 69 | -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017-2018 Federico Bond 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/README.md: -------------------------------------------------------------------------------- 1 | solidity-parser-antlr 2 | ===================== 3 | 4 | [![npm](https://img.shields.io/npm/v/solidity-parser-antlr.svg)](https://www.npmjs.com/package/solidity-parser-antlr) 5 | [![Build Status](https://travis-ci.org/federicobond/solidity-parser-antlr.svg?branch=master)](https://travis-ci.org/federicobond/solidity-parser-antlr) 6 | 7 | A Solidity parser built on top of a robust [ANTLR4 grammar](https://github.com/solidityj/solidity-antlr4). 8 | 9 | ### Usage 10 | 11 | ```javascript 12 | import parser from 'solidity-parser-antlr'; 13 | 14 | var input = ` 15 | contract test { 16 | uint256 a; 17 | function f() {} 18 | } 19 | ` 20 | try { 21 | parser.parse(input) 22 | } catch (e) { 23 | if (e instanceof parser.ParserError) { 24 | console.log(e.errors) 25 | } 26 | } 27 | ``` 28 | 29 | The `parse` method also accepts a second argument which lets you specify the 30 | following options, in a style similar to the _esprima_ API: 31 | 32 | | Key | Type | Default | Description | 33 | |----------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 34 | | tolerant | Boolean | false | When set to `true` it will collect syntax errors and place them in a list under the key `errors` inside the root node of the returned AST. Otherwise, it will raise a `parser.ParserError`. | 35 | | loc | Boolean | false | When set to `true`, it will add location information to each node, with start and stop keys that contain the corresponding line and column numbers. Column numbers start from 0, lines start from 1. | 36 | | range | Boolean | false | When set to `true`, it will add range information to each node, which consists of a two-element array with start and stop character indexes in the input. | 37 | 38 | 39 | #### Example with location information 40 | 41 | ```javascript 42 | parser.parse('contract test { uint a; }', { loc: true }) 43 | 44 | // { type: 'SourceUnit', 45 | // children: 46 | // [ { type: 'ContractDefinition', 47 | // name: 'test', 48 | // baseContracts: [], 49 | // subNodes: [Array], 50 | // kind: 'contract', 51 | // loc: [Object] } ], 52 | // loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 24 } } } 53 | 54 | ``` 55 | 56 | #### Example using a visitor to walk over the AST 57 | 58 | ```javascript 59 | var ast = parser.parse('contract test { uint a; }') 60 | 61 | // output the path of each import found 62 | parser.visit(ast, { 63 | ImportDirective: function(node) { 64 | console.log(node.path) 65 | } 66 | }) 67 | ``` 68 | 69 | ### Author 70 | 71 | Federico Bond ([@federicobond](https://github.com/federicobond)) 72 | 73 | ### License 74 | 75 | MIT 76 | -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/ErrorListener.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var antlr4 = require('./antlr4/index'); 4 | 5 | function ErrorListener() { 6 | antlr4.error.ErrorListener.call(this); 7 | this._errors = []; 8 | } 9 | 10 | ErrorListener.prototype = Object.create(antlr4.error.ErrorListener.prototype); 11 | ErrorListener.prototype.constructor = ErrorListener; 12 | 13 | ErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, message) { 14 | this._errors.push({ message: message, line: line, column: column }); 15 | }; 16 | 17 | ErrorListener.prototype.getErrors = function () { 18 | return this._errors; 19 | }; 20 | 21 | ErrorListener.prototype.hasErrors = function () { 22 | return this._errors.length > 0; 23 | }; 24 | 25 | module.exports = ErrorListener; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/CharStreams.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | var InputStream = require('./InputStream').InputStream; 11 | 12 | var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined'; 13 | var fs = isNodeJs ? require("fs") : null; 14 | 15 | // Utility functions to create InputStreams from various sources. 16 | // 17 | // All returned InputStreams support the full range of Unicode 18 | // up to U+10FFFF (the default behavior of InputStream only supports 19 | // code points up to U+FFFF). 20 | var CharStreams = { 21 | // Creates an InputStream from a string. 22 | fromString: function fromString(str) { 23 | return new InputStream(str, true); 24 | }, 25 | 26 | // Asynchronously creates an InputStream from a blob given the 27 | // encoding of the bytes in that blob (defaults to 'utf8' if 28 | // encoding is null). 29 | // 30 | // Invokes onLoad(result) on success, onError(error) on 31 | // failure. 32 | fromBlob: function fromBlob(blob, encoding, onLoad, onError) { 33 | var reader = FileReader(); 34 | reader.onload = function (e) { 35 | var is = new InputStream(e.target.result, true); 36 | onLoad(is); 37 | }; 38 | reader.onerror = onError; 39 | reader.readAsText(blob, encoding); 40 | }, 41 | 42 | // Creates an InputStream from a Buffer given the 43 | // encoding of the bytes in that buffer (defaults to 'utf8' if 44 | // encoding is null). 45 | fromBuffer: function fromBuffer(buffer, encoding) { 46 | return new InputStream(buffer.toString(encoding), true); 47 | }, 48 | 49 | // Asynchronously creates an InputStream from a file on disk given 50 | // the encoding of the bytes in that file (defaults to 'utf8' if 51 | // encoding is null). 52 | // 53 | // Invokes callback(error, result) on completion. 54 | fromPath: function fromPath(path, encoding, callback) { 55 | fs.readFile(path, encoding, function (err, data) { 56 | var is = null; 57 | if (data !== null) { 58 | is = new InputStream(data, true); 59 | } 60 | callback(err, is); 61 | }); 62 | }, 63 | 64 | // Synchronously creates an InputStream given a path to a file 65 | // on disk and the encoding of the bytes in that file (defaults to 66 | // 'utf8' if encoding is null). 67 | fromPathSync: function fromPathSync(path, encoding) { 68 | var data = fs.readFileSync(path, encoding); 69 | return new InputStream(data, true); 70 | } 71 | }; 72 | 73 | exports.CharStreams = CharStreams; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/CommonTokenFactory.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | // 11 | // This default implementation of {@link TokenFactory} creates 12 | // {@link CommonToken} objects. 13 | // 14 | 15 | var CommonToken = require('./Token').CommonToken; 16 | 17 | function TokenFactory() { 18 | return this; 19 | } 20 | 21 | function CommonTokenFactory(copyText) { 22 | TokenFactory.call(this); 23 | // Indicates whether {@link CommonToken//setText} should be called after 24 | // constructing tokens to explicitly set the text. This is useful for cases 25 | // where the input stream might not be able to provide arbitrary substrings 26 | // of text from the input after the lexer creates a token (e.g. the 27 | // implementation of {@link CharStream//getText} in 28 | // {@link UnbufferedCharStream} throws an 29 | // {@link UnsupportedOperationException}). Explicitly setting the token text 30 | // allows {@link Token//getText} to be called at any time regardless of the 31 | // input stream implementation. 32 | // 33 | //

34 | // The default value is {@code false} to avoid the performance and memory 35 | // overhead of copying text for every token unless explicitly requested.

36 | // 37 | this.copyText = copyText === undefined ? false : copyText; 38 | return this; 39 | } 40 | 41 | CommonTokenFactory.prototype = Object.create(TokenFactory.prototype); 42 | CommonTokenFactory.prototype.constructor = CommonTokenFactory; 43 | 44 | // 45 | // The default {@link CommonTokenFactory} instance. 46 | // 47 | //

48 | // This token factory does not explicitly copy token text when constructing 49 | // tokens.

50 | // 51 | CommonTokenFactory.DEFAULT = new CommonTokenFactory(); 52 | 53 | CommonTokenFactory.prototype.create = function (source, type, text, channel, start, stop, line, column) { 54 | var t = new CommonToken(source, type, channel, start, stop); 55 | t.line = line; 56 | t.column = column; 57 | if (text !== null) { 58 | t.text = text; 59 | } else if (this.copyText && source[1] !== null) { 60 | t.text = source[1].getText(start, stop); 61 | } 62 | return t; 63 | }; 64 | 65 | CommonTokenFactory.prototype.createThin = function (type, text) { 66 | var t = new CommonToken(null, type); 67 | t.text = text; 68 | return t; 69 | }; 70 | 71 | exports.CommonTokenFactory = CommonTokenFactory; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/CommonTokenStream.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | /// 9 | 10 | // 11 | // This class extends {@link BufferedTokenStream} with functionality to filter 12 | // token streams to tokens on a particular channel (tokens where 13 | // {@link Token//getChannel} returns a particular value). 14 | // 15 | //

16 | // This token stream provides access to all tokens by index or when calling 17 | // methods like {@link //getText}. The channel filtering is only used for code 18 | // accessing tokens via the lookahead methods {@link //LA}, {@link //LT}, and 19 | // {@link //LB}.

20 | // 21 | //

22 | // By default, tokens are placed on the default channel 23 | // ({@link Token//DEFAULT_CHANNEL}), but may be reassigned by using the 24 | // {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to 25 | // call {@link Lexer//setChannel}. 26 | //

27 | // 28 | //

29 | // Note: lexer rules which use the {@code ->skip} lexer command or call 30 | // {@link Lexer//skip} do not produce tokens at all, so input text matched by 31 | // such a rule will not be available as part of the token stream, regardless of 32 | // channel.

33 | /// 34 | 35 | var Token = require('./Token').Token; 36 | var BufferedTokenStream = require('./BufferedTokenStream').BufferedTokenStream; 37 | 38 | function CommonTokenStream(lexer, channel) { 39 | BufferedTokenStream.call(this, lexer); 40 | this.channel = channel === undefined ? Token.DEFAULT_CHANNEL : channel; 41 | return this; 42 | } 43 | 44 | CommonTokenStream.prototype = Object.create(BufferedTokenStream.prototype); 45 | CommonTokenStream.prototype.constructor = CommonTokenStream; 46 | 47 | CommonTokenStream.prototype.adjustSeekIndex = function (i) { 48 | return this.nextTokenOnChannel(i, this.channel); 49 | }; 50 | 51 | CommonTokenStream.prototype.LB = function (k) { 52 | if (k === 0 || this.index - k < 0) { 53 | return null; 54 | } 55 | var i = this.index; 56 | var n = 1; 57 | // find k good tokens looking backwards 58 | while (n <= k) { 59 | // skip off-channel tokens 60 | i = this.previousTokenOnChannel(i - 1, this.channel); 61 | n += 1; 62 | } 63 | if (i < 0) { 64 | return null; 65 | } 66 | return this.tokens[i]; 67 | }; 68 | 69 | CommonTokenStream.prototype.LT = function (k) { 70 | this.lazyInit(); 71 | if (k === 0) { 72 | return null; 73 | } 74 | if (k < 0) { 75 | return this.LB(-k); 76 | } 77 | var i = this.index; 78 | var n = 1; // we know tokens[pos] is a good one 79 | // find k good tokens 80 | while (n < k) { 81 | // skip off-channel tokens, but make sure to not look past EOF 82 | if (this.sync(i + 1)) { 83 | i = this.nextTokenOnChannel(i + 1, this.channel); 84 | } 85 | n += 1; 86 | } 87 | return this.tokens[i]; 88 | }; 89 | 90 | // Count EOF just once./// 91 | CommonTokenStream.prototype.getNumberOfOnChannelTokens = function () { 92 | var n = 0; 93 | this.fill(); 94 | for (var i = 0; i < this.tokens.length; i++) { 95 | var t = this.tokens[i]; 96 | if (t.channel === this.channel) { 97 | n += 1; 98 | } 99 | if (t.type === Token.EOF) { 100 | break; 101 | } 102 | } 103 | return n; 104 | }; 105 | 106 | exports.CommonTokenStream = CommonTokenStream; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/FileStream.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | // 11 | // This is an InputStream that is loaded from a file all at once 12 | // when you construct the object. 13 | // 14 | var InputStream = require('./InputStream').InputStream; 15 | var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined'; 16 | var fs = isNodeJs ? require("fs") : null; 17 | 18 | function FileStream(fileName, decodeToUnicodeCodePoints) { 19 | var data = fs.readFileSync(fileName, "utf8"); 20 | InputStream.call(this, data, decodeToUnicodeCodePoints); 21 | this.fileName = fileName; 22 | return this; 23 | } 24 | 25 | FileStream.prototype = Object.create(InputStream.prototype); 26 | FileStream.prototype.constructor = FileStream; 27 | 28 | exports.FileStream = FileStream; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/InputStream.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | var Token = require('./Token').Token; 11 | require('./polyfills/codepointat'); 12 | require('./polyfills/fromcodepoint'); 13 | 14 | // Vacuum all input from a string and then treat it like a buffer. 15 | 16 | function _loadString(stream, decodeToUnicodeCodePoints) { 17 | stream._index = 0; 18 | stream.data = []; 19 | if (stream.decodeToUnicodeCodePoints) { 20 | for (var i = 0; i < stream.strdata.length;) { 21 | var codePoint = stream.strdata.codePointAt(i); 22 | stream.data.push(codePoint); 23 | i += codePoint <= 0xFFFF ? 1 : 2; 24 | } 25 | } else { 26 | for (var i = 0; i < stream.strdata.length; i++) { 27 | var codeUnit = stream.strdata.charCodeAt(i); 28 | stream.data.push(codeUnit); 29 | } 30 | } 31 | stream._size = stream.data.length; 32 | } 33 | 34 | // If decodeToUnicodeCodePoints is true, the input is treated 35 | // as a series of Unicode code points. 36 | // 37 | // Otherwise, the input is treated as a series of 16-bit UTF-16 code 38 | // units. 39 | function InputStream(data, decodeToUnicodeCodePoints) { 40 | this.name = ""; 41 | this.strdata = data; 42 | this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false; 43 | _loadString(this); 44 | return this; 45 | } 46 | 47 | Object.defineProperty(InputStream.prototype, "index", { 48 | get: function get() { 49 | return this._index; 50 | } 51 | }); 52 | 53 | Object.defineProperty(InputStream.prototype, "size", { 54 | get: function get() { 55 | return this._size; 56 | } 57 | }); 58 | 59 | // Reset the stream so that it's in the same state it was 60 | // when the object was created *except* the data array is not 61 | // touched. 62 | // 63 | InputStream.prototype.reset = function () { 64 | this._index = 0; 65 | }; 66 | 67 | InputStream.prototype.consume = function () { 68 | if (this._index >= this._size) { 69 | // assert this.LA(1) == Token.EOF 70 | throw "cannot consume EOF"; 71 | } 72 | this._index += 1; 73 | }; 74 | 75 | InputStream.prototype.LA = function (offset) { 76 | if (offset === 0) { 77 | return 0; // undefined 78 | } 79 | if (offset < 0) { 80 | offset += 1; // e.g., translate LA(-1) to use offset=0 81 | } 82 | var pos = this._index + offset - 1; 83 | if (pos < 0 || pos >= this._size) { 84 | // invalid 85 | return Token.EOF; 86 | } 87 | return this.data[pos]; 88 | }; 89 | 90 | InputStream.prototype.LT = function (offset) { 91 | return this.LA(offset); 92 | }; 93 | 94 | // mark/release do nothing; we have entire buffer 95 | InputStream.prototype.mark = function () { 96 | return -1; 97 | }; 98 | 99 | InputStream.prototype.release = function (marker) {}; 100 | 101 | // consume() ahead until p==_index; can't just set p=_index as we must 102 | // update line and column. If we seek backwards, just set p 103 | // 104 | InputStream.prototype.seek = function (_index) { 105 | if (_index <= this._index) { 106 | this._index = _index; // just jump; don't update stream state (line, 107 | // ...) 108 | return; 109 | } 110 | // seek forward 111 | this._index = Math.min(_index, this._size); 112 | }; 113 | 114 | InputStream.prototype.getText = function (start, stop) { 115 | if (stop >= this._size) { 116 | stop = this._size - 1; 117 | } 118 | if (start >= this._size) { 119 | return ""; 120 | } else { 121 | if (this.decodeToUnicodeCodePoints) { 122 | var result = ""; 123 | for (var i = start; i <= stop; i++) { 124 | result += String.fromCodePoint(this.data[i]); 125 | } 126 | return result; 127 | } else { 128 | return this.strdata.slice(start, stop + 1); 129 | } 130 | } 131 | }; 132 | 133 | InputStream.prototype.toString = function () { 134 | return this.strdata; 135 | }; 136 | 137 | exports.InputStream = InputStream; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/Recognizer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | var Token = require('./Token').Token; 11 | var ConsoleErrorListener = require('./error/ErrorListener').ConsoleErrorListener; 12 | var ProxyErrorListener = require('./error/ErrorListener').ProxyErrorListener; 13 | 14 | function Recognizer() { 15 | this._listeners = [ConsoleErrorListener.INSTANCE]; 16 | this._interp = null; 17 | this._stateNumber = -1; 18 | return this; 19 | } 20 | 21 | Recognizer.tokenTypeMapCache = {}; 22 | Recognizer.ruleIndexMapCache = {}; 23 | 24 | Recognizer.prototype.checkVersion = function (toolVersion) { 25 | var runtimeVersion = "4.7"; 26 | if (runtimeVersion !== toolVersion) { 27 | console.log("ANTLR runtime and generated code versions disagree: " + runtimeVersion + "!=" + toolVersion); 28 | } 29 | }; 30 | 31 | Recognizer.prototype.addErrorListener = function (listener) { 32 | this._listeners.push(listener); 33 | }; 34 | 35 | Recognizer.prototype.removeErrorListeners = function () { 36 | this._listeners = []; 37 | }; 38 | 39 | Recognizer.prototype.getTokenTypeMap = function () { 40 | var tokenNames = this.getTokenNames(); 41 | if (tokenNames === null) { 42 | throw "The current recognizer does not provide a list of token names."; 43 | } 44 | var result = this.tokenTypeMapCache[tokenNames]; 45 | if (result === undefined) { 46 | result = tokenNames.reduce(function (o, k, i) { 47 | o[k] = i; 48 | }); 49 | result.EOF = Token.EOF; 50 | this.tokenTypeMapCache[tokenNames] = result; 51 | } 52 | return result; 53 | }; 54 | 55 | // Get a map from rule names to rule indexes. 56 | // 57 | //

Used for XPath and tree pattern compilation.

58 | // 59 | Recognizer.prototype.getRuleIndexMap = function () { 60 | var ruleNames = this.ruleNames; 61 | if (ruleNames === null) { 62 | throw "The current recognizer does not provide a list of rule names."; 63 | } 64 | var result = this.ruleIndexMapCache[ruleNames]; 65 | if (result === undefined) { 66 | result = ruleNames.reduce(function (o, k, i) { 67 | o[k] = i; 68 | }); 69 | this.ruleIndexMapCache[ruleNames] = result; 70 | } 71 | return result; 72 | }; 73 | 74 | Recognizer.prototype.getTokenType = function (tokenName) { 75 | var ttype = this.getTokenTypeMap()[tokenName]; 76 | if (ttype !== undefined) { 77 | return ttype; 78 | } else { 79 | return Token.INVALID_TYPE; 80 | } 81 | }; 82 | 83 | // What is the error header, normally line/character position information?// 84 | Recognizer.prototype.getErrorHeader = function (e) { 85 | var line = e.getOffendingToken().line; 86 | var column = e.getOffendingToken().column; 87 | return "line " + line + ":" + column; 88 | }; 89 | 90 | // How should a token be displayed in an error message? The default 91 | // is to display just the text, but during development you might 92 | // want to have a lot of information spit out. Override in that case 93 | // to use t.toString() (which, for CommonToken, dumps everything about 94 | // the token). This is better than forcing you to override a method in 95 | // your token objects because you don't have to go modify your lexer 96 | // so that it creates a new Java type. 97 | // 98 | // @deprecated This method is not called by the ANTLR 4 Runtime. Specific 99 | // implementations of {@link ANTLRErrorStrategy} may provide a similar 100 | // feature when necessary. For example, see 101 | // {@link DefaultErrorStrategy//getTokenErrorDisplay}. 102 | // 103 | Recognizer.prototype.getTokenErrorDisplay = function (t) { 104 | if (t === null) { 105 | return ""; 106 | } 107 | var s = t.text; 108 | if (s === null) { 109 | if (t.type === Token.EOF) { 110 | s = ""; 111 | } else { 112 | s = "<" + t.type + ">"; 113 | } 114 | } 115 | s = s.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t"); 116 | return "'" + s + "'"; 117 | }; 118 | 119 | Recognizer.prototype.getErrorListenerDispatch = function () { 120 | return new ProxyErrorListener(this._listeners); 121 | }; 122 | 123 | // subclass needs to override these if there are sempreds or actions 124 | // that the ATN interp needs to execute 125 | Recognizer.prototype.sempred = function (localctx, ruleIndex, actionIndex) { 126 | return true; 127 | }; 128 | 129 | Recognizer.prototype.precpred = function (localctx, precedence) { 130 | return true; 131 | }; 132 | 133 | //Indicate that the recognizer has changed internal state that is 134 | //consistent with the ATN state passed in. This way we always know 135 | //where we are in the ATN as the parser goes along. The rule 136 | //context objects form a stack that lets us see the stack of 137 | //invoking rules. Combine this and we have complete ATN 138 | //configuration information. 139 | 140 | Object.defineProperty(Recognizer.prototype, "state", { 141 | get: function get() { 142 | return this._stateNumber; 143 | }, 144 | set: function set(state) { 145 | this._stateNumber = state; 146 | } 147 | }); 148 | 149 | exports.Recognizer = Recognizer; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/RuleContext.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | /// 8 | 9 | // A rule context is a record of a single rule invocation. It knows 10 | // which context invoked it, if any. If there is no parent context, then 11 | // naturally the invoking state is not valid. The parent link 12 | // provides a chain upwards from the current rule invocation to the root 13 | // of the invocation tree, forming a stack. We actually carry no 14 | // information about the rule associated with this context (except 15 | // when parsing). We keep only the state number of the invoking state from 16 | // the ATN submachine that invoked this. Contrast this with the s 17 | // pointer inside ParserRuleContext that tracks the current state 18 | // being "executed" for the current rule. 19 | // 20 | // The parent contexts are useful for computing lookahead sets and 21 | // getting error information. 22 | // 23 | // These objects are used during parsing and prediction. 24 | // For the special case of parsers, we use the subclass 25 | // ParserRuleContext. 26 | // 27 | // @see ParserRuleContext 28 | /// 29 | 30 | var RuleNode = require('./tree/Tree').RuleNode; 31 | var INVALID_INTERVAL = require('./tree/Tree').INVALID_INTERVAL; 32 | var INVALID_ALT_NUMBER = require('./atn/ATN').INVALID_ALT_NUMBER; 33 | 34 | function RuleContext(parent, invokingState) { 35 | RuleNode.call(this); 36 | // What context invoked this rule? 37 | this.parentCtx = parent || null; 38 | // What state invoked the rule associated with this context? 39 | // The "return address" is the followState of invokingState 40 | // If parent is null, this should be -1. 41 | this.invokingState = invokingState || -1; 42 | return this; 43 | } 44 | 45 | RuleContext.prototype = Object.create(RuleNode.prototype); 46 | RuleContext.prototype.constructor = RuleContext; 47 | 48 | RuleContext.prototype.depth = function () { 49 | var n = 0; 50 | var p = this; 51 | while (p !== null) { 52 | p = p.parentCtx; 53 | n += 1; 54 | } 55 | return n; 56 | }; 57 | 58 | // A context is empty if there is no invoking state; meaning nobody call 59 | // current context. 60 | RuleContext.prototype.isEmpty = function () { 61 | return this.invokingState === -1; 62 | }; 63 | 64 | // satisfy the ParseTree / SyntaxTree interface 65 | 66 | RuleContext.prototype.getSourceInterval = function () { 67 | return INVALID_INTERVAL; 68 | }; 69 | 70 | RuleContext.prototype.getRuleContext = function () { 71 | return this; 72 | }; 73 | 74 | RuleContext.prototype.getPayload = function () { 75 | return this; 76 | }; 77 | 78 | // Return the combined text of all child nodes. This method only considers 79 | // tokens which have been added to the parse tree. 80 | //

81 | // Since tokens on hidden channels (e.g. whitespace or comments) are not 82 | // added to the parse trees, they will not appear in the output of this 83 | // method. 84 | // / 85 | RuleContext.prototype.getText = function () { 86 | if (this.getChildCount() === 0) { 87 | return ""; 88 | } else { 89 | return this.children.map(function (child) { 90 | return child.getText(); 91 | }).join(""); 92 | } 93 | }; 94 | 95 | // For rule associated with this parse tree internal node, return 96 | // the outer alternative number used to match the input. Default 97 | // implementation does not compute nor store this alt num. Create 98 | // a subclass of ParserRuleContext with backing field and set 99 | // option contextSuperClass. 100 | // to set it. 101 | RuleContext.prototype.getAltNumber = function () { 102 | return INVALID_ALT_NUMBER; 103 | }; 104 | 105 | // Set the outer alternative number for this context node. Default 106 | // implementation does nothing to avoid backing field overhead for 107 | // trees that don't need it. Create 108 | // a subclass of ParserRuleContext with backing field and set 109 | // option contextSuperClass. 110 | RuleContext.prototype.setAltNumber = function (altNumber) {}; 111 | 112 | RuleContext.prototype.getChild = function (i) { 113 | return null; 114 | }; 115 | 116 | RuleContext.prototype.getChildCount = function () { 117 | return 0; 118 | }; 119 | 120 | RuleContext.prototype.accept = function (visitor) { 121 | return visitor.visitChildren(this); 122 | }; 123 | 124 | //need to manage circular dependencies, so export now 125 | exports.RuleContext = RuleContext; 126 | var Trees = require('./tree/Trees').Trees; 127 | 128 | // Print out a whole tree, not just a node, in LISP format 129 | // (root child1 .. childN). Print just a node if this is a leaf. 130 | // 131 | 132 | RuleContext.prototype.toStringTree = function (ruleNames, recog) { 133 | return Trees.toStringTree(this, ruleNames, recog); 134 | }; 135 | 136 | RuleContext.prototype.toString = function (ruleNames, stop) { 137 | ruleNames = ruleNames || null; 138 | stop = stop || null; 139 | var p = this; 140 | var s = "["; 141 | while (p !== null && p !== stop) { 142 | if (ruleNames === null) { 143 | if (!p.isEmpty()) { 144 | s += p.invokingState; 145 | } 146 | } else { 147 | var ri = p.ruleIndex; 148 | var ruleName = ri >= 0 && ri < ruleNames.length ? ruleNames[ri] : "" + ri; 149 | s += ruleName; 150 | } 151 | if (p.parentCtx !== null && (ruleNames !== null || !p.parentCtx.isEmpty())) { 152 | s += " "; 153 | } 154 | p = p.parentCtx; 155 | } 156 | s += "]"; 157 | return s; 158 | }; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/Token.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | // 8 | 9 | // A token has properties: text, type, line, character position in the line 10 | // (so we can ignore tabs), token channel, index, and source from which 11 | // we obtained this token. 12 | 13 | function Token() { 14 | this.source = null; 15 | this.type = null; // token type of the token 16 | this.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL 17 | this.start = null; // optional; return -1 if not implemented. 18 | this.stop = null; // optional; return -1 if not implemented. 19 | this.tokenIndex = null; // from 0..n-1 of the token object in the input stream 20 | this.line = null; // line=1..n of the 1st character 21 | this.column = null; // beginning of the line at which it occurs, 0..n-1 22 | this._text = null; // text of the token. 23 | return this; 24 | } 25 | 26 | Token.INVALID_TYPE = 0; 27 | 28 | // During lookahead operations, this "token" signifies we hit rule end ATN state 29 | // and did not follow it despite needing to. 30 | Token.EPSILON = -2; 31 | 32 | Token.MIN_USER_TOKEN_TYPE = 1; 33 | 34 | Token.EOF = -1; 35 | 36 | // All tokens go to the parser (unless skip() is called in that rule) 37 | // on a particular "channel". The parser tunes to a particular channel 38 | // so that whitespace etc... can go to the parser on a "hidden" channel. 39 | 40 | Token.DEFAULT_CHANNEL = 0; 41 | 42 | // Anything on different channel than DEFAULT_CHANNEL is not parsed 43 | // by parser. 44 | 45 | Token.HIDDEN_CHANNEL = 1; 46 | 47 | // Explicitly set the text for this token. If {code text} is not 48 | // {@code null}, then {@link //getText} will return this value rather than 49 | // extracting the text from the input. 50 | // 51 | // @param text The explicit text of the token, or {@code null} if the text 52 | // should be obtained from the input along with the start and stop indexes 53 | // of the token. 54 | 55 | Object.defineProperty(Token.prototype, "text", { 56 | get: function get() { 57 | return this._text; 58 | }, 59 | set: function set(text) { 60 | this._text = text; 61 | } 62 | }); 63 | 64 | Token.prototype.getTokenSource = function () { 65 | return this.source[0]; 66 | }; 67 | 68 | Token.prototype.getInputStream = function () { 69 | return this.source[1]; 70 | }; 71 | 72 | function CommonToken(source, type, channel, start, stop) { 73 | Token.call(this); 74 | this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE; 75 | this.type = type !== undefined ? type : null; 76 | this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL; 77 | this.start = start !== undefined ? start : -1; 78 | this.stop = stop !== undefined ? stop : -1; 79 | this.tokenIndex = -1; 80 | if (this.source[0] !== null) { 81 | this.line = source[0].line; 82 | this.column = source[0].column; 83 | } else { 84 | this.column = -1; 85 | } 86 | return this; 87 | } 88 | 89 | CommonToken.prototype = Object.create(Token.prototype); 90 | CommonToken.prototype.constructor = CommonToken; 91 | 92 | // An empty {@link Pair} which is used as the default value of 93 | // {@link //source} for tokens that do not have a source. 94 | CommonToken.EMPTY_SOURCE = [null, null]; 95 | 96 | // Constructs a new {@link CommonToken} as a copy of another {@link Token}. 97 | // 98 | //

99 | // If {@code oldToken} is also a {@link CommonToken} instance, the newly 100 | // constructed token will share a reference to the {@link //text} field and 101 | // the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will 102 | // be assigned the result of calling {@link //getText}, and {@link //source} 103 | // will be constructed from the result of {@link Token//getTokenSource} and 104 | // {@link Token//getInputStream}.

105 | // 106 | // @param oldToken The token to copy. 107 | // 108 | CommonToken.prototype.clone = function () { 109 | var t = new CommonToken(this.source, this.type, this.channel, this.start, this.stop); 110 | t.tokenIndex = this.tokenIndex; 111 | t.line = this.line; 112 | t.column = this.column; 113 | t.text = this.text; 114 | return t; 115 | }; 116 | 117 | Object.defineProperty(CommonToken.prototype, "text", { 118 | get: function get() { 119 | if (this._text !== null) { 120 | return this._text; 121 | } 122 | var input = this.getInputStream(); 123 | if (input === null) { 124 | return null; 125 | } 126 | var n = input.size; 127 | if (this.start < n && this.stop < n) { 128 | return input.getText(this.start, this.stop); 129 | } else { 130 | return ""; 131 | } 132 | }, 133 | set: function set(text) { 134 | this._text = text; 135 | } 136 | }); 137 | 138 | CommonToken.prototype.toString = function () { 139 | var txt = this.text; 140 | if (txt !== null) { 141 | txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); 142 | } else { 143 | txt = ""; 144 | } 145 | return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" + txt + "',<" + this.type + ">" + (this.channel > 0 ? ",channel=" + this.channel : "") + "," + this.line + ":" + this.column + "]"; 146 | }; 147 | 148 | exports.Token = Token; 149 | exports.CommonToken = CommonToken; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/atn/ATNDeserializationOptions.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | function ATNDeserializationOptions(copyFrom) { 9 | if (copyFrom === undefined) { 10 | copyFrom = null; 11 | } 12 | this.readOnly = false; 13 | this.verifyATN = copyFrom === null ? true : copyFrom.verifyATN; 14 | this.generateRuleBypassTransitions = copyFrom === null ? false : copyFrom.generateRuleBypassTransitions; 15 | 16 | return this; 17 | } 18 | 19 | ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions(); 20 | ATNDeserializationOptions.defaultOptions.readOnly = true; 21 | 22 | // def __setattr__(self, key, value): 23 | // if key!="readOnly" and self.readOnly: 24 | // raise Exception("The object is read only.") 25 | // super(type(self), self).__setattr__(key,value) 26 | 27 | exports.ATNDeserializationOptions = ATNDeserializationOptions; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/atn/ATNSimulator.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | /// 9 | 10 | var DFAState = require('./../dfa/DFAState').DFAState; 11 | var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet; 12 | var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext; 13 | 14 | function ATNSimulator(atn, sharedContextCache) { 15 | 16 | // The context cache maps all PredictionContext objects that are == 17 | // to a single cached copy. This cache is shared across all contexts 18 | // in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet 19 | // to use only cached nodes/graphs in addDFAState(). We don't want to 20 | // fill this during closure() since there are lots of contexts that 21 | // pop up but are not used ever again. It also greatly slows down closure(). 22 | // 23 | //

This cache makes a huge difference in memory and a little bit in speed. 24 | // For the Java grammar on java.*, it dropped the memory requirements 25 | // at the end from 25M to 16M. We don't store any of the full context 26 | // graphs in the DFA because they are limited to local context only, 27 | // but apparently there's a lot of repetition there as well. We optimize 28 | // the config contexts before storing the config set in the DFA states 29 | // by literally rebuilding them with cached subgraphs only.

30 | // 31 | //

I tried a cache for use during closure operations, that was 32 | // whacked after each adaptivePredict(). It cost a little bit 33 | // more time I think and doesn't save on the overall footprint 34 | // so it's not worth the complexity.

35 | /// 36 | this.atn = atn; 37 | this.sharedContextCache = sharedContextCache; 38 | return this; 39 | } 40 | 41 | // Must distinguish between missing edge and edge we know leads nowhere/// 42 | ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet()); 43 | 44 | ATNSimulator.prototype.getCachedContext = function (context) { 45 | if (this.sharedContextCache === null) { 46 | return context; 47 | } 48 | var visited = {}; 49 | return getCachedPredictionContext(context, this.sharedContextCache, visited); 50 | }; 51 | 52 | exports.ATNSimulator = ATNSimulator; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/atn/ATNType.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | /// 8 | 9 | // Represents the type of recognizer an ATN applies to. 10 | 11 | function ATNType() {} 12 | 13 | ATNType.LEXER = 0; 14 | ATNType.PARSER = 1; 15 | 16 | exports.ATNType = ATNType; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/atn/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | exports.ATN = require('./ATN').ATN; 9 | exports.ATNDeserializer = require('./ATNDeserializer').ATNDeserializer; 10 | exports.LexerATNSimulator = require('./LexerATNSimulator').LexerATNSimulator; 11 | exports.ParserATNSimulator = require('./ParserATNSimulator').ParserATNSimulator; 12 | exports.PredictionMode = require('./PredictionMode').PredictionMode; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/dfa/DFA.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | 9 | var Set = require("../Utils").Set; 10 | var DFAState = require('./DFAState').DFAState; 11 | var StarLoopEntryState = require('../atn/ATNState').StarLoopEntryState; 12 | var ATNConfigSet = require('./../atn/ATNConfigSet').ATNConfigSet; 13 | var DFASerializer = require('./DFASerializer').DFASerializer; 14 | var LexerDFASerializer = require('./DFASerializer').LexerDFASerializer; 15 | 16 | function DFA(atnStartState, decision) { 17 | if (decision === undefined) { 18 | decision = 0; 19 | } 20 | // From which ATN state did we create this DFA? 21 | this.atnStartState = atnStartState; 22 | this.decision = decision; 23 | // A set of all DFA states. Use {@link Map} so we can get old state back 24 | // ({@link Set} only allows you to see if it's there). 25 | this._states = new Set(); 26 | this.s0 = null; 27 | // {@code true} if this DFA is for a precedence decision; otherwise, 28 | // {@code false}. This is the backing field for {@link //isPrecedenceDfa}, 29 | // {@link //setPrecedenceDfa}. 30 | this.precedenceDfa = false; 31 | if (atnStartState instanceof StarLoopEntryState) { 32 | if (atnStartState.isPrecedenceDecision) { 33 | this.precedenceDfa = true; 34 | var precedenceState = new DFAState(null, new ATNConfigSet()); 35 | precedenceState.edges = []; 36 | precedenceState.isAcceptState = false; 37 | precedenceState.requiresFullContext = false; 38 | this.s0 = precedenceState; 39 | } 40 | } 41 | return this; 42 | } 43 | 44 | // Get the start state for a specific precedence value. 45 | // 46 | // @param precedence The current precedence. 47 | // @return The start state corresponding to the specified precedence, or 48 | // {@code null} if no start state exists for the specified precedence. 49 | // 50 | // @throws IllegalStateException if this is not a precedence DFA. 51 | // @see //isPrecedenceDfa() 52 | 53 | DFA.prototype.getPrecedenceStartState = function (precedence) { 54 | if (!this.precedenceDfa) { 55 | throw "Only precedence DFAs may contain a precedence start state."; 56 | } 57 | // s0.edges is never null for a precedence DFA 58 | if (precedence < 0 || precedence >= this.s0.edges.length) { 59 | return null; 60 | } 61 | return this.s0.edges[precedence] || null; 62 | }; 63 | 64 | // Set the start state for a specific precedence value. 65 | // 66 | // @param precedence The current precedence. 67 | // @param startState The start state corresponding to the specified 68 | // precedence. 69 | // 70 | // @throws IllegalStateException if this is not a precedence DFA. 71 | // @see //isPrecedenceDfa() 72 | // 73 | DFA.prototype.setPrecedenceStartState = function (precedence, startState) { 74 | if (!this.precedenceDfa) { 75 | throw "Only precedence DFAs may contain a precedence start state."; 76 | } 77 | if (precedence < 0) { 78 | return; 79 | } 80 | 81 | // synchronization on s0 here is ok. when the DFA is turned into a 82 | // precedence DFA, s0 will be initialized once and not updated again 83 | // s0.edges is never null for a precedence DFA 84 | this.s0.edges[precedence] = startState; 85 | }; 86 | 87 | // 88 | // Sets whether this is a precedence DFA. If the specified value differs 89 | // from the current DFA configuration, the following actions are taken; 90 | // otherwise no changes are made to the current DFA. 91 | // 92 | //
    93 | //
  • The {@link //states} map is cleared
  • 94 | //
  • If {@code precedenceDfa} is {@code false}, the initial state 95 | // {@link //s0} is set to {@code null}; otherwise, it is initialized to a new 96 | // {@link DFAState} with an empty outgoing {@link DFAState//edges} array to 97 | // store the start states for individual precedence values.
  • 98 | //
  • The {@link //precedenceDfa} field is updated
  • 99 | //
100 | // 101 | // @param precedenceDfa {@code true} if this is a precedence DFA; otherwise, 102 | // {@code false} 103 | 104 | DFA.prototype.setPrecedenceDfa = function (precedenceDfa) { 105 | if (this.precedenceDfa !== precedenceDfa) { 106 | this._states = new DFAStatesSet(); 107 | if (precedenceDfa) { 108 | var precedenceState = new DFAState(null, new ATNConfigSet()); 109 | precedenceState.edges = []; 110 | precedenceState.isAcceptState = false; 111 | precedenceState.requiresFullContext = false; 112 | this.s0 = precedenceState; 113 | } else { 114 | this.s0 = null; 115 | } 116 | this.precedenceDfa = precedenceDfa; 117 | } 118 | }; 119 | 120 | Object.defineProperty(DFA.prototype, "states", { 121 | get: function get() { 122 | return this._states; 123 | } 124 | }); 125 | 126 | // Return a list of all states in this DFA, ordered by state number. 127 | DFA.prototype.sortedStates = function () { 128 | var list = this._states.values(); 129 | return list.sort(function (a, b) { 130 | return a.stateNumber - b.stateNumber; 131 | }); 132 | }; 133 | 134 | DFA.prototype.toString = function (literalNames, symbolicNames) { 135 | literalNames = literalNames || null; 136 | symbolicNames = symbolicNames || null; 137 | if (this.s0 === null) { 138 | return ""; 139 | } 140 | var serializer = new DFASerializer(this, literalNames, symbolicNames); 141 | return serializer.toString(); 142 | }; 143 | 144 | DFA.prototype.toLexerString = function () { 145 | if (this.s0 === null) { 146 | return ""; 147 | } 148 | var serializer = new LexerDFASerializer(this); 149 | return serializer.toString(); 150 | }; 151 | 152 | exports.DFA = DFA; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/dfa/DFASerializer.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | // A DFA walker that knows how to dump them to serialized strings.#/ 9 | 10 | 11 | function DFASerializer(dfa, literalNames, symbolicNames) { 12 | this.dfa = dfa; 13 | this.literalNames = literalNames || []; 14 | this.symbolicNames = symbolicNames || []; 15 | return this; 16 | } 17 | 18 | DFASerializer.prototype.toString = function () { 19 | if (this.dfa.s0 === null) { 20 | return null; 21 | } 22 | var buf = ""; 23 | var states = this.dfa.sortedStates(); 24 | for (var i = 0; i < states.length; i++) { 25 | var s = states[i]; 26 | if (s.edges !== null) { 27 | var n = s.edges.length; 28 | for (var j = 0; j < n; j++) { 29 | var t = s.edges[j] || null; 30 | if (t !== null && t.stateNumber !== 0x7FFFFFFF) { 31 | buf = buf.concat(this.getStateString(s)); 32 | buf = buf.concat("-"); 33 | buf = buf.concat(this.getEdgeLabel(j)); 34 | buf = buf.concat("->"); 35 | buf = buf.concat(this.getStateString(t)); 36 | buf = buf.concat('\n'); 37 | } 38 | } 39 | } 40 | } 41 | return buf.length === 0 ? null : buf; 42 | }; 43 | 44 | DFASerializer.prototype.getEdgeLabel = function (i) { 45 | if (i === 0) { 46 | return "EOF"; 47 | } else if (this.literalNames !== null || this.symbolicNames !== null) { 48 | return this.literalNames[i - 1] || this.symbolicNames[i - 1]; 49 | } else { 50 | return String.fromCharCode(i - 1); 51 | } 52 | }; 53 | 54 | DFASerializer.prototype.getStateString = function (s) { 55 | var baseStateStr = (s.isAcceptState ? ":" : "") + "s" + s.stateNumber + (s.requiresFullContext ? "^" : ""); 56 | if (s.isAcceptState) { 57 | if (s.predicates !== null) { 58 | return baseStateStr + "=>" + s.predicates.toString(); 59 | } else { 60 | return baseStateStr + "=>" + s.prediction.toString(); 61 | } 62 | } else { 63 | return baseStateStr; 64 | } 65 | }; 66 | 67 | function LexerDFASerializer(dfa) { 68 | DFASerializer.call(this, dfa, null); 69 | return this; 70 | } 71 | 72 | LexerDFASerializer.prototype = Object.create(DFASerializer.prototype); 73 | LexerDFASerializer.prototype.constructor = LexerDFASerializer; 74 | 75 | LexerDFASerializer.prototype.getEdgeLabel = function (i) { 76 | return "'" + String.fromCharCode(i) + "'"; 77 | }; 78 | 79 | exports.DFASerializer = DFASerializer; 80 | exports.LexerDFASerializer = LexerDFASerializer; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/dfa/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | exports.DFA = require('./DFA').DFA; 9 | exports.DFASerializer = require('./DFASerializer').DFASerializer; 10 | exports.LexerDFASerializer = require('./DFASerializer').LexerDFASerializer; 11 | exports.PredPrediction = require('./DFAState').PredPrediction; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/error/DiagnosticErrorListener.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | // 9 | 10 | // 11 | // This implementation of {@link ANTLRErrorListener} can be used to identify 12 | // certain potential correctness and performance problems in grammars. "Reports" 13 | // are made by calling {@link Parser//notifyErrorListeners} with the appropriate 14 | // message. 15 | // 16 | //
    17 | //
  • Ambiguities: These are cases where more than one path through the 18 | // grammar can match the input.
  • 19 | //
  • Weak context sensitivity: These are cases where full-context 20 | // prediction resolved an SLL conflict to a unique alternative which equaled the 21 | // minimum alternative of the SLL conflict.
  • 22 | //
  • Strong (forced) context sensitivity: These are cases where the 23 | // full-context prediction resolved an SLL conflict to a unique alternative, 24 | // and the minimum alternative of the SLL conflict was found to not be 25 | // a truly viable alternative. Two-stage parsing cannot be used for inputs where 26 | // this situation occurs.
  • 27 | //
28 | 29 | var BitSet = require('./../Utils').BitSet; 30 | var ErrorListener = require('./ErrorListener').ErrorListener; 31 | var Interval = require('./../IntervalSet').Interval; 32 | 33 | function DiagnosticErrorListener(exactOnly) { 34 | ErrorListener.call(this); 35 | exactOnly = exactOnly || true; 36 | // whether all ambiguities or only exact ambiguities are reported. 37 | this.exactOnly = exactOnly; 38 | return this; 39 | } 40 | 41 | DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype); 42 | DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener; 43 | 44 | DiagnosticErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) { 45 | if (this.exactOnly && !exact) { 46 | return; 47 | } 48 | var msg = "reportAmbiguity d=" + this.getDecisionDescription(recognizer, dfa) + ": ambigAlts=" + this.getConflictingAlts(ambigAlts, configs) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'"; 49 | recognizer.notifyErrorListeners(msg); 50 | }; 51 | 52 | DiagnosticErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) { 53 | var msg = "reportAttemptingFullContext d=" + this.getDecisionDescription(recognizer, dfa) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'"; 54 | recognizer.notifyErrorListeners(msg); 55 | }; 56 | 57 | DiagnosticErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) { 58 | var msg = "reportContextSensitivity d=" + this.getDecisionDescription(recognizer, dfa) + ", input='" + recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'"; 59 | recognizer.notifyErrorListeners(msg); 60 | }; 61 | 62 | DiagnosticErrorListener.prototype.getDecisionDescription = function (recognizer, dfa) { 63 | var decision = dfa.decision; 64 | var ruleIndex = dfa.atnStartState.ruleIndex; 65 | 66 | var ruleNames = recognizer.ruleNames; 67 | if (ruleIndex < 0 || ruleIndex >= ruleNames.length) { 68 | return "" + decision; 69 | } 70 | var ruleName = ruleNames[ruleIndex] || null; 71 | if (ruleName === null || ruleName.length === 0) { 72 | return "" + decision; 73 | } 74 | return "" + decision + " (" + ruleName + ")"; 75 | }; 76 | 77 | // 78 | // Computes the set of conflicting or ambiguous alternatives from a 79 | // configuration set, if that information was not already provided by the 80 | // parser. 81 | // 82 | // @param reportedAlts The set of conflicting or ambiguous alternatives, as 83 | // reported by the parser. 84 | // @param configs The conflicting or ambiguous configuration set. 85 | // @return Returns {@code reportedAlts} if it is not {@code null}, otherwise 86 | // returns the set of alternatives represented in {@code configs}. 87 | // 88 | DiagnosticErrorListener.prototype.getConflictingAlts = function (reportedAlts, configs) { 89 | if (reportedAlts !== null) { 90 | return reportedAlts; 91 | } 92 | var result = new BitSet(); 93 | for (var i = 0; i < configs.items.length; i++) { 94 | result.add(configs.items[i].alt); 95 | } 96 | return "{" + result.values().join(", ") + "}"; 97 | }; 98 | 99 | exports.DiagnosticErrorListener = DiagnosticErrorListener; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/error/ErrorListener.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | // 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 5 | * Use of this file is governed by the BSD 3-clause license that 6 | * can be found in the LICENSE.txt file in the project root. 7 | */ 8 | 9 | // Provides an empty default implementation of {@link ANTLRErrorListener}. The 10 | // default implementation of each method does nothing, but can be overridden as 11 | // necessary. 12 | 13 | function ErrorListener() { 14 | return this; 15 | } 16 | 17 | ErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) {}; 18 | 19 | ErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {}; 20 | 21 | ErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {}; 22 | 23 | ErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) {}; 24 | 25 | function ConsoleErrorListener() { 26 | ErrorListener.call(this); 27 | return this; 28 | } 29 | 30 | ConsoleErrorListener.prototype = Object.create(ErrorListener.prototype); 31 | ConsoleErrorListener.prototype.constructor = ConsoleErrorListener; 32 | 33 | // 34 | // Provides a default instance of {@link ConsoleErrorListener}. 35 | // 36 | ConsoleErrorListener.INSTANCE = new ConsoleErrorListener(); 37 | 38 | // 39 | // {@inheritDoc} 40 | // 41 | //

42 | // This implementation prints messages to {@link System//err} containing the 43 | // values of {@code line}, {@code charPositionInLine}, and {@code msg} using 44 | // the following format.

45 | // 46 | //
47 | // line line:charPositionInLine msg
48 | // 
49 | // 50 | ConsoleErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) { 51 | console.error("line " + line + ":" + column + " " + msg); 52 | }; 53 | 54 | function ProxyErrorListener(delegates) { 55 | ErrorListener.call(this); 56 | if (delegates === null) { 57 | throw "delegates"; 58 | } 59 | this.delegates = delegates; 60 | return this; 61 | } 62 | 63 | ProxyErrorListener.prototype = Object.create(ErrorListener.prototype); 64 | ProxyErrorListener.prototype.constructor = ProxyErrorListener; 65 | 66 | ProxyErrorListener.prototype.syntaxError = function (recognizer, offendingSymbol, line, column, msg, e) { 67 | this.delegates.map(function (d) { 68 | d.syntaxError(recognizer, offendingSymbol, line, column, msg, e); 69 | }); 70 | }; 71 | 72 | ProxyErrorListener.prototype.reportAmbiguity = function (recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) { 73 | this.delegates.map(function (d) { 74 | d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs); 75 | }); 76 | }; 77 | 78 | ProxyErrorListener.prototype.reportAttemptingFullContext = function (recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) { 79 | this.delegates.map(function (d) { 80 | d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs); 81 | }); 82 | }; 83 | 84 | ProxyErrorListener.prototype.reportContextSensitivity = function (recognizer, dfa, startIndex, stopIndex, prediction, configs) { 85 | this.delegates.map(function (d) { 86 | d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs); 87 | }); 88 | }; 89 | 90 | exports.ErrorListener = ErrorListener; 91 | exports.ConsoleErrorListener = ConsoleErrorListener; 92 | exports.ProxyErrorListener = ProxyErrorListener; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/error/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | exports.RecognitionException = require('./Errors').RecognitionException; 9 | exports.NoViableAltException = require('./Errors').NoViableAltException; 10 | exports.LexerNoViableAltException = require('./Errors').LexerNoViableAltException; 11 | exports.InputMismatchException = require('./Errors').InputMismatchException; 12 | exports.FailedPredicateException = require('./Errors').FailedPredicateException; 13 | exports.DiagnosticErrorListener = require('./DiagnosticErrorListener').DiagnosticErrorListener; 14 | exports.BailErrorStrategy = require('./ErrorStrategy').BailErrorStrategy; 15 | exports.ErrorListener = require('./ErrorListener').ErrorListener; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | exports.atn = require('./atn/index'); 8 | exports.codepointat = require('./polyfills/codepointat'); 9 | exports.dfa = require('./dfa/index'); 10 | exports.fromcodepoint = require('./polyfills/fromcodepoint'); 11 | exports.tree = require('./tree/index'); 12 | exports.error = require('./error/index'); 13 | exports.Token = require('./Token').Token; 14 | exports.CharStreams = require('./CharStreams').CharStreams; 15 | exports.CommonToken = require('./Token').CommonToken; 16 | exports.InputStream = require('./InputStream').InputStream; 17 | exports.FileStream = require('./FileStream').FileStream; 18 | exports.CommonTokenStream = require('./CommonTokenStream').CommonTokenStream; 19 | exports.Lexer = require('./Lexer').Lexer; 20 | exports.Parser = require('./Parser').Parser; 21 | var pc = require('./PredictionContext'); 22 | exports.PredictionContextCache = pc.PredictionContextCache; 23 | exports.ParserRuleContext = require('./ParserRuleContext').ParserRuleContext; 24 | exports.Interval = require('./IntervalSet').Interval; 25 | exports.Utils = require('./Utils'); -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/polyfills/codepointat.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /*! https://mths.be/codepointat v0.2.0 by @mathias */ 4 | if (!String.prototype.codePointAt) { 5 | (function () { 6 | 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` 7 | 8 | var defineProperty = function () { 9 | // IE 8 only supports `Object.defineProperty` on DOM elements 10 | try { 11 | var object = {}; 12 | var $defineProperty = Object.defineProperty; 13 | var result = $defineProperty(object, object, object) && $defineProperty; 14 | } catch (error) {} 15 | return result; 16 | }(); 17 | var codePointAt = function codePointAt(position) { 18 | if (this == null) { 19 | throw TypeError(); 20 | } 21 | var string = String(this); 22 | var size = string.length; 23 | // `ToInteger` 24 | var index = position ? Number(position) : 0; 25 | if (index != index) { 26 | // better `isNaN` 27 | index = 0; 28 | } 29 | // Account for out-of-bounds indices: 30 | if (index < 0 || index >= size) { 31 | return undefined; 32 | } 33 | // Get the first code unit 34 | var first = string.charCodeAt(index); 35 | var second; 36 | if ( // check if it’s the start of a surrogate pair 37 | first >= 0xD800 && first <= 0xDBFF && // high surrogate 38 | size > index + 1 // there is a next code unit 39 | ) { 40 | second = string.charCodeAt(index + 1); 41 | if (second >= 0xDC00 && second <= 0xDFFF) { 42 | // low surrogate 43 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae 44 | return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; 45 | } 46 | } 47 | return first; 48 | }; 49 | if (defineProperty) { 50 | defineProperty(String.prototype, 'codePointAt', { 51 | 'value': codePointAt, 52 | 'configurable': true, 53 | 'writable': true 54 | }); 55 | } else { 56 | String.prototype.codePointAt = codePointAt; 57 | } 58 | })(); 59 | } -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/polyfills/fromcodepoint.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */ 4 | if (!String.fromCodePoint) { 5 | (function () { 6 | var defineProperty = function () { 7 | // IE 8 only supports `Object.defineProperty` on DOM elements 8 | try { 9 | var object = {}; 10 | var $defineProperty = Object.defineProperty; 11 | var result = $defineProperty(object, object, object) && $defineProperty; 12 | } catch (error) {} 13 | return result; 14 | }(); 15 | var stringFromCharCode = String.fromCharCode; 16 | var floor = Math.floor; 17 | var fromCodePoint = function fromCodePoint(_) { 18 | var MAX_SIZE = 0x4000; 19 | var codeUnits = []; 20 | var highSurrogate; 21 | var lowSurrogate; 22 | var index = -1; 23 | var length = arguments.length; 24 | if (!length) { 25 | return ''; 26 | } 27 | var result = ''; 28 | while (++index < length) { 29 | var codePoint = Number(arguments[index]); 30 | if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` 31 | codePoint < 0 || // not a valid Unicode code point 32 | codePoint > 0x10FFFF || // not a valid Unicode code point 33 | floor(codePoint) != codePoint // not an integer 34 | ) { 35 | throw RangeError('Invalid code point: ' + codePoint); 36 | } 37 | if (codePoint <= 0xFFFF) { 38 | // BMP code point 39 | codeUnits.push(codePoint); 40 | } else { 41 | // Astral code point; split in surrogate halves 42 | // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae 43 | codePoint -= 0x10000; 44 | highSurrogate = (codePoint >> 10) + 0xD800; 45 | lowSurrogate = codePoint % 0x400 + 0xDC00; 46 | codeUnits.push(highSurrogate, lowSurrogate); 47 | } 48 | if (index + 1 == length || codeUnits.length > MAX_SIZE) { 49 | result += stringFromCharCode.apply(null, codeUnits); 50 | codeUnits.length = 0; 51 | } 52 | } 53 | return result; 54 | }; 55 | if (defineProperty) { 56 | defineProperty(String, 'fromCodePoint', { 57 | 'value': fromCodePoint, 58 | 'configurable': true, 59 | 'writable': true 60 | }); 61 | } else { 62 | String.fromCodePoint = fromCodePoint; 63 | } 64 | })(); 65 | } -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/tree/Trees.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | var Utils = require('./../Utils'); 9 | var Token = require('./../Token').Token; 10 | var RuleNode = require('./Tree').RuleNode; 11 | var ErrorNode = require('./Tree').ErrorNode; 12 | var TerminalNode = require('./Tree').TerminalNode; 13 | var ParserRuleContext = require('./../ParserRuleContext').ParserRuleContext; 14 | var RuleContext = require('./../RuleContext').RuleContext; 15 | var INVALID_ALT_NUMBER = require('./../atn/ATN').INVALID_ALT_NUMBER; 16 | 17 | /** A set of utility routines useful for all kinds of ANTLR trees. */ 18 | function Trees() {} 19 | 20 | // Print out a whole tree in LISP form. {@link //getNodeText} is used on the 21 | // node payloads to get the text for the nodes. Detect 22 | // parse trees and extract data appropriately. 23 | Trees.toStringTree = function (tree, ruleNames, recog) { 24 | ruleNames = ruleNames || null; 25 | recog = recog || null; 26 | if (recog !== null) { 27 | ruleNames = recog.ruleNames; 28 | } 29 | var s = Trees.getNodeText(tree, ruleNames); 30 | s = Utils.escapeWhitespace(s, false); 31 | var c = tree.getChildCount(); 32 | if (c === 0) { 33 | return s; 34 | } 35 | var res = "(" + s + ' '; 36 | if (c > 0) { 37 | s = Trees.toStringTree(tree.getChild(0), ruleNames); 38 | res = res.concat(s); 39 | } 40 | for (var i = 1; i < c; i++) { 41 | s = Trees.toStringTree(tree.getChild(i), ruleNames); 42 | res = res.concat(' ' + s); 43 | } 44 | res = res.concat(")"); 45 | return res; 46 | }; 47 | 48 | Trees.getNodeText = function (t, ruleNames, recog) { 49 | ruleNames = ruleNames || null; 50 | recog = recog || null; 51 | if (recog !== null) { 52 | ruleNames = recog.ruleNames; 53 | } 54 | if (ruleNames !== null) { 55 | if (t instanceof RuleContext) { 56 | var altNumber = t.getAltNumber(); 57 | if (altNumber != INVALID_ALT_NUMBER) { 58 | return ruleNames[t.ruleIndex] + ":" + altNumber; 59 | } 60 | return ruleNames[t.ruleIndex]; 61 | } else if (t instanceof ErrorNode) { 62 | return t.toString(); 63 | } else if (t instanceof TerminalNode) { 64 | if (t.symbol !== null) { 65 | return t.symbol.text; 66 | } 67 | } 68 | } 69 | // no recog for rule names 70 | var payload = t.getPayload(); 71 | if (payload instanceof Token) { 72 | return payload.text; 73 | } 74 | return t.getPayload().toString(); 75 | }; 76 | 77 | // Return ordered list of all children of this node 78 | Trees.getChildren = function (t) { 79 | var list = []; 80 | for (var i = 0; i < t.getChildCount(); i++) { 81 | list.push(t.getChild(i)); 82 | } 83 | return list; 84 | }; 85 | 86 | // Return a list of all ancestors of this node. The first node of 87 | // list is the root and the last is the parent of this node. 88 | // 89 | Trees.getAncestors = function (t) { 90 | var ancestors = []; 91 | t = t.getParent(); 92 | while (t !== null) { 93 | ancestors = [t].concat(ancestors); 94 | t = t.getParent(); 95 | } 96 | return ancestors; 97 | }; 98 | 99 | Trees.findAllTokenNodes = function (t, ttype) { 100 | return Trees.findAllNodes(t, ttype, true); 101 | }; 102 | 103 | Trees.findAllRuleNodes = function (t, ruleIndex) { 104 | return Trees.findAllNodes(t, ruleIndex, false); 105 | }; 106 | 107 | Trees.findAllNodes = function (t, index, findTokens) { 108 | var nodes = []; 109 | Trees._findAllNodes(t, index, findTokens, nodes); 110 | return nodes; 111 | }; 112 | 113 | Trees._findAllNodes = function (t, index, findTokens, nodes) { 114 | // check this node (the root) first 115 | if (findTokens && t instanceof TerminalNode) { 116 | if (t.symbol.type === index) { 117 | nodes.push(t); 118 | } 119 | } else if (!findTokens && t instanceof ParserRuleContext) { 120 | if (t.ruleIndex === index) { 121 | nodes.push(t); 122 | } 123 | } 124 | // check children 125 | for (var i = 0; i < t.getChildCount(); i++) { 126 | Trees._findAllNodes(t.getChild(i), index, findTokens, nodes); 127 | } 128 | }; 129 | 130 | Trees.descendants = function (t) { 131 | var nodes = [t]; 132 | for (var i = 0; i < t.getChildCount(); i++) { 133 | nodes = nodes.concat(Trees.descendants(t.getChild(i))); 134 | } 135 | return nodes; 136 | }; 137 | 138 | exports.Trees = Trees; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/antlr4/tree/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. 4 | * Use of this file is governed by the BSD 3-clause license that 5 | * can be found in the LICENSE.txt file in the project root. 6 | */ 7 | 8 | var Tree = require('./Tree'); 9 | exports.Trees = require('./Trees').Trees; 10 | exports.RuleNode = Tree.RuleNode; 11 | exports.ParseTreeListener = Tree.ParseTreeListener; 12 | exports.ParseTreeVisitor = Tree.ParseTreeVisitor; 13 | exports.ParseTreeWalker = Tree.ParseTreeWalker; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; 4 | 5 | var antlr4 = require('./antlr4/index'); 6 | 7 | var _require = require('./lib/SolidityLexer'), 8 | SolidityLexer = _require.SolidityLexer; 9 | 10 | var _require2 = require('./lib/SolidityParser'), 11 | SolidityParser = _require2.SolidityParser; 12 | 13 | var ASTBuilder = require('./ASTBuilder'); 14 | var ErrorListener = require('./ErrorListener'); 15 | 16 | var _require3 = require('./tokens'), 17 | buildTokenList = _require3.buildTokenList; 18 | 19 | function ParserError(args) { 20 | var _args$errors$ = args.errors[0], 21 | message = _args$errors$.message, 22 | line = _args$errors$.line, 23 | column = _args$errors$.column; 24 | 25 | this.message = message + ' (' + line + ':' + column + ')'; 26 | this.errors = args.errors; 27 | 28 | if (Error.captureStackTrace) { 29 | Error.captureStackTrace(this, this.constructor); 30 | } else { 31 | this.stack = new Error().stack; 32 | } 33 | } 34 | 35 | ParserError.prototype = Object.create(Error.prototype); 36 | ParserError.prototype.constructor = ParserError; 37 | ParserError.prototype.name = 'ParserError'; 38 | 39 | function tokenize(input, options) { 40 | options = options || {}; 41 | 42 | var chars = antlr4.CharStreams.fromString(input); 43 | var lexer = new SolidityLexer(chars); 44 | var tokens = new antlr4.CommonTokenStream(lexer); 45 | 46 | return buildTokenList(tokens.tokenSource.getAllTokens(), options); 47 | } 48 | 49 | function parse(input, options) { 50 | options = options || {}; 51 | 52 | var chars = antlr4.CharStreams.fromString(input); 53 | 54 | var listener = new ErrorListener(); 55 | 56 | var lexer = new SolidityLexer(chars); 57 | lexer.removeErrorListeners(); 58 | lexer.addErrorListener(listener); 59 | 60 | var tokens = new antlr4.CommonTokenStream(lexer); 61 | 62 | var parser = new SolidityParser(tokens); 63 | 64 | parser.removeErrorListeners(); 65 | parser.addErrorListener(listener); 66 | parser.buildParseTrees = true; 67 | 68 | var tree = parser.sourceUnit(); 69 | 70 | var tokenList = void 0; 71 | if (options.tokens) { 72 | var tokenSource = tokens.tokenSource; 73 | tokenSource.reset(); 74 | 75 | tokenList = buildTokenList(tokenSource.getAllTokens(), options); 76 | } 77 | 78 | if (!options.tolerant && listener.hasErrors()) { 79 | throw new ParserError({ errors: listener.getErrors() }); 80 | } 81 | 82 | var visitor = new ASTBuilder(options); 83 | var ast = visitor.visit(tree); 84 | 85 | if (options.tolerant && listener.hasErrors()) { 86 | ast.errors = listener.getErrors(); 87 | } 88 | if (options.tokens) { 89 | ast.tokens = tokenList; 90 | } 91 | 92 | return ast; 93 | } 94 | 95 | function _isASTNode(node) { 96 | return !!node && (typeof node === 'undefined' ? 'undefined' : _typeof(node)) === 'object' && node.hasOwnProperty('type'); 97 | } 98 | 99 | function visit(node, visitor) { 100 | if (Array.isArray(node)) { 101 | node.forEach(function (child) { 102 | return visit(child, visitor); 103 | }); 104 | } 105 | 106 | if (!_isASTNode(node)) return; 107 | 108 | var cont = true; 109 | 110 | if (visitor[node.type]) { 111 | cont = visitor[node.type](node); 112 | } 113 | 114 | if (cont === false) return; 115 | 116 | for (var prop in node) { 117 | if (node.hasOwnProperty(prop)) { 118 | visit(node[prop], visitor); 119 | } 120 | } 121 | 122 | var selector = node.type + ':exit'; 123 | if (visitor[selector]) { 124 | visitor[selector](node); 125 | } 126 | } 127 | 128 | exports.tokenize = tokenize; 129 | exports.parse = parse; 130 | exports.visit = visit; 131 | exports.ParserError = ParserError; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/dist/tokens.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 4 | 5 | var fs = require('fs'); 6 | var path = require('path'); 7 | 8 | var TYPE_TOKENS = ['var', 'bool', 'address', 'string', 'Int', 'Uint', 'Byte', 'Fixed', 'UFixed']; 9 | 10 | function rsplit(str, value) { 11 | var index = str.lastIndexOf(value); 12 | return [str.substring(0, index), str.substring(index + 1, str.length)]; 13 | } 14 | 15 | function normalizeTokenType(value) { 16 | if (value.endsWith("'")) { 17 | value = value.substring(0, value.length - 1); 18 | } 19 | if (value.startsWith("'")) { 20 | value = value.substring(1, value.length); 21 | } 22 | return value; 23 | } 24 | 25 | function getTokenType(value) { 26 | if (value === 'Identifier' || value === 'from') { 27 | return 'Identifier'; 28 | } else if (value === 'TrueLiteral' || value === 'FalseLiteral') { 29 | return 'Boolean'; 30 | } else if (value === 'VersionLiteral') { 31 | return 'Version'; 32 | } else if (value === 'StringLiteral') { 33 | return 'String'; 34 | } else if (TYPE_TOKENS.includes(value)) { 35 | return 'Type'; 36 | } else if (value === 'NumberUnit') { 37 | return 'Subdenomination'; 38 | } else if (value === 'DecimalNumber') { 39 | return 'Numeric'; 40 | } else if (value === 'HexLiteral') { 41 | return 'Hex'; 42 | } else if (value === 'ReservedKeyword') { 43 | return 'Reserved'; 44 | } else if (/^\W+$/.test(value)) { 45 | return 'Punctuator'; 46 | } else { 47 | return 'Keyword'; 48 | } 49 | } 50 | 51 | function getTokenTypeMap() { 52 | var filePath = path.join(__dirname, '../lib/Solidity.tokens'); 53 | 54 | return fs.readFileSync(filePath).toString('utf-8').split('\n').map(function (line) { 55 | return rsplit(line, '='); 56 | }).reduce(function (acum, _ref) { 57 | var _ref2 = _slicedToArray(_ref, 2), 58 | value = _ref2[0], 59 | key = _ref2[1]; 60 | 61 | acum[parseInt(key, 10)] = normalizeTokenType(value); 62 | return acum; 63 | }, {}); 64 | } 65 | 66 | function buildTokenList(tokens, options) { 67 | var tokenTypes = getTokenTypeMap(); 68 | 69 | return tokens.map(function (token) { 70 | var type = getTokenType(tokenTypes[token.type]); 71 | var node = { type: type, value: token.text }; 72 | if (options.range) { 73 | node.range = [token.start, token.stop + 1]; 74 | } 75 | if (options.loc) { 76 | node.loc = { 77 | start: { line: token.line, column: token.column }, 78 | end: { line: token.line, column: token.column + token.text.length } 79 | }; 80 | } 81 | return node; 82 | }); 83 | } 84 | 85 | exports.buildTokenList = buildTokenList; -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "_from": "solidity-parser-antlr", 3 | "_id": "solidity-parser-antlr@0.4.11", 4 | "_inBundle": false, 5 | "_integrity": "sha512-4jtxasNGmyC0midtjH/lTFPZYvTTUMy6agYcF+HoMnzW8+cqo3piFrINb4ZCzpPW+7tTVFCGa5ubP34zOzeuMg==", 6 | "_location": "/solidity-parser-antlr", 7 | "_phantomChildren": {}, 8 | "_requested": { 9 | "type": "tag", 10 | "registry": true, 11 | "raw": "solidity-parser-antlr", 12 | "name": "solidity-parser-antlr", 13 | "escapedName": "solidity-parser-antlr", 14 | "rawSpec": "", 15 | "saveSpec": null, 16 | "fetchSpec": "latest" 17 | }, 18 | "_requiredBy": [ 19 | "#USER", 20 | "/" 21 | ], 22 | "_resolved": "https://registry.npmjs.org/solidity-parser-antlr/-/solidity-parser-antlr-0.4.11.tgz", 23 | "_shasum": "af43e1f13b3b88309a875455f5d6e565b05ee5f1", 24 | "_spec": "solidity-parser-antlr", 25 | "_where": "/home/chenyy/learning_code_change", 26 | "author": { 27 | "name": "Federico Bond", 28 | "email": "federicobond@gmail.com" 29 | }, 30 | "bugs": { 31 | "url": "https://github.com/federicobond/solidity-parser-antlr/issues" 32 | }, 33 | "bundleDependencies": false, 34 | "deprecated": false, 35 | "description": "A Solidity parser built from a robust ANTLR 4 grammar", 36 | "devDependencies": { 37 | "babel-cli": "^6.26.0", 38 | "babel-preset-env": "^1.7.0", 39 | "chai": "^4.2.0", 40 | "eslint": "^5.16.0", 41 | "eslint-plugin-import": "^2.17.3", 42 | "eslint-plugin-node": "^9.1.0", 43 | "eslint-plugin-promise": "^4.1.1", 44 | "eslint-plugin-standard": "^4.0.0", 45 | "mocha": "^6.1.4", 46 | "nyc": "^14.1.1", 47 | "prettier": "^1.18.2", 48 | "tslint": "5.17.0", 49 | "tslint-config-prettier": "^1.18.0", 50 | "typescript": "3.5.2", 51 | "yarn": "^1.16.0" 52 | }, 53 | "homepage": "https://github.com/federicobond/solidity-parser-antlr", 54 | "license": "MIT", 55 | "main": "dist/index.js", 56 | "name": "solidity-parser-antlr", 57 | "nyc": { 58 | "include": [ 59 | "src/*.js" 60 | ] 61 | }, 62 | "repository": { 63 | "type": "git", 64 | "url": "git+https://github.com/federicobond/solidity-parser-antlr.git" 65 | }, 66 | "scripts": { 67 | "antlr4": "sh scripts/antlr4.sh", 68 | "build": "rm -rf dist && babel --out-dir=dist src", 69 | "eslint": "eslint src", 70 | "prepare": "yarn build", 71 | "pretest": "eslint src && tslint-config-prettier-check ./tslint.json", 72 | "prettier": "find src -name *.js | egrep -v '^src/(lib|antlr4)/' | xargs prettier --no-semi --single-quote --write", 73 | "test": "nyc mocha", 74 | "tslint": "tslint-config-prettier-check ./tslint.json" 75 | }, 76 | "types": "./index.d.ts", 77 | "version": "0.4.11" 78 | } 79 | -------------------------------------------------------------------------------- /node_modules/solidity-parser-antlr/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": [ 4 | "tslint:recommended", 5 | "tslint-config-prettier" 6 | ], 7 | "jsRules": {}, 8 | "rules": { 9 | "interface-name": [true, "never-prefix"] 10 | }, 11 | "rulesDirectory": [] 12 | } 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.8.1 2 | aiosignal==1.2.0 3 | antlr4-python3-runtime==4.9.3 4 | async-timeout==4.0.2 5 | asynctest==0.13.0 6 | attrs==20.3.0 7 | base58==2.1.1 8 | bitarray==1.2.2 9 | certifi==2021.10.8 10 | charset-normalizer==2.0.12 11 | click==8.0.4 12 | configparser==5.2.0 13 | cycler==0.11.0 14 | cytoolz==0.11.2 15 | dnspython==2.2.1 16 | docker==4.4.4 17 | eth-abi==2.1.1 18 | eth-account==0.5.7 19 | eth-hash==0.3.2 20 | eth-keyfile==0.5.1 21 | eth-keys==0.3.4 22 | eth-rlp==0.2.1 23 | eth-tester==0.6.0b6 24 | eth-typing==2.3.0 25 | eth-utils==1.10.0 26 | eventlet==0.33.0 27 | fonttools==4.29.1 28 | frozenlist==1.3.0 29 | gensim==3.8.3 30 | gitdb==4.0.9 31 | GitPython==3.1.5 32 | greenlet==1.1.2 33 | hexbytes==0.2.2 34 | idna==3.3 35 | ijson==3.1.4 36 | importlib-metadata==4.11.3 37 | ipfshttpclient==0.8.0a2 38 | joblib==1.1.0 39 | jsonschema==3.2.0 40 | kiwisolver==1.3.2 41 | lru-dict==1.1.7 42 | matplotlib==3.5.1 43 | multiaddr==0.0.9 44 | multidict==6.0.2 45 | netaddr==0.8.0 46 | nltk==3.5 47 | numpy==1.21.5 48 | packaging==21.3 49 | pandas==1.2.3 50 | parsimonious==0.8.1 51 | pbr==5.8.1 52 | Pillow==9.0.1 53 | ply==3.11 54 | protobuf==3.19.4 55 | py-solc==3.2.0 56 | py-solc-x==1.1.1 57 | pycryptodome==3.14.1 58 | pyparsing==3.0.7 59 | pyrsistent==0.18.1 60 | pysha3==1.0.2 61 | python-dateutil==2.8.2 62 | pytz==2021.3 63 | PyYAML==5.4.1 64 | regex==2022.3.15 65 | requests==2.27.1 66 | rlp==2.0.1 67 | sarif-om==1.0.4 68 | scipy==1.7.3 69 | semantic-version==2.9.0 70 | six==1.16.0 71 | smart-open==5.2.1 72 | smmap==5.0.0 73 | solc-select==0.2.0 74 | solidity-parser==0.0.7 75 | toolz==0.11.2 76 | torch==1.8.0+cu111 77 | torchaudio==0.8.0 78 | torchvision==0.9.0+cu111 79 | tqdm==4.63.0 80 | typing_extensions==4.1.1 81 | urllib3==1.26.8 82 | varint==1.0.2 83 | web3==5.28.0 84 | websocket-client==1.2.3 85 | websockets==9.1 86 | yarl==1.7.2 87 | zipp==3.7.0 88 | -------------------------------------------------------------------------------- /similarity_compute.py: -------------------------------------------------------------------------------- 1 | import os, re 2 | from gensim.models.fasttext import FastText 3 | from antlr4 import * 4 | from scipy.spatial import distance 5 | import numpy as np 6 | from solidityparser.SolidityLexer import SolidityLexer 7 | from solidityparser.SolidityParser import SolidityParser 8 | 9 | 10 | loading = False 11 | if loading: 12 | model = FastText.load("FastText/fasttext50/fasttext.model") 13 | 14 | def get3TokenSeq(path1, path2): 15 | with open(path1) as f: 16 | lines = f.readlines() 17 | buglines = [t[0] for t in enumerate(lines) if '// fault line' in t[1]] 18 | bugline = buglines[0] 19 | with open(path2, 'w') as again: 20 | for i in range(3): 21 | path3 = '{0}-{1}.sol'.format(path2.strip('.sol'), i+1) 22 | with open(path3, 'w') as f: 23 | for line in lines[bugline - 1 + i]: 24 | f.write(line) 25 | parser = SolidityParser(CommonTokenStream(SolidityLexer(FileStream(path3)))) 26 | tree = parser.sourceUnit() 27 | code_line = tree.toCodeSequence() 28 | regex = r'(\[)[0-9\s]*(\])' 29 | code_line = re.sub(regex, '', code_line) 30 | regex2 = "]+>" 31 | code_line = re.sub(regex2, '', code_line) 32 | tokenSeq = [x for x in code_line.split(' ') if not x == '' and not x == ''] 33 | seq = ' '.join(tokenSeq) 34 | again.write(seq) 35 | again.write('\n') 36 | for i in range(3): 37 | path4 = '{0}-{1}.sol'.format(path2.strip('.sol'), i + 1) 38 | os.remove(path4) 39 | 40 | def getLineVector(line, dimension): 41 | token_list = line.strip('\n').split(' ') 42 | vector = np.zeros((dimension,), dtype="float64") 43 | token_num = 0 44 | global model 45 | for token in token_list: 46 | if token in model: 47 | token_num += 1 48 | vector = np.add(vector, model[token]) 49 | lineVector = np.array([vector]) / token_num 50 | return lineVector 51 | 52 | def getSimilarity(v, e): 53 | numerator = distance.cdist(v.reshape(1, 150), e, 'euclidean') 54 | denominator = np.linalg.norm(e, axis=1) + np.linalg.norm(v) 55 | return 1 - np.divide(numerator, denominator) 56 | 57 | def get_similarity(contract_code_path): 58 | five_list = [] 59 | bts = [0, 1, 2, 3, 4] 60 | for bt in bts: 61 | tmp_dir = "dataset_vul/newALLBUGS/tmp/tmp_tokenseq3/" 62 | os.makedirs(tmp_dir, exist_ok=True) 63 | context1_npy_path = "FastText/bugEmbedding/{}context1.npy".format(bt) 64 | bug_npy_path = "FastText/bugEmbedding/{}bug.npy".format(bt) 65 | context2_npy_path = "FastText/bugEmbedding/{}context2.npy".format(bt) 66 | context1_npy = np.load(context1_npy_path) 67 | bug_npy = np.load(bug_npy_path) 68 | context2_npy = np.load(context2_npy_path) 69 | 70 | tmp_3tokenseq_path = tmp_dir + contract_code_path.split('/')[-1] 71 | get3TokenSeq(contract_code_path, tmp_3tokenseq_path) 72 | with open(tmp_3tokenseq_path) as tf: 73 | threelines = tf.readlines() 74 | context1_vector = getLineVector(threelines[0], 150) 75 | bug_vector = getLineVector(threelines[1], 150) 76 | context2_vector = getLineVector(threelines[2], 150) 77 | 78 | sims_list = [] 79 | for vs in zip(context1_npy, bug_npy, context2_npy): 80 | sims1 = getSimilarity(vs[0], context1_vector) 81 | sims2 = getSimilarity(vs[1], bug_vector) 82 | sims3 = getSimilarity(vs[2], context2_vector) 83 | w1, w2, w3 = (1, 2, 1) 84 | sims = (w1 * sims1 + w2 * sims2 + w3 * sims3) / (w1 + w2 + w3) 85 | sims_list.append(sims[0][0]) 86 | 87 | os.remove(tmp_3tokenseq_path) 88 | five_list.append(max(sims_list)) 89 | 90 | return max(five_list) 91 | -------------------------------------------------------------------------------- /solidity-extractor/extractor.js: -------------------------------------------------------------------------------- 1 | const parser = require('@solidity-parser/parser'); 2 | 3 | const ContractDef = 'ContractDefinition'; 4 | const FunctionDef = 'FunctionDefinition'; 5 | 6 | module.exports.extract = (sourceCode, opts = {}) => { 7 | const granularity = opts.granularity || 'sourceunit'; 8 | const tolerant = opts.tolerant || false; 9 | 10 | if(granularity == 'sourceunit') { 11 | return sourceCode; 12 | } 13 | 14 | const ast = parser.parse(sourceCode, { tolerant, range: true }); 15 | const output = {}; 16 | 17 | if(granularity == 'contract') { 18 | ast.children.forEach(child => { 19 | if(child.type == ContractDef) { 20 | const [start, end] = child.range; 21 | output[child.name] = sourceCode.substring(start, end + 1); 22 | } 23 | }); 24 | } else if(granularity == 'function') { 25 | ast.children.forEach(child => { 26 | if(child.type == ContractDef) { 27 | child.subNodes.forEach(grandchild => { 28 | if(grandchild.type == FunctionDef) { 29 | const [start, end] = grandchild.range; 30 | const tmp = sourceCode.substring(start, end + 1); 31 | output[child.name] = output[child.name] || {}; 32 | output[child.name][grandchild.name || 'fallback'] = tmp; 33 | } 34 | }); 35 | } 36 | }); 37 | } 38 | 39 | return output; 40 | }; 41 | 42 | module.exports.ParserError = parser.ParserError; 43 | -------------------------------------------------------------------------------- /solidity-extractor/function.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const extractor = require('./extractor'); 5 | 6 | const [,, ...infiles] = process.argv; 7 | 8 | infiles.forEach(file => { 9 | const addr = path.basename(file, '.sol'); 10 | const code = fs.readFileSync(file, 'utf8'); 11 | try { 12 | const contracts = extractor.extract(code, { granularity: 'function' }); 13 | Object.entries(contracts).forEach(([contractName, functions]) => { 14 | Object.entries(functions).forEach(([functionName, functionCode]) => { 15 | if(functionCode.search("// fault line") != -1) { 16 | const fout = fs.createWriteStream(`${addr}.sol`); 17 | fout.write(functionCode); 18 | fout.end(); 19 | } 20 | }); 21 | }); 22 | } catch(e) { 23 | if(e instanceof extractor.ParserError) { 24 | // TODO 25 | } 26 | console.error(e); 27 | } 28 | }); 29 | -------------------------------------------------------------------------------- /solidity-extractor/function_faultline.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const extractor = require('./extractor'); 5 | 6 | const [,, ...infiles] = process.argv; 7 | 8 | infiles.forEach(file => { 9 | const addr = path.basename(file, '.sol'); 10 | const code = fs.readFileSync(file, 'utf8'); 11 | try { 12 | const contracts = extractor.extract(code, { granularity: 'function' }); 13 | Object.entries(contracts).forEach(([contractName, functions]) => { 14 | Object.entries(functions).forEach(([functionName, functionCode]) => { 15 | if(functionCode.search("// fault line") != -1) { 16 | const fout = fs.createWriteStream(`${addr}.sol`); 17 | fout.write(functionCode); 18 | fout.end(); 19 | } 20 | }); 21 | }); 22 | } catch(e) { 23 | if(e instanceof extractor.ParserError) { 24 | // TODO 25 | } 26 | console.error(e); 27 | } 28 | }); 29 | -------------------------------------------------------------------------------- /solidityparser/Solidity.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /solidityparser/SolidityLexer.tokens: -------------------------------------------------------------------------------- 1 | T__0=1 2 | T__1=2 3 | T__2=3 4 | T__3=4 5 | T__4=5 6 | T__5=6 7 | T__6=7 8 | T__7=8 9 | T__8=9 10 | T__9=10 11 | T__10=11 12 | T__11=12 13 | T__12=13 14 | T__13=14 15 | T__14=15 16 | T__15=16 17 | T__16=17 18 | T__17=18 19 | T__18=19 20 | T__19=20 21 | T__20=21 22 | T__21=22 23 | T__22=23 24 | T__23=24 25 | T__24=25 26 | T__25=26 27 | T__26=27 28 | T__27=28 29 | T__28=29 30 | T__29=30 31 | T__30=31 32 | T__31=32 33 | T__32=33 34 | T__33=34 35 | T__34=35 36 | T__35=36 37 | T__36=37 38 | T__37=38 39 | T__38=39 40 | T__39=40 41 | T__40=41 42 | T__41=42 43 | T__42=43 44 | T__43=44 45 | T__44=45 46 | T__45=46 47 | T__46=47 48 | T__47=48 49 | T__48=49 50 | T__49=50 51 | T__50=51 52 | T__51=52 53 | T__52=53 54 | T__53=54 55 | T__54=55 56 | T__55=56 57 | T__56=57 58 | T__57=58 59 | T__58=59 60 | T__59=60 61 | T__60=61 62 | T__61=62 63 | T__62=63 64 | T__63=64 65 | T__64=65 66 | T__65=66 67 | T__66=67 68 | T__67=68 69 | T__68=69 70 | T__69=70 71 | T__70=71 72 | T__71=72 73 | T__72=73 74 | T__73=74 75 | T__74=75 76 | T__75=76 77 | T__76=77 78 | T__77=78 79 | T__78=79 80 | T__79=80 81 | T__80=81 82 | T__81=82 83 | T__82=83 84 | T__83=84 85 | T__84=85 86 | T__85=86 87 | T__86=87 88 | T__87=88 89 | T__88=89 90 | T__89=90 91 | T__90=91 92 | T__91=92 93 | T__92=93 94 | T__93=94 95 | T__94=95 96 | T__95=96 97 | T__96=97 98 | Int=98 99 | Uint=99 100 | Byte=100 101 | Fixed=101 102 | Ufixed=102 103 | BooleanLiteral=103 104 | DecimalNumber=104 105 | HexNumber=105 106 | NumberUnit=106 107 | HexLiteralFragment=107 108 | ReservedKeyword=108 109 | AnonymousKeyword=109 110 | BreakKeyword=110 111 | ConstantKeyword=111 112 | ImmutableKeyword=112 113 | ContinueKeyword=113 114 | LeaveKeyword=114 115 | ExternalKeyword=115 116 | IndexedKeyword=116 117 | InternalKeyword=117 118 | PayableKeyword=118 119 | PrivateKeyword=119 120 | PublicKeyword=120 121 | VirtualKeyword=121 122 | PureKeyword=122 123 | TypeKeyword=123 124 | ViewKeyword=124 125 | ConstructorKeyword=125 126 | FallbackKeyword=126 127 | ReceiveKeyword=127 128 | Identifier=128 129 | StringLiteralFragment=129 130 | VersionLiteral=130 131 | WS=131 132 | COMMENT=132 133 | LINE_COMMENT=133 134 | 'pragma'=1 135 | ';'=2 136 | '||'=3 137 | '^'=4 138 | '~'=5 139 | '>='=6 140 | '>'=7 141 | '<'=8 142 | '<='=9 143 | '='=10 144 | 'as'=11 145 | 'import'=12 146 | '*'=13 147 | 'from'=14 148 | '{'=15 149 | ','=16 150 | '}'=17 151 | 'abstract'=18 152 | 'contract'=19 153 | 'interface'=20 154 | 'library'=21 155 | 'is'=22 156 | '('=23 157 | ')'=24 158 | 'error'=25 159 | 'using'=26 160 | 'for'=27 161 | 'struct'=28 162 | 'modifier'=29 163 | 'function'=30 164 | 'returns'=31 165 | 'event'=32 166 | 'enum'=33 167 | '['=34 168 | ']'=35 169 | 'address'=36 170 | '.'=37 171 | 'mapping'=38 172 | '=>'=39 173 | 'memory'=40 174 | 'storage'=41 175 | 'calldata'=42 176 | 'if'=43 177 | 'else'=44 178 | 'try'=45 179 | 'catch'=46 180 | 'while'=47 181 | 'unchecked'=48 182 | 'assembly'=49 183 | 'do'=50 184 | 'return'=51 185 | 'throw'=52 186 | 'emit'=53 187 | 'revert'=54 188 | 'var'=55 189 | 'bool'=56 190 | 'string'=57 191 | 'byte'=58 192 | '++'=59 193 | '--'=60 194 | 'new'=61 195 | ':'=62 196 | '+'=63 197 | '-'=64 198 | 'after'=65 199 | 'delete'=66 200 | '!'=67 201 | '**'=68 202 | '/'=69 203 | '%'=70 204 | '<<'=71 205 | '>>'=72 206 | '&'=73 207 | '|'=74 208 | '=='=75 209 | '!='=76 210 | '&&'=77 211 | '?'=78 212 | '|='=79 213 | '^='=80 214 | '&='=81 215 | '<<='=82 216 | '>>='=83 217 | '+='=84 218 | '-='=85 219 | '*='=86 220 | '/='=87 221 | '%='=88 222 | 'let'=89 223 | ':='=90 224 | '=:'=91 225 | 'switch'=92 226 | 'case'=93 227 | 'default'=94 228 | '->'=95 229 | 'callback'=96 230 | 'override'=97 231 | 'anonymous'=109 232 | 'break'=110 233 | 'constant'=111 234 | 'immutable'=112 235 | 'continue'=113 236 | 'leave'=114 237 | 'external'=115 238 | 'indexed'=116 239 | 'internal'=117 240 | 'payable'=118 241 | 'private'=119 242 | 'public'=120 243 | 'virtual'=121 244 | 'pure'=122 245 | 'type'=123 246 | 'view'=124 247 | 'constructor'=125 248 | 'fallback'=126 249 | 'receive'=127 250 | -------------------------------------------------------------------------------- /src/exception/VulnerabilityNotFoundException.py: -------------------------------------------------------------------------------- 1 | class VulnerabilityNotFoundException(Exception): 2 | """ 3 | Exception raised when a Static Analysis tool reports an 4 | unknown exception for the table sarif_vulnerability_mapping.csv. 5 | 6 | Attributes: 7 | Tool -> The static analysis tool to report the vulnerability. 8 | Vulnerability -> The vulnerability reported. 9 | """ 10 | 11 | def __init__(self, tool, vulnerability): 12 | self.message = 'Vulnerability not found on sarif_vulnerability_mapping.csv table. Tool: {}, Vulnerability: {}'.format( 13 | tool, vulnerability) 14 | super().__init__(self.message) 15 | -------------------------------------------------------------------------------- /src/output_parser/Conkas.py: -------------------------------------------------------------------------------- 1 | from sarif_om import Tool, ToolComponent, MultiformatMessageString, Run 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import parseRule, parseResult, isNotDuplicateRule, parseArtifact, \ 5 | parseLogicalLocation, isNotDuplicateLogicalLocation 6 | 7 | 8 | class Conkas(Parser): 9 | def __init__(self): 10 | pass 11 | 12 | @staticmethod 13 | def __parse_vuln_line(line): 14 | vuln_type = line.split('Vulnerability: ')[1].split('.')[0] 15 | maybe_in_function = line.split('Maybe in function: ')[1].split('.')[0] 16 | pc = line.split('PC: ')[1].split('.')[0] 17 | line_number = line.split('Line number: ')[1].split('.')[0] 18 | if vuln_type == 'Integer Overflow': 19 | vuln_type = 'Integer_Overflow' 20 | elif vuln_type == 'Integer Underflow': 21 | vuln_type = 'Integer_Underflow' 22 | return { 23 | 'vuln_type': vuln_type, 24 | 'maybe_in_function': maybe_in_function, 25 | 'pc': pc, 26 | 'line_number': line_number 27 | } 28 | 29 | def parse(self, str_output): 30 | output = [] 31 | str_output = str_output.split('\n') 32 | for line in str_output: 33 | if 'Vulnerability' in line: 34 | try: 35 | output.append(self.__parse_vuln_line(line)) 36 | except: 37 | continue 38 | return output 39 | 40 | def parseSarif(self, conkas_output_results, file_path_in_repo): 41 | resultsList = [] 42 | rulesList = [] 43 | logicalLocationsList = [] 44 | 45 | for analysis_result in conkas_output_results["analysis"]: 46 | rule = parseRule(tool="conkas", vulnerability=analysis_result["vuln_type"]) 47 | 48 | logicalLocation = parseLogicalLocation(analysis_result["maybe_in_function"], kind="function") 49 | 50 | result = parseResult(tool="conkas", vulnerability=analysis_result["vuln_type"], uri=file_path_in_repo, 51 | line=int(analysis_result["line_number"]), 52 | logicalLocation=logicalLocation) 53 | 54 | resultsList.append(result) 55 | 56 | if isNotDuplicateRule(rule, rulesList): 57 | rulesList.append(rule) 58 | 59 | if isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 60 | logicalLocationsList.append(logicalLocation) 61 | 62 | artifact = parseArtifact(uri=file_path_in_repo) 63 | 64 | tool = Tool(driver=ToolComponent(name="Conkas", version="1.0.0", rules=rulesList, 65 | information_uri="https://github.com/nveloso/conkas", 66 | full_description=MultiformatMessageString( 67 | text="Conkas is based on symbolic execution, determines which inputs cause which program branches to execute, to find potential security vulnerabilities. Conkas uses rattle to lift bytecode to a high level representation."))) 68 | 69 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 70 | 71 | return run 72 | -------------------------------------------------------------------------------- /src/output_parser/HoneyBadger.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseRule, parseResult, \ 5 | parseArtifact, parseLogicalLocation, isNotDuplicateLogicalLocation 6 | 7 | 8 | class HoneyBadger(Parser): 9 | def __init__(self): 10 | pass 11 | 12 | def extract_result_line(self, line): 13 | line = line.replace("INFO:symExec: ", '') 14 | index_split = line.index(":") 15 | key = line[:index_split].lower().replace(' ', '_').replace('(', '').replace(')', '').strip() 16 | value = line[index_split + 1:].strip() 17 | if "True" == value: 18 | value = True 19 | elif "False" == value: 20 | value = False 21 | return (key, value) 22 | 23 | def parse(self, str_output): 24 | output = [] 25 | current_contract = None 26 | lines = str_output.splitlines() 27 | for line in lines: 28 | if "INFO:root:Contract " in line: 29 | if current_contract is not None: 30 | output.append(current_contract) 31 | current_contract = { 32 | 'errors': [] 33 | } 34 | (file, contract_name, _) = line.replace("INFO:root:Contract ", '').split(':') 35 | current_contract['file'] = file 36 | current_contract['name'] = contract_name 37 | elif "INFO:symExec: " in line and '---' not in line and '======' not in line: 38 | current_error = None 39 | (key, value) = self.extract_result_line(line) 40 | if value: 41 | current_error = key 42 | elif current_contract is not None and current_contract['file'] in line and line.index( 43 | current_contract['file']) == 0: 44 | (file, classname, line, column) = line.split(':') 45 | current_contract['errors'].append({ 46 | 'line': int(line), 47 | 'column': int(column), 48 | 'message': current_error 49 | }) 50 | if current_contract is not None: 51 | output.append(current_contract) 52 | return output 53 | 54 | def parseSarif(self, honeybadger_output_results, file_path_in_repo): 55 | resultsList = [] 56 | logicalLocationsList = [] 57 | rulesList = [] 58 | 59 | for analysis in honeybadger_output_results["analysis"]: 60 | for result in analysis["errors"]: 61 | rule = parseRule(tool="honeybadger", vulnerability=result["message"]) 62 | result = parseResult(tool="honeybadger", vulnerability=result["message"], level="warning", 63 | uri=file_path_in_repo, line=result["line"], column=result["column"]) 64 | 65 | resultsList.append(result) 66 | 67 | if isNotDuplicateRule(rule, rulesList): 68 | rulesList.append(rule) 69 | 70 | logicalLocation = parseLogicalLocation(analysis["name"]) 71 | 72 | if logicalLocation is not None and isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 73 | logicalLocationsList.append(logicalLocation) 74 | 75 | artifact = parseArtifact(uri=file_path_in_repo) 76 | 77 | tool = Tool(driver=ToolComponent(name="HoneyBadger", version="1.8.16", rules=rulesList, 78 | information_uri="https://honeybadger.uni.lu/", 79 | full_description=MultiformatMessageString( 80 | text="An analysis tool to detect honeypots in Ethereum smart contracts"))) 81 | 82 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 83 | 84 | return run 85 | -------------------------------------------------------------------------------- /src/output_parser/Maian.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import parseRule, \ 5 | parseResult, parseArtifact 6 | 7 | 8 | class Maian(Parser): 9 | def __init__(self): 10 | pass 11 | 12 | def parse(self, str_output): 13 | output = { 14 | 'is_lock_vulnerable': False, 15 | 'is_prodigal_vulnerable': False, 16 | 'is_suicidal_vulnerable': False, 17 | } 18 | lines = str_output.splitlines() 19 | for line in lines: 20 | if 'Locking vulnerability found!' in line: 21 | output['is_lock_vulnerable'] = True 22 | if 'The contract is prodigal' in line: 23 | output['is_prodigal_vulnerable'] = True 24 | if 'Confirmed ! The contract is suicidal' in line: 25 | output['is_suicidal_vulnerable'] = True 26 | return output 27 | 28 | def parseSarif(self, maian_output_results, file_path_in_repo): 29 | resultsList = [] 30 | rulesList = [] 31 | 32 | for vulnerability in maian_output_results["analysis"].keys(): 33 | if maian_output_results["analysis"][vulnerability]: 34 | rule = parseRule(tool="maian", vulnerability=vulnerability) 35 | result = parseResult(tool="maian", vulnerability=vulnerability, level="error", 36 | uri=file_path_in_repo) 37 | 38 | rulesList.append(rule) 39 | resultsList.append(result) 40 | 41 | artifact = parseArtifact(uri=file_path_in_repo) 42 | 43 | tool = Tool(driver=ToolComponent(name="Maian", version="5.10", rules=rulesList, 44 | information_uri="https://github.com/ivicanikolicsg/MAIAN", 45 | full_description=MultiformatMessageString( 46 | text="Maian is a tool for automatic detection of buggy Ethereum smart contracts of three different types prodigal, suicidal and greedy."))) 47 | 48 | run = Run(tool=tool, artifacts=[artifact], results=resultsList) 49 | 50 | return run 51 | -------------------------------------------------------------------------------- /src/output_parser/Manticore.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseArtifact, parseRule, parseResult 5 | 6 | 7 | class Manticore(Parser): 8 | def __init__(self): 9 | pass 10 | 11 | def parse(self, str_output): 12 | output = [] 13 | lines = str_output.splitlines() 14 | 15 | current_vul = None 16 | for line in lines: 17 | if len(line) == 0: 18 | continue 19 | if line[0] == '-': 20 | if current_vul is not None: 21 | output.append(current_vul) 22 | current_vul = { 23 | 'name': line[1:-2].strip(), 24 | 'line': -1, 25 | 'code': None 26 | } 27 | elif current_vul is not None and line[:4] == ' ': 28 | index = line[4:].rindex(' ') + 4 29 | current_vul['line'] = int(line[4:index]) 30 | current_vul['code'] = line[index:].strip() 31 | 32 | if current_vul is not None: 33 | output.append(current_vul) 34 | return output 35 | 36 | def parseSarif(self, manticore_output_results, file_path_in_repo): 37 | rulesList = [] 38 | resultsList = [] 39 | 40 | artifact = parseArtifact(uri=file_path_in_repo) 41 | 42 | for multipleAnalysis in manticore_output_results["analysis"]: 43 | for analysis in multipleAnalysis: 44 | rule = parseRule(tool="manticore", vulnerability=analysis["name"]) 45 | result = parseResult(tool="manticore", vulnerability=analysis["name"], level="warning", 46 | uri=file_path_in_repo, 47 | line=analysis["line"], snippet=analysis["code"]) 48 | 49 | resultsList.append(result) 50 | 51 | if isNotDuplicateRule(rule, rulesList): 52 | rulesList.append(rule) 53 | 54 | tool = Tool(driver=ToolComponent(name="Manticore", version="0.3.5", rules=rulesList, 55 | information_uri="https://github.com/trailofbits/manticore", 56 | full_description=MultiformatMessageString( 57 | text="Manticore is a symbolic execution tool for analysis of smart contracts and binaries."))) 58 | 59 | run = Run(tool=tool, artifacts=[artifact], results=resultsList) 60 | 61 | return run 62 | -------------------------------------------------------------------------------- /src/output_parser/Mythril.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseLogicalLocation, parseRule, \ 4 | parseResult, parseArtifact, isNotDuplicateLogicalLocation 5 | 6 | 7 | class Mythril: 8 | 9 | def parseSarif(self, mythril_output_results, file_path_in_repo): 10 | resultsList = [] 11 | logicalLocationsList = [] 12 | rulesList = [] 13 | 14 | for issue in mythril_output_results["analysis"]["issues"]: 15 | rule = parseRule(tool="mythril", vulnerability=issue["title"], full_description=issue["description"]) 16 | result = parseResult(tool="mythril", vulnerability=issue["title"], level=issue["type"], 17 | uri=file_path_in_repo, 18 | line=issue["lineno"], snippet=issue["code"] if "code" in issue.keys() else None, 19 | logicalLocation=parseLogicalLocation(issue["function"], 20 | kind="function")) 21 | 22 | logicalLocation = parseLogicalLocation(name=issue["function"], kind="function") 23 | 24 | if isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 25 | logicalLocationsList.append(logicalLocation) 26 | resultsList.append(result) 27 | 28 | if isNotDuplicateRule(rule, rulesList): 29 | rulesList.append(rule) 30 | 31 | artifact = parseArtifact(uri=file_path_in_repo) 32 | 33 | tool = Tool(driver=ToolComponent(name="Mythril", version="0.4.25", rules=rulesList, 34 | information_uri="https://mythx.io/", 35 | full_description=MultiformatMessageString( 36 | text="Mythril analyses EVM bytecode using symbolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities."))) 37 | 38 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 39 | 40 | return run 41 | -------------------------------------------------------------------------------- /src/output_parser/Osiris.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseRule, parseResult, \ 5 | parseArtifact, parseLogicalLocation, isNotDuplicateLogicalLocation 6 | 7 | 8 | class Osiris(Parser): 9 | def __init__(self): 10 | pass 11 | 12 | def extract_result_line(self, line): 13 | line = line.replace("INFO:symExec: ", '') 14 | index_split = line.index(":") 15 | key = line[:index_split].lower().replace(' ', '_').replace('(', '').replace(')', '').replace('└>_', '').strip() 16 | value = line[index_split + 1:].strip() 17 | if "True" == value: 18 | value = True 19 | elif "False" == value: 20 | value = False 21 | return (key, value) 22 | 23 | def parse(self, str_output): 24 | output = [] 25 | current_contract = None 26 | current_error = None 27 | lines = str_output.splitlines() 28 | for line in lines: 29 | if "INFO:root:Contract" in line: 30 | if current_contract is not None: 31 | output.append(current_contract) 32 | current_contract = { 33 | 'errors': [] 34 | } 35 | (file, contract_name, _) = line.replace("INFO:root:Contract ", '').split(':') 36 | current_contract['file'] = file 37 | current_contract['name'] = contract_name 38 | elif "INFO:symExec: " in line and '---' not in line and '======' not in line: 39 | current_error = None 40 | (key, value) = self.extract_result_line(line) 41 | if value: 42 | current_error = key 43 | elif current_contract is not None and current_contract['file'] in line and line.index( 44 | current_contract['file']) == 0: 45 | (file, classname, line, column) = line.split(':') 46 | current_contract['errors'].append({ 47 | 'line': int(line), 48 | 'column': int(column), 49 | 'message': current_error 50 | }) 51 | if current_contract is not None: 52 | output.append(current_contract) 53 | return output 54 | 55 | def parseSarif(self, osiris_output_results, file_path_in_repo): 56 | resultsList = [] 57 | logicalLocationsList = [] 58 | rulesList = [] 59 | 60 | for analysis in osiris_output_results["analysis"]: 61 | 62 | for result in analysis["errors"]: 63 | rule = parseRule(tool="osiris", vulnerability=result["message"]) 64 | result = parseResult(tool="osiris", vulnerability=result["message"], level="warning", 65 | uri=file_path_in_repo, line=result["line"], column=result["column"]) 66 | 67 | resultsList.append(result) 68 | 69 | if isNotDuplicateRule(rule, rulesList): 70 | rulesList.append(rule) 71 | 72 | logicalLocation = parseLogicalLocation(name=analysis["name"]) 73 | 74 | if isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 75 | logicalLocationsList.append(logicalLocation) 76 | 77 | artifact = parseArtifact(uri=file_path_in_repo) 78 | 79 | tool = Tool(driver=ToolComponent(name="Osiris", version="1.0", rules=rulesList, 80 | information_uri="https://github.com/christoftorres/Osiris", 81 | full_description=MultiformatMessageString( 82 | text="Osiris is an analysis tool to detect integer bugs in Ethereum smart contracts. Osiris is based on Oyente."))) 83 | 84 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 85 | 86 | return run 87 | -------------------------------------------------------------------------------- /src/output_parser/Oyente.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseRule, parseResult, \ 5 | parseArtifact, parseLogicalLocation, isNotDuplicateLogicalLocation 6 | 7 | 8 | class Oyente(Parser): 9 | def __init__(self): 10 | pass 11 | 12 | def extract_result_line(self, line): 13 | line = line.replace("INFO:symExec: ", '') 14 | index_split = line.index(":") 15 | key = line[:index_split].lower().replace(' ', '_').replace('(', '').replace(')', '').strip() 16 | value = line[index_split + 1:].strip() 17 | if "True" == value: 18 | value = True 19 | elif "False" == value: 20 | value = False 21 | return key, value 22 | 23 | def parse(self, str_output): 24 | output = [] 25 | current_contract = None 26 | lines = str_output.splitlines() 27 | for line in lines: 28 | if "INFO:root:contract" in line: 29 | if current_contract is not None: 30 | output.append(current_contract) 31 | current_contract = { 32 | 'errors': [] 33 | } 34 | (file, contract_name, _) = line.replace("INFO:root:contract ", '').split(':') 35 | current_contract['file'] = file 36 | current_contract['name'] = contract_name 37 | elif "INFO:symExec: " in line: 38 | (key, value) = self.extract_result_line(line) 39 | current_contract[key] = value 40 | elif current_contract and current_contract['file'] in line: 41 | if "INFO:symExec:" not in line: 42 | line = "INFO:symExec:" + line 43 | (line, column, level, message) = line.replace("INFO:symExec:%s:" % (current_contract['file']), 44 | '').split(':') 45 | current_contract['errors'].append({ 46 | 'line': int(line), 47 | 'column': int(column), 48 | 'level': level.strip(), 49 | 'message': message.strip() 50 | }) 51 | if current_contract is not None: 52 | output.append(current_contract) 53 | return output 54 | 55 | def parseSarif(self, oyente_output_results, file_path_in_repo): 56 | resultsList = [] 57 | logicalLocationsList = [] 58 | rulesList = [] 59 | 60 | for analysis in oyente_output_results["analysis"]: 61 | for result in analysis["errors"]: 62 | rule = parseRule(tool="oyente", vulnerability=result["message"]) 63 | result = parseResult(tool="oyente", vulnerability=result["message"], level=result["level"], 64 | uri=file_path_in_repo, line=result["line"], column=result["column"]) 65 | 66 | resultsList.append(result) 67 | 68 | if isNotDuplicateRule(rule, rulesList): 69 | rulesList.append(rule) 70 | 71 | logicalLocation = parseLogicalLocation(name=analysis["name"]) 72 | 73 | if isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 74 | logicalLocationsList.append(logicalLocation) 75 | 76 | artifact = parseArtifact(uri=file_path_in_repo) 77 | 78 | tool = Tool(driver=ToolComponent(name="Oyente", version="0.4.25", rules=rulesList, 79 | information_uri="https://oyente.tech/", 80 | full_description=MultiformatMessageString( 81 | text="Oyente runs on symbolic execution, determines which inputs cause which program branches to execute, to find potential security vulnerabilities. Oyente works directly with EVM bytecode without access high level representation and does not provide soundness nor completeness."))) 82 | 83 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 84 | 85 | return run 86 | -------------------------------------------------------------------------------- /src/output_parser/Parser.py: -------------------------------------------------------------------------------- 1 | class Parser: 2 | def __init__(self): 3 | pass 4 | 5 | def parse(self, str): 6 | pass 7 | 8 | def parseSarif(self, str, file_path_in_repo): 9 | pass 10 | -------------------------------------------------------------------------------- /src/output_parser/Securify.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | from sarif_om import * 3 | 4 | from src.output_parser.SarifHolder import parseLogicalLocation, parseArtifact, \ 5 | parseRule, parseResult, isNotDuplicateLogicalLocation 6 | 7 | 8 | class Securify: 9 | 10 | def parseSarif(self, securify_output_results, file_path_in_repo): 11 | resultsList = [] 12 | logicalLocationsList = [] 13 | rulesList = [] 14 | 15 | for name, analysis in securify_output_results["analysis"].items(): 16 | 17 | contractName = name.split(':')[1] 18 | logicalLocation = parseLogicalLocation(name=contractName) 19 | 20 | if isNotDuplicateLogicalLocation(logicalLocation, logicalLocationsList): 21 | logicalLocationsList.append(logicalLocation) 22 | 23 | for vuln, analysisResult in analysis["results"].items(): 24 | rule = parseRule(tool="securify", vulnerability=vuln) 25 | # Extra loop to add unique rule to tool in sarif 26 | for level, lines in analysisResult.items(): 27 | if len(lines) > 0: 28 | rulesList.append(rule) 29 | break 30 | for level, lines in analysisResult.items(): 31 | for lineNumber in lines: 32 | result = parseResult(tool="securify", vulnerability=vuln, level=level, uri=file_path_in_repo, 33 | line=lineNumber) 34 | 35 | resultsList.append(result) 36 | 37 | artifact = parseArtifact(uri=file_path_in_repo) 38 | 39 | tool = Tool(driver=ToolComponent(name="Securify", version="0.4.25", rules=rulesList, 40 | information_uri="https://github.com/eth-sri/securify2", 41 | full_description=MultiformatMessageString( 42 | text="Securify uses formal verification, also relying on static analysis checks. Securify’s analysis consists of two steps. First, it symbolically analyzes the contract’s dependency graph to extract precise semantic information from the code. Then, it checks compliance and violation patterns that capture sufficient conditions for proving if a property holds or not."))) 43 | 44 | run = Run(tool=tool, artifacts=[artifact], logical_locations=logicalLocationsList, results=resultsList) 45 | 46 | return run 47 | 48 | def parseSarifFromLiveJson(self, securify_output_results, file_path_in_repo): 49 | resultsList = [] 50 | rulesList = [] 51 | 52 | for name, analysis in securify_output_results["analysis"].items(): 53 | for vuln, analysisResult in analysis["results"].items(): 54 | rule = parseRule(tool="securify", vulnerability=vuln) 55 | # Extra loop to add unique rule to tool in sarif 56 | for level, lines in analysisResult.items(): 57 | if not isinstance(lines, list): 58 | continue 59 | if len(lines) > 0: 60 | rulesList.append(rule) 61 | break 62 | for level, lines in analysisResult.items(): 63 | if not isinstance(lines, list): 64 | continue 65 | for lineNumber in list(numpy.unique(lines)): 66 | result = parseResult(tool="securify", vulnerability=vuln, level=level, uri=file_path_in_repo, 67 | line=int(lineNumber)) # without int() lineNumber returns null??! 68 | 69 | resultsList.append(result) 70 | 71 | artifact = parseArtifact(uri=file_path_in_repo) 72 | 73 | tool = Tool(driver=ToolComponent(name="Securify", version="0.4.25", rules=rulesList, 74 | information_uri="https://github.com/eth-sri/securify2", 75 | full_description=MultiformatMessageString( 76 | text="Securify uses formal verification, also relying on static analysis checks. Securify’s analysis consists of two steps. First, it symbolically analyzes the contract’s dependency graph to extract precise semantic information from the code. Then, it checks compliance and violation patterns that capture sufficient conditions for proving if a property holds or not."))) 77 | 78 | run = Run(tool=tool, artifacts=[artifact], results=resultsList) 79 | 80 | return run 81 | -------------------------------------------------------------------------------- /src/output_parser/Slither.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseRule, parseArtifact, parseResult 4 | 5 | 6 | class Slither: 7 | 8 | def parseSarif(self, slither_output_results, file_path_in_repo): 9 | rulesList = [] 10 | resultsList = [] 11 | 12 | for analysis in slither_output_results["analysis"]: 13 | 14 | level = analysis["impact"] 15 | message = analysis["description"] 16 | locations = [] 17 | 18 | for element in analysis["elements"]: 19 | location = Location(physical_location=PhysicalLocation( 20 | artifact_location=ArtifactLocation(uri=file_path_in_repo), 21 | region=Region(start_line=element["source_mapping"]["lines"][0], 22 | end_line=element["source_mapping"]["lines"][-1])), logical_locations=[]) 23 | 24 | if "name" in element.keys(): 25 | if "type" in element.keys(): 26 | location.logical_locations.append(LogicalLocation(name=element["name"], kind=element["type"])) 27 | if "target" in element.keys(): 28 | location.logical_locations.append(LogicalLocation(name=element["name"], kind=element["target"])) 29 | if "expression" in element.keys(): 30 | location.physical_location.region.snippet = ArtifactContent(text=element["expression"]) 31 | if "contract" in element.keys(): 32 | location.logical_locations.append( 33 | LogicalLocation(name=element["contract"]["name"], kind=element["contract"]["type"])) 34 | locations.append(location) 35 | 36 | result = parseResult(tool="slither", vulnerability=analysis["check"], level=level) 37 | 38 | result.locations = locations 39 | 40 | rule = parseRule(tool="slither", vulnerability=analysis["check"], full_description=message) 41 | 42 | if isNotDuplicateRule(rule, rulesList): 43 | rulesList.append(rule) 44 | 45 | resultsList.append(result) 46 | 47 | artifact = parseArtifact(uri=file_path_in_repo) 48 | 49 | tool = Tool(driver=ToolComponent(name="Slither", version="0.7.0", rules=rulesList, 50 | information_uri="https://github.com/crytic/slither", 51 | full_description=MultiformatMessageString( 52 | text="Slither is a Solidity static analysis framework written in Python 3. It runs a suite of vulnerability detectors and prints visual information about contract details. Slither enables developers to find vulnerabilities, enhance their code comphrehension, and quickly prototype custom analyses."))) 53 | 54 | run = Run(tool=tool, artifacts=[artifact], results=resultsList) 55 | 56 | return run 57 | -------------------------------------------------------------------------------- /src/output_parser/Smartcheck.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseArtifact, parseRule, parseResult, parseLogicalLocation 5 | 6 | 7 | class Smartcheck(Parser): 8 | def __init__(self): 9 | pass 10 | 11 | def extract_result_line(self, line): 12 | index_split = line.index(":") 13 | key = line[:index_split] 14 | value = line[index_split + 1:].strip() 15 | if value.isdigit(): 16 | value = int(value) 17 | return (key, value) 18 | 19 | def parse(self, str_output): 20 | output = [] 21 | current_error = None 22 | lines = str_output.splitlines() 23 | for line in lines: 24 | if "ruleId: " in line: 25 | if current_error is not None: 26 | output.append(current_error) 27 | current_error = { 28 | 'name': line[line.index("ruleId: ") + 8:] 29 | } 30 | elif current_error is not None and ':' in line and ' :' not in line: 31 | (key, value) = self.extract_result_line(line) 32 | current_error[key] = value 33 | 34 | if current_error is not None: 35 | output.append(current_error) 36 | return output 37 | 38 | def parseSarif(self, smartcheck_output_results, file_path_in_repo): 39 | resultsList = [] 40 | rulesList = [] 41 | 42 | artifact = parseArtifact(uri=file_path_in_repo) 43 | 44 | for analysis in smartcheck_output_results["analysis"]: 45 | rule = parseRule(tool="smartcheck", vulnerability=analysis["name"]) 46 | result = parseResult(tool="smartcheck", vulnerability=analysis["name"], level=analysis["severity"], 47 | uri=file_path_in_repo, 48 | line=analysis["line"], column=analysis["column"], snippet=analysis["content"]) 49 | 50 | resultsList.append(result) 51 | 52 | if isNotDuplicateRule(rule, rulesList): 53 | rulesList.append(rule) 54 | 55 | logicalLocation = parseLogicalLocation(name=smartcheck_output_results["contract"]) 56 | 57 | tool = Tool(driver=ToolComponent(name="SmartCheck", version="0.0.12", rules=rulesList, 58 | information_uri="https://tool.smartdec.net/", 59 | full_description=MultiformatMessageString( 60 | text="Securify automatically checks for vulnerabilities and bad coding practices. It runs lexical and syntactical analysis on Solidity source code."))) 61 | 62 | run = Run(tool=tool, artifacts=[artifact], logical_locations=[logicalLocation], results=resultsList) 63 | 64 | return run 65 | -------------------------------------------------------------------------------- /src/output_parser/Solhint.py: -------------------------------------------------------------------------------- 1 | from sarif_om import * 2 | 3 | from src.output_parser.Parser import Parser 4 | from src.output_parser.SarifHolder import isNotDuplicateRule, parseRule, parseResult, parseArtifact, parseLogicalLocation 5 | 6 | 7 | class Solhint(Parser): 8 | def __init__(self): 9 | pass 10 | 11 | def parse(self, str_output): 12 | output = [] 13 | lines = str_output.splitlines() 14 | for line in lines: 15 | if ":" in line: 16 | s_result = line.split(':') 17 | if len(s_result) != 4: 18 | continue 19 | (file, line, column, end_error) = s_result 20 | if ']' not in end_error: 21 | continue 22 | message = end_error[1:end_error.index('[') - 1] 23 | level = end_error[end_error.index('[') + 1: end_error.index('/')] 24 | type = end_error[end_error.index('/') + 1: len(end_error) - 1] 25 | output.append({ 26 | 'file': file, 27 | 'line': line, 28 | 'column': column, 29 | 'message': message, 30 | 'level': level, 31 | 'type': type 32 | }) 33 | 34 | return output 35 | 36 | def parseSarif(self, solhint_output_results, file_path_in_repo): 37 | resultsList = [] 38 | rulesList = [] 39 | 40 | for analysis in solhint_output_results["analysis"]: 41 | rule = parseRule(tool="solhint", vulnerability=analysis["type"], full_description=analysis["message"]) 42 | result = parseResult(tool="solhint", vulnerability=analysis["type"], level=analysis["level"], 43 | uri=file_path_in_repo, line=int(analysis["line"]), column=int(analysis["column"])) 44 | 45 | resultsList.append(result) 46 | 47 | if isNotDuplicateRule(rule, rulesList): 48 | rulesList.append(rule) 49 | 50 | artifact = parseArtifact(uri=file_path_in_repo) 51 | 52 | logicalLocation = parseLogicalLocation(name=solhint_output_results["contract"], kind="contract") 53 | 54 | tool = Tool(driver=ToolComponent(name="Solhint", version="3.3.2", rules=rulesList, 55 | information_uri="https://protofire.github.io/solhint/", 56 | full_description=MultiformatMessageString( 57 | text="Open source project for linting solidity code. This project provide both security and style guide validations."))) 58 | 59 | run = Run(tool=tool, artifacts=[artifact], logical_locations=[logicalLocation], results=resultsList) 60 | 61 | return run 62 | -------------------------------------------------------------------------------- /src/output_parser/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anonymous123xx/RLRep/a06f64caa153e22494f5e063dde965044f9b8baf/src/output_parser/__init__.py -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/Dockerfile: -------------------------------------------------------------------------------- 1 | # Docker Image with MAIAN and Solc for Augur contracts security analysis 2 | 3 | # Pull base image 4 | FROM ubuntu:16.04 5 | 6 | # Install Python and build tools 7 | RUN \ 8 | apt-get update && \ 9 | apt-get install -y build-essential software-properties-common libssl-dev wget && \ 10 | apt-get install -y python python-dev python-pip git psmisc lsof 11 | 12 | # Install Solidity compiler 0.4.25 release 13 | #RUN wget https://github.com/ethereum/solidity/releases/download/v0.4.25/solc-static-linux && \ 14 | # mv solc-static-linux /usr/bin/solc 15 | 16 | # Install Solidity compiler 0.5.10 release 17 | RUN wget https://github.com/ethereum/solidity/releases/download/v0.5.10/solc-static-linux && \ 18 | mv solc-static-linux /usr/bin/solc 19 | 20 | # Install Go Ethereum (GETH) from Ethereum PPA 21 | RUN \ 22 | add-apt-repository ppa:ethereum/ethereum && \ 23 | apt-get update && \ 24 | apt-get -y install ethereum 25 | 26 | # Install MAIAN from GitHub 27 | RUN \ 28 | git clone https://github.com/MAIAN-tool/MAIAN.git 29 | 30 | # Install Python dependencies 31 | 32 | RUN pip install --upgrade pip 33 | 34 | COPY requirements.txt scripts/requirements.txt 35 | RUN \ 36 | pip install -r scripts/requirements.txt 37 | 38 | # Copy test runner script to Docker image 39 | COPY scripts/test_runner.py scripts/test_runner.py 40 | 41 | # Set SOLC environment variable 42 | ENV SOLC /usr/bin/solc 43 | 44 | # Add exec rights to solc 45 | RUN chmod +x /usr/bin/solc 46 | 47 | # Extract contract names automatically 48 | RUN apt-get -y install python3-pip 49 | 50 | ENV LC_ALL C.UTF-8 51 | 52 | RUN pip3 --no-cache-dir install --upgrade setuptools pip 53 | 54 | RUN pip3 install solidity_parser 55 | 56 | COPY scripts/printContractNames.py printContractNames.py 57 | COPY scripts/runMAIANall.sh runMAIANall.sh 58 | RUN chmod +x printContractNames.py runMAIANall.sh 59 | 60 | # Allow insecure unlock 61 | RUN sed -si "s/'geth'/'geth','--allow-insecure-unlock'/g" /MAIAN/tool/blockchain.py 62 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/README.md: -------------------------------------------------------------------------------- 1 | # MAIAN Continuous Integration Docker Image for Augur project 2 | 3 | This Docker file is based on cryptomental's Docker file for the Augur Project: https://github.com/cryptomental/maian-augur-ci 4 | 5 | The Docker Image is available at https://hub.docker.com/r/smartbugs/maian 6 | 7 | 8 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/requirements.txt: -------------------------------------------------------------------------------- 1 | pandoc-attributes 2 | rlp==0.6.0 3 | web3==3.16.5 4 | z3-solver 5 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/scripts/printContractNames.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pprint 3 | 4 | from solidity_parser import parser 5 | 6 | sourceUnit = parser.parse_file(sys.argv[1]) 7 | #pprint.pprint(sourceUnit) 8 | 9 | sourceUnitObject = parser.objectify(sourceUnit) 10 | 11 | # access imports, contracts, functions, ... (see outline example in 12 | # __main__.py) 13 | sourceUnitObject.imports # [] 14 | sourceUnitObject.pragmas # [] 15 | for contract_name in sourceUnitObject.contracts.keys(): 16 | print(contract_name) 17 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/scripts/runMAIANall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | FILENAME=$1 4 | 5 | for c in `python3 printContractNames.py ${FILENAME}`; 6 | do 7 | cd /MAIAN/tool; 8 | python maian.py -c 0 -s ${FILENAME} ${c}; 9 | python maian.py -c 1 -s ${FILENAME} ${c}; 10 | python maian.py -c 2 -s ${FILENAME} ${c} 11 | done 12 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-maian/scripts/test_runner.py: -------------------------------------------------------------------------------- 1 | """ 2 | MAIAN CI test runner for Augur project. 3 | """ 4 | import argparse 5 | import json 6 | import os 7 | import pprint 8 | import re 9 | import shutil 10 | 11 | from subprocess import check_output 12 | 13 | fail_build = False # Specifies if to fail the build 14 | 15 | 16 | def check_failure(test_result): 17 | """ 18 | Return True if a failure was found. 19 | 20 | :param test_result: test result log. 21 | :return: True if failure found, false otherwise. 22 | """ 23 | fail_regexes = ["Confirmed ! The contract is suicidal !", 24 | "Confirmed ! The contract is prodigal !", 25 | "Leak vulnerability found!", 26 | "Locking vulnerability found!", 27 | "The code does not have CALL/SUICIDE/DELEGATECALL/CALLCODE thus is greedy !"] 28 | for fail_regex in fail_regexes: 29 | if re.search(fail_regex, test_result, re.IGNORECASE): 30 | return True 31 | return False 32 | 33 | 34 | def setup_blockchain(maian_blockchain_dir="/MAIAN/tool/blockchains"): 35 | """ 36 | Setup private blockchain for the project. 37 | 38 | :param maian_blockchain_dir: path to MAIAN blockchain dir 39 | :return: - 40 | """ 41 | if os.path.exists(os.path.join(os.getcwd(), 'blockchains')): 42 | shutil.rmtree(os.path.join(os.getcwd(), 'blockchains')) 43 | shutil.copytree(maian_blockchain_dir, os.path.join(os.getcwd(), 'blockchains')) 44 | 45 | 46 | def run_maian(contract_bytecode_path, mode): 47 | """ 48 | Run MAIAN tool. 49 | 50 | :param contract_bytecode_path: path to bin contract file 51 | :param mode: 0 - search for suicidal contracts, 1 - prodigal, 2 - greedy. 52 | :return: True if vulnerability found. False otherwise. 53 | """ 54 | vulnerability_found = False 55 | result = check_output(['python', 56 | '/MAIAN/tool/maian.py', 57 | '-b', 58 | contract_bytecode_path, 59 | '-c', 60 | mode]).decode("utf-8") 61 | print(result) 62 | 63 | if check_failure(result): 64 | vulnerability_found = True 65 | 66 | return vulnerability_found 67 | 68 | 69 | def extract_augur_contracts_for_analysis(contracts_file_path= 70 | '/app/output/contracts/contracts.json'): 71 | """ 72 | Extract Augur contracts from contracts.json 73 | 74 | :param contracts_file_path: full path to contracts.json 75 | :return: a list of paths to files with contracts bytecode 76 | :rtype: list 77 | """ 78 | contract_list = [] 79 | with open(contracts_file_path) as f: 80 | contracts = json.load(f)['contracts'] 81 | for contract_filename in contracts.keys(): 82 | contract_name = contracts[contract_filename].keys()[0] 83 | contract_bytecode = contracts[contract_filename][contract_name]['evm']['bytecode']['object'] 84 | print("Extracting " + contract_filename + "...") 85 | if os.path.exists(os.path.join(os.getcwd(), contract_filename)): 86 | os.remove(os.path.join(os.getcwd(), contract_filename)) 87 | try: 88 | os.makedirs(os.path.join(os.getcwd(), os.path.dirname(contract_filename))) 89 | except os.error: 90 | pass # folder already exists 91 | contract_bytecode_path = os.path.join(os.path.dirname(contract_filename), contract_name + '.bin') 92 | with open(contract_bytecode_path, 'w') as wf: 93 | wf.write(contract_bytecode) 94 | print("Contract bytecode written to " + contract_bytecode_path) 95 | contract_list.append(contract_bytecode_path) 96 | return contract_list 97 | 98 | 99 | if __name__ == '__main__': 100 | parser = argparse.ArgumentParser() 101 | parser.add_argument("--fail-on-vulnerability", 102 | help="Return a non-zero exit code if a vulnerability is found", 103 | action="store_true", 104 | default=False) 105 | args = parser.parse_args() 106 | 107 | setup_blockchain() 108 | 109 | suicidal = [] 110 | prodigal = [] 111 | greedy = [] 112 | 113 | # Process each file individually and check for suicidal, prodigal and greedy contracts 114 | for file in extract_augur_contracts_for_analysis(): 115 | 116 | print("Processing " + file + " for suicidal contracts\n") 117 | if run_maian(file, '0'): 118 | suicidal.append(file) 119 | if args.fail_on_vulnerability: 120 | fail_build = True 121 | 122 | print("Processing " + file + " for prodigal contracts\n") 123 | if run_maian(file, '1'): 124 | prodigal.append(file) 125 | if args.fail_on_vulnerability: 126 | fail_build = True 127 | 128 | print("Processing " + file + " for greedy contracts\n") 129 | if run_maian(file, '2'): 130 | greedy.append(file) 131 | if args.fail_on_vulnerability: 132 | fail_build = True 133 | 134 | print("#" * 60) 135 | print("MAIAN test results summary:") 136 | print("Suicidal contracts:") 137 | pprint.pprint([c.encode("utf-8") for c in sorted(suicidal)]) 138 | print("Prodigal contracts:") 139 | pprint.pprint([c.encode("utf-8") for c in sorted(prodigal)]) 140 | print("Greedy contracts:") 141 | pprint.pprint([c.encode("utf-8") for c in sorted(greedy)]) 142 | 143 | if fail_build: 144 | exit(1) 145 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-manticore/Dockerfile: -------------------------------------------------------------------------------- 1 | # Docker Image with manticore 2 | 3 | # Pull base image 4 | FROM trailofbits/manticore 5 | 6 | # Extract contract names automatically 7 | RUN apt-get -y install python3-pip 8 | 9 | ENV LC_ALL C.UTF-8 10 | 11 | RUN pip3 --no-cache-dir install --upgrade setuptools pip 12 | 13 | RUN pip3 install solidity_parser 14 | 15 | COPY scripts/printContractNames.py printContractNames.py 16 | COPY scripts/runManticore.sh runManticore.sh 17 | RUN chmod +x printContractNames.py runManticore.sh 18 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-manticore/README.md: -------------------------------------------------------------------------------- 1 | # Manticore Docker Image for the SmartBugs project 2 | 3 | This Docker file is based on Trail of Bit's image: https://hub.docker.com/r/trailofbits/manticore 4 | 5 | The Docker Image is available at https://hub.docker.com/r/smartbugs/manticore 6 | 7 | 8 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-manticore/scripts/printContractNames.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pprint 3 | 4 | from solidity_parser import parser 5 | 6 | sourceUnit = parser.parse_file(sys.argv[1]) 7 | #pprint.pprint(sourceUnit) 8 | 9 | sourceUnitObject = parser.objectify(sourceUnit) 10 | 11 | # access imports, contracts, functions, ... (see outline example in 12 | # __main__.py) 13 | sourceUnitObject.imports # [] 14 | sourceUnitObject.pragmas # [] 15 | for contract_name in sourceUnitObject.contracts.keys(): 16 | print(contract_name) 17 | -------------------------------------------------------------------------------- /utils/docker/smartbugs-manticore/scripts/runManticore.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | FILENAME=$1 4 | 5 | mkdir /results 6 | for c in `python3 printContractNames.py ${FILENAME}`; 7 | do 8 | path_contract=$(echo "$1" | sed -e 's/^\///') 9 | manticore --no-colors --contract ${c} $path_contract 10 | mv /mcore_* /results 11 | done 12 | -------------------------------------------------------------------------------- /utils/scripts/get_vulns_lines.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | (async () => { 4 | const fs = require('fs') 5 | 6 | const getSolidityFiles = (dir, filelist) => { 7 | files = fs.readdirSync(dir) 8 | filelist = filelist || [] 9 | files.forEach(function(file) { 10 | file_type = file.split(".").pop() 11 | if (fs.statSync(dir + '/' + file).isDirectory()) { 12 | filelist = getSolidityFiles(dir + '/' + file, filelist) 13 | } 14 | else if (file_type == "sol") { 15 | const contract_dir = dir + '/' + file 16 | const vuln_cat = dir.split("/").pop() 17 | const params = { 18 | name: file, 19 | path: contract_dir, 20 | cat: vuln_cat 21 | } 22 | filelist.push(params) 23 | } 24 | }) 25 | return filelist 26 | } 27 | 28 | const getResults = () => { 29 | const results = [] 30 | const contracts = getSolidityFiles('dataset') 31 | contracts.forEach(contract => { 32 | let vulnerabilities = [] 33 | let result = { 34 | name: contract.name, 35 | path: contract.path, 36 | source: '', 37 | vulnerabilities: vulnerabilities 38 | } 39 | const contract_lines = fs.readFileSync(contract.path).toString().split("\n") 40 | contract_lines.forEach(line => { 41 | let contract_source, vuln_at_lines 42 | 43 | //get source 44 | if (line.includes('@source:')) { 45 | contract_source = line.split("@source:").pop() 46 | result.source = contract_source.trim() 47 | return 48 | } 49 | //get vuln lines 50 | if (line.includes('@vulnerable_at_lines')) { 51 | vuln_at_lines = line.split("@vulnerable_at_lines: ").pop() 52 | const lines = vuln_at_lines.split(",") 53 | 54 | for (let index = 0; index < lines.length; index++){ 55 | let vuln 56 | let vuln_flow = [] 57 | if((parseInt(lines[index]) + 1) === parseInt(lines[index + 1])){ 58 | while((parseInt(lines[index]) + 1) === parseInt(lines[index + 1])){ 59 | vuln_flow.push(parseInt(lines[index])) 60 | index+=1 61 | } 62 | vuln_flow.push(parseInt(lines[index])) 63 | vuln = { 64 | lines: vuln_flow, 65 | category: contract.cat 66 | } 67 | } 68 | 69 | else{ 70 | vuln_flow.push(parseInt(lines[index])) 71 | vuln = { 72 | lines: vuln_flow, 73 | category: contract.cat 74 | } 75 | } 76 | vulnerabilities.push(vuln) 77 | } 78 | 79 | return 80 | } 81 | 82 | }) 83 | 84 | results.push(result) 85 | }) 86 | return results 87 | } 88 | 89 | const result = getResults() 90 | fs.writeFileSync('dataset/vulnerabilities.json', JSON.stringify(result)) 91 | process.exit() 92 | })() 93 | -------------------------------------------------------------------------------- /utils/vagrant/README.md: -------------------------------------------------------------------------------- 1 | # SmartBugs Vagrant Box 2 | 3 | This Vagrant box can be used to experiment with SmartBugs. 4 | 5 | ![Screenshot of SmartBugs Vagrant box](vagrant-box-screenshot.png "Screenshot of SmartBugs Vagrant box") 6 | 7 | 8 | ## Requirements 9 | 10 | We tested this Vagrant box with [Vagrant](https://www.vagrantup.com) 2.2.6 and [VirtualBox](https://www.virtualbox.org) 5.2.34 11 | 12 | The Vagrant plugin `vagrant-reload` is required and can be installed as: 13 | 14 | ```bash 15 | vagrant plugin install vagrant-reload 16 | ``` 17 | 18 | ## Usage 19 | 20 | Just run the following command to get the virtual box up and running: 21 | 22 | ```bash 23 | vagrant up 24 | ``` 25 | 26 | To access the box, use the command: 27 | 28 | ```bash 29 | vagrant ssh 30 | ``` 31 | 32 | For more details and documentation on SmartBugs: https://smartbugs.github.io 33 | -------------------------------------------------------------------------------- /utils/vagrant/Vagrantfile: -------------------------------------------------------------------------------- 1 | # -*- mode: ruby -*- 2 | # vi: set ft=ruby : 3 | 4 | # All Vagrant configuration is done below. The "2" in Vagrant.configure 5 | # configures the configuration version (we support older styles for 6 | # backwards compatibility). Please don't change it unless you know what 7 | # you're doing. 8 | Vagrant.configure("2") do |config| 9 | # The most common configuration options are documented and commented below. 10 | # For a complete reference, please see the online documentation at 11 | # https://docs.vagrantup.com. 12 | 13 | # Every Vagrant development environment requires a box. You can search for 14 | # boxes at https://atlas.hashicorp.com/search. 15 | config.vm.box = "ubuntu/bionic64" 16 | 17 | # Disable automatic box update checking. If you disable this, then 18 | # boxes will only be checked for updates when the user runs 19 | # `vagrant box outdated`. This is not recommended. 20 | # config.vm.box_check_update = false 21 | 22 | # Create a forwarded port mapping which allows access to a specific port 23 | # within the machine from a port on the host machine. In the example below, 24 | # accessing "localhost:8080" will access port 80 on the guest machine. 25 | # NOTE: This will enable public access to the opened port 26 | # config.vm.network "forwarded_port", guest: 80, host: 8080 27 | 28 | # Create a forwarded port mapping which allows access to a specific port 29 | # within the machine from a port on the host machine and only allow access 30 | # via 127.0.0.1 to disable public access 31 | # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1" 32 | 33 | # Create a private network, which allows host-only access to the machine 34 | # using a specific IP. 35 | # config.vm.network "private_network", ip: "192.168.33.10" 36 | 37 | # Create a public network, which generally matched to bridged network. 38 | # Bridged networks make the machine appear as another physical device on 39 | # your network. 40 | # config.vm.network "public_network" 41 | 42 | # Share an additional folder to the guest VM. The first argument is 43 | # the path on the host to the actual folder. The second argument is 44 | # the path on the guest to mount the folder. And the optional third 45 | # argument is a set of non-required options. 46 | # config.vm.synced_folder "../data", "/vagrant_data" 47 | 48 | # Provider-specific configuration so you can fine-tune various 49 | # backing providers for Vagrant. These expose provider-specific options. 50 | # Example for VirtualBox: 51 | # 52 | config.vm.provider "virtualbox" do |vb| 53 | # # Display the VirtualBox GUI when booting the machine 54 | vb.gui = false 55 | # 56 | # Customize the amount of memory on the VM: 57 | vb.memory = "4096" 58 | end 59 | # 60 | # View the documentation for the provider you are using for more 61 | # information on available options. 62 | 63 | # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies 64 | # such as FTP and Heroku are also available. See the documentation at 65 | # https://docs.vagrantup.com/v2/push/atlas.html for more information. 66 | # config.push.define "atlas" do |push| 67 | # push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME" 68 | # end 69 | 70 | # Enable provisioning with a shell script. Additional provisioners such as 71 | # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the 72 | # documentation for more information about their specific syntax and use. 73 | # config.vm.provision "shell", inline: <<-SHELL 74 | # apt-get update 75 | # apt-get install -y apache2 76 | # SHELL 77 | 78 | config.vm.provision "shell", path: "provision.sh", privileged: false 79 | config.vm.provision :reload 80 | end 81 | -------------------------------------------------------------------------------- /utils/vagrant/provision.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Adjust to closest mirrors. 4 | sudo sed -i -e 's/http:\/\/us.archive/mirror:\/\/mirrors/' -e 's/\/ubuntu\//\/mirrors.txt/' /etc/apt/sources.list 5 | 6 | # Standard stuff for fresh system. 7 | sudo apt-get update -y 8 | sudo apt-get upgrade -y -qq # The quiet flag suppresses annoying GRUB interactive. 9 | 10 | # Install to allow apt to use a repository over HTTPS 11 | sudo apt-get install \ 12 | apt-transport-https \ 13 | ca-certificates \ 14 | curl \ 15 | gnupg-agent \ 16 | software-properties-common -y 17 | 18 | # Install pip for Python 3. 19 | sudo apt-get install python3-pip -y 20 | 21 | # Install Node.js. 22 | sudo apt-get install nodejs -y 23 | 24 | # Add Dockerr's official GPG key and set up stable repository 25 | curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - 26 | sudo apt-key fingerprint 0EBFCD88 27 | 28 | sudo add-apt-repository \ 29 | "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ 30 | $(lsb_release -cs) \ 31 | stable" 32 | 33 | # Install latest version of Docker 34 | sudo apt-get update -y 35 | sudo apt-get install docker-ce docker-ce-cli containerd.io -y 36 | 37 | # Add user vagrant to group docker 38 | sudo usermod -aG docker vagrant 39 | 40 | # Clone, build and install Smartbugs 41 | cd ~ 42 | if [ ! -d smartbugs ]; then 43 | git clone https://github.com/smartbugs/smartbugs.git smartbugs 44 | cd smartbugs 45 | pip3 install -r requirements.txt 46 | else 47 | cd smartbugs 48 | git pull 49 | pip3 install -r requirements.txt 50 | fi 51 | 52 | # Use antlr4-python3-runtime v4.7.2 to avoid warnings 53 | pip3 install -Iv antlr4-python3-runtime==4.7.2 54 | 55 | # Change MOTD 56 | 57 | sudo sh -c 'echo "\ 58 | ____ _ ____ 59 | / ___| _ __ ___ __ _ _ __| |_| __ ) _ _ __ _ ___ 60 | \___ \| '"'"'_ \` _ \ / _\` | '"'"'__| __| _ \| | | |/ _\` / __| 61 | ___) | | | | | | (_| | | | |_| |_) | |_| | (_| \__ \ 62 | |____/|_| |_| |_|\__,_|_| \__|____/ \__,_|\__, |___/ 63 | |___/ 64 | 65 | Welcome! SmartBugs usage example: 66 | 67 | cd smartbugs 68 | ./smartBugs.py --dataset reentrancy -t oyente 69 | 70 | For more details and documentation: https://smartbugs.github.io 71 | 72 | " > /etc/motd' 73 | -------------------------------------------------------------------------------- /utils/vagrant/vagrant-box-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anonymous123xx/RLRep/a06f64caa153e22494f5e063dde965044f9b8baf/utils/vagrant/vagrant-box-screenshot.png --------------------------------------------------------------------------------