├── .gitattributes ├── .gitignore ├── .nojekyll ├── INSTALL ├── LICENSE ├── README.md ├── cnerator.py ├── core ├── __init__.py ├── ast.py ├── generators.py ├── operators.py ├── operators_types.py ├── probs.py ├── probs_helper.py ├── type_inference.py └── utils.py ├── debug ├── __init__.py ├── call_inspector.py ├── graph.py └── structure_inspector.py ├── docs ├── .buildinfo ├── .nojekyll ├── _images │ ├── cr.png │ ├── transparent.png │ └── uniovi.png ├── _modules │ ├── cnerator.html │ ├── core │ │ ├── ast.html │ │ ├── generators.html │ │ ├── graph.html │ │ ├── probs.html │ │ ├── probs_helper.html │ │ ├── type_inference.html │ │ └── utils.html │ ├── debug │ │ ├── call_inspector.html │ │ ├── graph.html │ │ └── structure_inspector.html │ ├── index.html │ ├── params │ │ ├── epilog.html │ │ ├── json_probs.html │ │ ├── parameters.html │ │ └── writter.html │ └── visitors │ │ ├── fix_ptr_literal.html │ │ ├── func_to_proc.html │ │ ├── function_subs.html │ │ └── return_instrumentation.html ├── _sources │ ├── cnerator.rst.txt │ ├── core.rst.txt │ ├── debug.rst.txt │ ├── getting_started.rst.txt │ ├── index.rst.txt │ ├── modules.rst.txt │ ├── params.rst.txt │ ├── run.rst.txt │ ├── setup.rst.txt │ ├── user_manual.rst.txt │ └── visitors.rst.txt ├── _static │ ├── basic.css │ ├── cr.png │ ├── css │ │ ├── badge_only.css │ │ ├── fonts │ │ │ ├── Roboto-Slab-Bold.woff │ │ │ ├── Roboto-Slab-Bold.woff2 │ │ │ ├── Roboto-Slab-Regular.woff │ │ │ ├── Roboto-Slab-Regular.woff2 │ │ │ ├── fontawesome-webfont.eot │ │ │ ├── fontawesome-webfont.svg │ │ │ ├── fontawesome-webfont.ttf │ │ │ ├── fontawesome-webfont.woff │ │ │ ├── fontawesome-webfont.woff2 │ │ │ ├── lato-bold-italic.woff │ │ │ ├── lato-bold-italic.woff2 │ │ │ ├── lato-bold.woff │ │ │ ├── lato-bold.woff2 │ │ │ ├── lato-normal-italic.woff │ │ │ ├── lato-normal-italic.woff2 │ │ │ ├── lato-normal.woff │ │ │ └── lato-normal.woff2 │ │ └── theme.css │ ├── doctools.js │ ├── documentation_options.js │ ├── file.png │ ├── footer.html │ ├── jquery-3.5.1.js │ ├── jquery.js │ ├── js │ │ ├── badge_only.js │ │ ├── html5shiv-printshiv.min.js │ │ ├── html5shiv.min.js │ │ └── theme.js │ ├── language_data.js │ ├── minus.png │ ├── plus.png │ ├── pygments.css │ ├── searchtools.js │ ├── transparent-cr.png │ ├── transparent.png │ ├── underscore-1.3.1.js │ ├── underscore.js │ └── uniovi.png ├── cnerator.html ├── core.html ├── debug.html ├── genindex.html ├── getting_started.html ├── index.html ├── modules.html ├── objects.inv ├── params.html ├── py-modindex.html ├── run.html ├── search.html ├── searchindex.js ├── setup.html ├── user_manual.html └── visitors.html ├── json ├── functions │ ├── 1-function-each-type.json │ ├── 15-function-each-type.json │ ├── 150-functions-total.json │ ├── 2000-function-void-no-void.json │ ├── 300-function-each-type.json │ ├── 3000-functions-total.json │ ├── article.json │ └── n-functions.json └── probabilities │ ├── article.json │ └── example_probs.json ├── params ├── __init__.py ├── epilog.py ├── json_probs.py ├── parameters.py └── writter.py ├── requirements.txt ├── run ├── 15_function_each_type.py ├── 1_function_each_type.py ├── 2000_function_void_no_void.py ├── 300_function_each_type.py ├── __init__.py ├── article.py ├── defaults.py ├── defaults_one_file.py ├── help.py ├── probs.py └── probs_file.py ├── sphinx ├── Makefile ├── _build │ ├── doctrees │ │ ├── cnerator.doctree │ │ ├── core.doctree │ │ ├── debug.doctree │ │ ├── environment.pickle │ │ ├── getting_started.doctree │ │ ├── index.doctree │ │ ├── modules.doctree │ │ ├── params.doctree │ │ ├── run.doctree │ │ ├── user_manual.doctree │ │ └── visitors.doctree │ └── html │ │ ├── .buildinfo │ │ ├── _modules │ │ ├── cnerator.html │ │ ├── core │ │ │ ├── ast.html │ │ │ ├── generators.html │ │ │ ├── probs.html │ │ │ ├── probs_helper.html │ │ │ ├── type_inference.html │ │ │ └── utils.html │ │ ├── debug │ │ │ ├── call_inspector.html │ │ │ └── structure_inspector.html │ │ ├── index.html │ │ ├── params │ │ │ ├── epilog.html │ │ │ ├── json_probs.html │ │ │ ├── parameters.html │ │ │ └── writter.html │ │ └── visitors │ │ │ ├── fix_ptr_literal.html │ │ │ ├── func_to_proc.html │ │ │ ├── function_subs.html │ │ │ └── return_instrumentation.html │ │ ├── _sources │ │ ├── cnerator.rst.txt │ │ ├── core.rst.txt │ │ ├── debug.rst.txt │ │ ├── getting_started.rst.txt │ │ ├── index.rst.txt │ │ ├── modules.rst.txt │ │ ├── params.rst.txt │ │ ├── run.rst.txt │ │ ├── user_manual.rst.txt │ │ └── visitors.rst.txt │ │ ├── _static │ │ ├── basic.css │ │ ├── cr.png │ │ ├── css │ │ │ ├── badge_only.css │ │ │ ├── fonts │ │ │ │ ├── Roboto-Slab-Bold.woff │ │ │ │ ├── Roboto-Slab-Bold.woff2 │ │ │ │ ├── Roboto-Slab-Regular.woff │ │ │ │ ├── Roboto-Slab-Regular.woff2 │ │ │ │ ├── fontawesome-webfont.eot │ │ │ │ ├── fontawesome-webfont.svg │ │ │ │ ├── fontawesome-webfont.ttf │ │ │ │ ├── fontawesome-webfont.woff │ │ │ │ ├── fontawesome-webfont.woff2 │ │ │ │ ├── lato-bold-italic.woff │ │ │ │ ├── lato-bold-italic.woff2 │ │ │ │ ├── lato-bold.woff │ │ │ │ ├── lato-bold.woff2 │ │ │ │ ├── lato-normal-italic.woff │ │ │ │ ├── lato-normal-italic.woff2 │ │ │ │ ├── lato-normal.woff │ │ │ │ └── lato-normal.woff2 │ │ │ └── theme.css │ │ ├── doctools.js │ │ ├── documentation_options.js │ │ ├── file.png │ │ ├── jquery-3.5.1.js │ │ ├── jquery.js │ │ ├── js │ │ │ ├── badge_only.js │ │ │ ├── html5shiv-printshiv.min.js │ │ │ ├── html5shiv.min.js │ │ │ └── theme.js │ │ ├── language_data.js │ │ ├── minus.png │ │ ├── plus.png │ │ ├── pygments.css │ │ ├── searchtools.js │ │ ├── underscore-1.3.1.js │ │ ├── underscore.js │ │ └── uniovi.png │ │ ├── cnerator.html │ │ ├── core.html │ │ ├── debug.html │ │ ├── genindex.html │ │ ├── getting_started.html │ │ ├── index.html │ │ ├── modules.html │ │ ├── objects.inv │ │ ├── params.html │ │ ├── py-modindex.html │ │ ├── run.html │ │ ├── search.html │ │ ├── searchindex.js │ │ ├── user_manual.html │ │ └── visitors.html ├── _static │ ├── cr.png │ ├── transparent.png │ └── uniovi.png ├── cnerator.rst ├── conf.py ├── core.rst ├── debug.rst ├── getting_started.rst ├── index.rst ├── make.bat ├── modules.rst ├── params.rst ├── run.rst ├── user_manual.rst └── visitors.rst ├── user-manual.md └── visitors ├── __init__.py ├── fix_ptr_literal.py ├── func_to_proc.py ├── function_subs.py └── return_instrumentation.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.c filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # PyBuilder 72 | .pybuilder/ 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | # For a library or package, you might want to ignore these files since the code is 84 | # intended to run in multiple environments; otherwise, check them in: 85 | # .python-version 86 | ======= 87 | .python-version 88 | >>>>>>> 892da8f00d4ce0b5f981ca1329f6b076693c0ad7 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | 140 | 141 | 142 | # Mac OS X 143 | .DS_Store 144 | # Generated files 145 | out/ 146 | # Pycharm config dir 147 | .idea/ 148 | 149 | # Sphinx documentation 150 | sphinx/_build/ 151 | 152 | scratch.py 153 | out/ -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/.nojekyll -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | pip install numpy 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2020, Computational Reflection 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cnerator 2 | 3 | 4 | [![License](https://img.shields.io/github/license/ComputationalReflection/cnerator)](LICENSE) 5 | [![Latest release](https://img.shields.io/github/v/release/computationalreflection/cnerator?include_prereleases)](https://github.com/ComputationalReflection/cnerator/releases) 6 | [![Documentation](https://img.shields.io/static/v1?label=docs&message=Sphinx&color=blue)](https://computationalreflection.github.io/Cnerator/) 7 | Code size 8 | Repo size 9 | 10 | 11 | Cnerator is a C source code generation tool. It can be used to generate large amounts of 12 | [standard ANSI/ISO C source code](https://www.iso.org/standard/74528.html), ready to be compiled 13 | by any standard language implementation. 14 | Cnerator is highly customizable to generate all the syntactic constructs of the C language, necessary to build 15 | accurate predictive models with machine learning algorithms. 16 | 17 | ## Functionalities 18 | 19 | These are the main functionalities provided by Cnerator: 20 | 21 | 1. _ANSI/ISO standard C_. All the source code generated by Cnerator follows the ISO/IEC 9899:2018 (C17) 22 | standard specification. 23 | 24 | 2. _Probabilistic randomness_. C language constructs are randomly generated, following different probability 25 | distributions specified by the user. For example, it is possible to describe the probability of each statement 26 | and expression construct, the number of statements in a function, and the types of their arguments and return values. 27 | To this aim, the user can specify fixed probabilities of each element, or use different probability distributions, 28 | such as normal, uniform and direct and inverse proportional. 29 | 30 | 3. _Compilable code_. The generated code strictly follows the syntax grammar, type system and semantic 31 | rules of the C programming language. In this way, the generated code has been checked to be compilable 32 | by any standard compiler implementation. 33 | 34 | 4. _Highly customizable_. Many features of the programs to be generated are customizable. 35 | Some examples include the types of each language construct, array dimensions and sizes, struct fields, 36 | maximum depth of expression and statement trees, number of function parameters and statements, 37 | global and local variables, structures of control flow statements and type promotions, 38 | among others –see the detailed [documentation](user-manual.md). 39 | 40 | 5. _Large amounts of code_. Cnerator is designed to allow generating large amounts of C source code. 41 | A parameter indicates the number of independent compilation units to be created for the output application, 42 | so that each unit could be treated as an independently compilable module. This feature, together with the 43 | probabilistic randomness, make Cnerator an ideal tool to create predictive models of source code, because 44 | the input programs used to train such models comprise abundant and varied code patterns. 45 | 46 | ## Usage 47 | 48 | To run Cnerator, you need to install the `numpy` Python package: 49 | 50 | 51 | ``` text 52 | pip install numpy 53 | ``` 54 | 55 | Then, you may just run Cnerator with no arguments to generate a random C program: 56 | 57 | 58 | ``` text 59 | python cnerator.py 60 | ``` 61 | 62 | There are plenty of options to customize Cnerator. To specify the probability of a particular language 63 | construct, you can use the `-p` or `--probs` option. 64 | The following command sets to 20% the probability of 65 | generating a function invocation when a new expression is required: 66 | 67 | ``` text 68 | python cnerator.py -p "call_prob = {True: 0.2, False: 0.8}" 69 | ``` 70 | 71 | If more sophisticated probabilities are required, you can specify them in a JSON file and pass it as 72 | a parameter (see the [documentation](user-manual.md#probability-specification-files) to know the JSON file format). 73 | The following line passes an example JSON file in the `json/probabilities` folder where 74 | different probability distributions are specified for some syntactic constructs: 75 | 76 | ``` text 77 | python cnerator.py -P json/probabilities/example_probs.json 78 | ``` 79 | 80 | Cnerator also provides allows the user to control the number and characteristics of 81 | all the functions to be generated. A JSON file is used for that purpose 82 | (see the [documentation](user-manual.md#function-generation-files)). 83 | The following command makes Cnerator generate one function for each high-level return 84 | type in the C programming language: 85 | 86 | 87 | ``` text 88 | python cnerator.py -f json/functions/1-function-each-type.json 89 | ``` 90 | 91 | Sometimes, the user needs the output program to fulfill some requirements not guaranteed by the 92 | stochastic generation process. 93 | To this aim, Cnerator allows the specification of an ordered collection of Python 94 | post-process specification files (see the [documentation](user-manual.md#post-processing-specification-files)). 95 | These post-processing files can modify the generated code to satisfy those requirements. 96 | The following execution generates a random program and then executes two visitors: 97 | one to rename `func` functions to `proc` (and their invocations) when they return `void`; 98 | and another one to add a `__RETURN__` label before each return statement: 99 | 100 | ``` text 101 | python cnerator.py -V visitors.func_to_proc:visitors.return_instrumentation 102 | ``` 103 | 104 | To see all the options, just run the `-h` or `--help` options. 105 | For more information, please check the [documentation](user-manual.md). 106 | Developer documentation is also provided [here](https://computationalreflection.github.io/Cnerator). 107 | 108 | 109 | ## Documentation 110 | 111 | * Check out the [user manual](user-manual.md) about how to use Cnerator. 112 | 113 | * A [developer manual](https://computationalreflection.github.io/Cnerator) is also available 114 | if you want to modify the source code. 115 | 116 | ## License 117 | 118 | [BSD 3 clause license](LICENSE) -------------------------------------------------------------------------------- /cnerator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This is the entry point to the Cnerator source code generation tool. 6 | The main function runs Cnerator. 7 | To see the different arguments provided, run Cnerator with either ``-h`` or ``--help`` command line arguments. 8 | """ 9 | 10 | from __future__ import print_function 11 | 12 | import os 13 | import sys 14 | 15 | from debug import call_inspector, structure_inspector 16 | from params import parameters 17 | from params.parameters import parse_args, get_modules_to_import, get_probs_to_override 18 | from params.writter import write_in_files 19 | from params import json_probs 20 | import core 21 | 22 | 23 | def run(args): 24 | """ 25 | This function runs Cnerator, receiving the command line arguments. 26 | 27 | :param args: The command line arguments returned by ``argparse.ArgumentParser.parse_args``. 28 | :return: None. 29 | """ 30 | # Set the recursion limit 31 | sys.setrecursionlimit(args.recursion) 32 | 33 | # Get the probabilities from the command line arguments and modify the default ones 34 | core.probs.set_probabilities(get_probs_to_override(args.probs)) 35 | if args.probsfile: 36 | from core import probs 37 | probabilities = json_probs.parse_probabilities_specification_json_file(args.probsfile) 38 | probs.set_probabilities(probabilities) 39 | 40 | # Process the json file to create functions, or generates a program using the probabilities defined 41 | if args.functions: # if a json file was passed, it defines the functions to be generated 42 | dictionary = parameters.parse_function_specification_json_file(args.functions) 43 | program = core.generators.generate_program_with_function_distribution(dictionary, args, remove_unwanted_functions=True) 44 | else: # otherwise, a random program is generated, considering the specified probabilities 45 | program = core.generators.generate_program() 46 | 47 | # Load all the visitor modules and run them, in the same order as specified by the user 48 | modules = get_modules_to_import(args.visitors) 49 | for module in modules: 50 | module.visit(program) 51 | 52 | # Create output directory 53 | if not os.path.isdir(args.output_dir): 54 | os.mkdir(args.output_dir) 55 | 56 | # Write code to files 57 | write_in_files(program, args) 58 | 59 | # Write debug graph information 60 | if args.debug: 61 | # Write structure graph 62 | structure_inspector.write_graph(program, os.path.join(args.output_dir, args.output + ".structure.dot")) 63 | # Write call graph 64 | call_inspector.write_graph(program, True, os.path.join(args.output_dir, args.output + ".call.dot")) 65 | call_inspector.write_graph(program, False, os.path.join(args.output_dir, args.output + ".call_light.dot")) 66 | 67 | 68 | def main(): 69 | """Main function. 70 | To see the different arguments provided, run Cnerator with either ``-h`` or ``--help`` command line arguments. 71 | """ 72 | exit(run(parse_args())) 73 | 74 | 75 | if __name__ == "__main__": 76 | main() 77 | 78 | 79 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This is the most important package in Cnerator, which provides the core functionality. 6 | In this package, you can find the Abstract Syntax Tree (AST) program representation, 7 | the generators of each syntactic construct, type inference routines, probability specifications and 8 | different utilities provided by the system. 9 | """ 10 | 11 | from core import generators 12 | from core import probs -------------------------------------------------------------------------------- /core/probs_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | These functions are used to define the probability of the different syntax constructs of the C language. 6 | Probabilities are defined as Dict[object, float], where the key are the different values to be generated and the 7 | content defines the probability for each one. 8 | All the probabilities (contents of the dictionary) must sum 0.0. 9 | """ 10 | 11 | import random 12 | from typing import Dict, List 13 | import numpy as np 14 | 15 | 16 | FLOAT_PRECISION = 1e-8 17 | 18 | 19 | def random_value(probabilities: Dict[object, float]): 20 | """Returns one of the values in probabilities (key) given its probability (content)""" 21 | if abs(sum(probabilities.values()) - 1.0) > FLOAT_PRECISION: 22 | raise Exception("Probability must sum 1") 23 | rand = random.random() 24 | summation = 0 25 | for key, value in probabilities.items(): 26 | if summation <= rand < summation + value: 27 | return key 28 | summation += value 29 | return probabilities[probabilities.keys()[-1]] 30 | 31 | 32 | def compute_equal_prob(keys: set, base: float = 1.0) -> Dict[object, float]: 33 | """Given a list of elements (keys) returns a dictionary with the equal probabilities for all the elements""" 34 | probabilities = {} 35 | for key in keys: 36 | probabilities[key] = base * (1.0 / len(keys)) 37 | return probabilities 38 | 39 | 40 | def compute_proportional_prob(population: Dict[object, float], base: float = 1.0) -> Dict[object, float]: 41 | """Given a dictionary of elements and their proportional occurrence, returns a dictionary with its probability 42 | distribution. For example, {'a':1, 'b':2, c:'1'} returns {'a':0.25, 'b':0.5, c:'0.25'} """ 43 | probabilities = {} 44 | total = float(sum(population.values())) 45 | for individual, amount in population.items(): 46 | probabilities[individual] = base * (amount / total) 47 | assert abs(1.0 - sum(probabilities.values())) <= FLOAT_PRECISION 48 | return probabilities 49 | 50 | 51 | def compute_inverse_proportional_prob(population: Dict[object, float], base: float = 1.0) -> Dict[object, float]: 52 | """Given a dictionary of elements and their inverse proportional occurrence, returns a dictionary with its 53 | probability distribution. For example, {'a':1, 'b':2, c:'2'} returns {'a':0.5, 'b':0.25, 'c':0.25} """ 54 | probabilities = {} 55 | total = 0 56 | for individual, amount in population.items(): 57 | probabilities[individual] = 1.0 / amount 58 | total += probabilities[individual] 59 | for individual, prob in probabilities.items(): 60 | probabilities[individual] = base * (prob / total) 61 | assert abs(1.0 - sum(probabilities.values())) <= FLOAT_PRECISION 62 | return probabilities 63 | 64 | 65 | def compute_normal_prob(mean: int, stdev: int, base: float = 1.0, number: int = 30) -> Dict[object, float]: 66 | """Given the mean and standard deviation, returns a dictionary a normal distribution""" 67 | float_values = np.random.normal(mean, stdev, size=number) 68 | int_values = [int(float_value) for float_value in float_values] 69 | frequencies = {int_value: int_values.count(int_value) for int_value in int_values} 70 | return compute_proportional_prob(frequencies, base) 71 | 72 | 73 | -------------------------------------------------------------------------------- /core/type_inference.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Different functions to infer the type of a syntax construct. 6 | This module heavily depends on the data provided in the ``operators_types`` module. 7 | """ 8 | 9 | from functools import partial 10 | 11 | from core import probs, operators_types, probs_helper, generators, ast 12 | 13 | 14 | def infer_return_type(program, function, operator, *args_t): 15 | arity = len(args_t) 16 | _generate_type = partial(generators.generate_type, program, function) 17 | 18 | if operator == "*" and arity == 1: 19 | assert args_t[0].__class__ == ast.Pointer 20 | return [args_t[0].type] 21 | 22 | if operator == "&" and arity == 1: 23 | return _generate_type(ast.Pointer, args_t[0]) 24 | 25 | if operator == "[]": 26 | assert arity == 2 27 | assert args_t[0].__class__ == ast.Array 28 | assert args_t[1].__class__ in [t for t in probs.primitive_types_prob.keys() if "Int" in t.__name__] 29 | return [args_t[0].type] 30 | 31 | if operator == ".": 32 | assert arity == 1 33 | assert args_t[0].__class__ == ast.Struct 34 | assert isinstance(args_t[1], str) 35 | return [args_t[0].get_field(args_t[1])] 36 | 37 | if operator == "->": 38 | assert arity == 1 39 | assert args_t[0].__class__ == ast.Pointer 40 | assert args_t[0].type.__class__ == ast.Struct 41 | assert isinstance(args_t[1], str) 42 | return [args_t[0].type.get_type_by_field(args_t[1])] 43 | 44 | if operator == "?:": 45 | assert arity == 3 46 | assert args_t[0].__class__ in [t for t in probs.primitive_types_prob.keys() if "Int" in t.__name__] 47 | assert args_t[1].__class__ == args_t[2].__class__ 48 | return [args_t[1]] 49 | 50 | if operator == "=": 51 | assert arity == 1 52 | assert not isinstance(args_t[0], ast.Array) 53 | return [args_t[0]] 54 | 55 | return list(_infer_return_type(program, function, operator, *args_t)) 56 | 57 | 58 | def _infer_return_type(program, function, operator, *args_t): 59 | arity = len(args_t) 60 | _generate_type = partial(generators.generate_type, program, function) 61 | 62 | # Otherwise search on the table 63 | try: 64 | selected_arity = operators_types.by_operands[arity] 65 | except KeyError: 66 | raise ValueError("Unknown arity '{}'".format(arity)) 67 | try: 68 | selected_operator = selected_arity[operator] 69 | except KeyError: 70 | raise ValueError("Unknown operator '{}'".format(operator)) 71 | 72 | last_selected_arg = selected_operator 73 | for pos, arg in enumerate(args_t): 74 | try: 75 | last_selected_arg = last_selected_arg[arg.__class__] 76 | except KeyError: 77 | raise ValueError("In arg '{}'. Unknown type in arg {} '{}'".format( 78 | arg, pos, arg.__class__.__name__)) 79 | ret_ts_cls = last_selected_arg 80 | 81 | # And return one of the types 82 | for ret_t_cls in ret_ts_cls: 83 | if ret_t_cls is ast.Pointer: 84 | if arity == 1: 85 | assert args_t[0].__class__ is ast.Pointer 86 | yield _generate_type(ast.Pointer, args_t[0].type) 87 | elif arity == 2: 88 | if args_t[0].__class__ is ast.Pointer: 89 | yield _generate_type(ast.Pointer, args_t[0].type) 90 | elif args_t[1].__class__ is ast.Pointer: 91 | yield _generate_type(ast.Pointer, args_t[1].type) 92 | else: 93 | raise ValueError("Unknown operation with Pointers") 94 | else: 95 | yield ret_t_cls() # Direct call to constructor because are basic types 96 | 97 | 98 | def infer_operands_type(program, function, arity, operator, ret_t): 99 | _generate_type = partial(generators.generate_type, program, function) 100 | 101 | if operator == "*" and arity == 1: 102 | return [_generate_type(ast.Pointer, ret_t)] 103 | 104 | if operator == "&" and arity == 1: 105 | assert ret_t.__class__ == ast.Pointer 106 | # Pointer(T) <- & T 107 | return [ret_t.type] 108 | 109 | if operator == "[]": 110 | assert arity == 2 111 | array_obj = _generate_type(ast.Array, ret_t) 112 | return [(array_obj, t()) for t in probs.primitive_types_prob.keys() if "Int" in t.__name__] 113 | 114 | if operator == ".": 115 | assert arity == 1 116 | return [_generate_type(ast.Struct, ret_t)] 117 | 118 | if operator == "->": 119 | assert arity == 1 120 | struct_t = _generate_type(ast.Struct, ret_t) 121 | return [_generate_type(ast.Pointer, struct_t)] 122 | 123 | if operator == "?:": 124 | assert arity == 3 125 | return [(ast.SignedInt(), ret_t, ret_t)] 126 | 127 | if operator == "=": 128 | assert arity == 1 129 | assert not isinstance(ret_t, ast.Array) 130 | return [ret_t] 131 | 132 | return _infer_operands_type(program, function, arity, operator, ret_t) 133 | 134 | 135 | def _infer_operands_type(program, function, arity, operator, ret_t): 136 | _generate_type = partial(generators.generate_type, program, function) 137 | 138 | # Otherwise search on the table 139 | try: 140 | selected_arity = operators_types.by_return[arity] 141 | except KeyError: 142 | raise ValueError("Unknown arity '{}'".format(arity)) 143 | try: 144 | selected_operator = selected_arity[operator] 145 | except KeyError: 146 | raise ValueError("Unknown operator '{}'".format(operator)) 147 | try: 148 | args_t = selected_operator[ret_t.__class__] 149 | except KeyError: 150 | raise ValueError("There's no {} that use the operator '{}' and return '{}'".format( 151 | "type" if arity == 1 else "types", operator, ret_t.__class__.__name__)) 152 | 153 | # And return one of the types 154 | if ret_t.__class__ in [ast.Pointer, ast.Array]: 155 | type_obj = ret_t.type 156 | else: 157 | type_cls = probs_helper.random_value(probs.primitive_types_prob) 158 | type_obj = type_cls() 159 | if arity == 1: 160 | return [_generate_type(arg_t, type_obj) for arg_t in args_t] 161 | if arity == 2: 162 | return [(_generate_type(arg1_t, type_obj), _generate_type(arg2_t, type_obj)) for arg1_t, arg2_t in args_t] 163 | raise AssertionError("Unknown arity") 164 | -------------------------------------------------------------------------------- /core/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Different general-purpose functions used in the implementation of the core library. 6 | """ 7 | 8 | import re 9 | import sys 10 | 11 | from params.parameters import get_app_args 12 | 13 | 14 | def camel_case_to_snake_case(name: str) -> str: 15 | """Converts a camel-case string into its snake-case representation""" 16 | s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name) 17 | return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1).lower() 18 | 19 | 20 | def print_to_std_error(*args, sep=' ', end='\n'): 21 | """This function wraps the print Python function to show something in the 22 | standard output error""" 23 | print(*args, sep=sep, end=end, file=sys.stderr) 24 | 25 | 26 | def print_if_verbose(*args, sep=' ', end='\n', file=None): 27 | """Prints a message if the verbose option has been passed to the application""" 28 | if get_app_args().verbose: 29 | print(*args, sep=sep, end=end, file=file) 30 | -------------------------------------------------------------------------------- /debug/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This package stores different program information (call graphs and struct representations) 6 | as graphs and saves them as .dot files. 7 | Such functionality only occurs when the ``-d`` or ``--debug`` options are passed from the command line. 8 | """ 9 | 10 | -------------------------------------------------------------------------------- /debug/call_inspector.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | A visitor implementation that stores a representation of the calling graph into a text stream. 6 | Its use is for debugging purposes, to check the structure of the generated program. 7 | """ 8 | 9 | from __future__ import print_function 10 | from __future__ import unicode_literals 11 | 12 | import io 13 | 14 | from functools import singledispatch 15 | 16 | from core import ast 17 | 18 | global_visit_main = True 19 | 20 | def write_graph(program, visit_main, path): 21 | with io.open(path, mode="w", encoding="utf-8") as buffer: 22 | buffer.write("digraph G {\n") 23 | buffer.write('graph [rankdir = "LR", orientation = "landscape", ranksep = 3.0, nodesep= 2.0];\n') 24 | buffer.write('node [fontsize = "8", style = "filled", color = "blue"];\n') 25 | buffer.write('edge [fontsize = "8", weight = 0.1];\n') 26 | # buffer.write('main [style = "filled", color = "red"];\n') 27 | edges = [] 28 | nodes = [] 29 | 30 | global global_visit_main 31 | global_visit_main = visit_main 32 | 33 | callinsp_visit(program, nodes, edges) 34 | for e in edges: 35 | buffer.write(e + "\n") 36 | for n in nodes: 37 | buffer.write(n + "\n") 38 | buffer.write("}\n") 39 | 40 | 41 | @singledispatch 42 | def callinsp_visit(node, nodes, edges, *args, **kwargs): 43 | raise TypeError("Unknown node type: " + node.__class__.__name__) 44 | 45 | 46 | @callinsp_visit.register(ast.Program) 47 | def _(program, nodes, edges): 48 | for f in program.functions: 49 | callinsp_visit(f, nodes, edges) 50 | if global_visit_main: 51 | callinsp_visit(program.main, nodes, edges) 52 | 53 | 54 | @callinsp_visit.register(ast.Function) 55 | def _(function, nodes, edges): 56 | if function.name == "main": 57 | color = "tomato" 58 | elif function.name.startswith("func"): 59 | color = "steelblue1" 60 | elif function.name.startswith("proc"): 61 | color = "greenyellow" 62 | else: 63 | raise AssertionError("Unknown type of function") 64 | 65 | nodes.append('{} [color = "{}"];'.format(function.name, color)) 66 | for s in function.stmts: 67 | callinsp_visit(s, nodes, edges, function.name, function) 68 | 69 | 70 | @callinsp_visit.register(ast.Invocation) 71 | def _(invocation, nodes, edges, func_name, parent): 72 | comment = " " 73 | if isinstance(parent, ast.Function): 74 | comment = " /* stmt invocation */" 75 | else: 76 | comment = " /* expr invocation */" 77 | edges.append("{} -> {}{}".format(func_name, invocation.func_name, comment)) 78 | 79 | if invocation.arguments: 80 | for arg in invocation.arguments: 81 | if isinstance(arg, ast.ASTNode): 82 | callinsp_visit(arg, nodes, edges, func_name, invocation) 83 | 84 | 85 | @callinsp_visit.register(ast.BinaryExpression) 86 | @callinsp_visit.register(ast.Assignment) 87 | @callinsp_visit.register(ast.ArrayAccessExpression) 88 | @callinsp_visit.register(ast.Return) 89 | @callinsp_visit.register(ast.UnaryExpression) 90 | @callinsp_visit.register(ast.StructAccessExpression) 91 | @callinsp_visit.register(ast.TernaryExpression) 92 | def _(node, nodes, edges, func_name, parent): 93 | for exp in node.children: 94 | if isinstance(exp, ast.ASTNode): 95 | callinsp_visit(exp, nodes, edges, func_name, node) 96 | 97 | @callinsp_visit.register(ast.Literal) 98 | @callinsp_visit.register(ast.Variable) 99 | @callinsp_visit.register(ast.Label) 100 | def _(node, nodes, edges, func_name, parent): 101 | pass 102 | -------------------------------------------------------------------------------- /debug/structure_inspector.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Stores in a text stream the representation of the struct data types in the generated program. 6 | Its use is for debugging purposes, to check the structure of the struct types in the generated program. 7 | """ 8 | 9 | from __future__ import print_function 10 | from __future__ import unicode_literals 11 | 12 | import io 13 | import core 14 | 15 | 16 | def get_struct_name(t): 17 | while True: 18 | if isinstance(t, core.ast.Struct): 19 | return t.name 20 | elif isinstance(t, (core.ast.Pointer, core.ast.Array)): 21 | t = t.type 22 | else: 23 | return None 24 | 25 | 26 | def write_graph(program, path): 27 | 28 | def get_color(t): 29 | if t.name.startswith("array"): 30 | return ' bgcolor="steelblue1"' 31 | if t.name.startswith("pointer"): 32 | return ' bgcolor="tomato"' 33 | if t.name.startswith("struct"): 34 | return ' bgcolor="greenyellow"' 35 | return "" 36 | 37 | with io.open(path, mode="w", encoding="utf-8") as buffer: 38 | 39 | buffer.write("digraph G {\n") 40 | buffer.write('graph [rankdir = "LR"];\n') 41 | buffer.write('node [fontsize = "8"];\n') 42 | buffer.write('edge [fontsize = "8"];\n') 43 | 44 | # Write nodes 45 | for s in program.structs: 46 | name = s.name 47 | label = """< 48 | \t\t 49 | \t\t{} 50 | \t
{}
>""".format( 51 | name, 52 | "\n\t\t".join('{}'.format( 53 | f, 54 | get_color(t), 55 | t.name) for f, t in s.fields)) 56 | buffer.write('"{}" [\n\tlabel = {}\n\tshape = none\n];\n'.format(name, label)) 57 | 58 | # Write edges 59 | for s in program.structs: 60 | for f, t in s.fields: 61 | name = get_struct_name(t) 62 | if name is not None: 63 | buffer.write('"{}":{} -> "{}":head\n'.format(s.name, f, name)) 64 | 65 | buffer.write("}\n") 66 | -------------------------------------------------------------------------------- /docs/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 0955bf54aa55ff5c9a24cfc47ed04c59 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/.nojekyll -------------------------------------------------------------------------------- /docs/_images/cr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_images/cr.png -------------------------------------------------------------------------------- /docs/_images/transparent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_images/transparent.png -------------------------------------------------------------------------------- /docs/_images/uniovi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_images/uniovi.png -------------------------------------------------------------------------------- /docs/_modules/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Overview: module code — Cnerator latest documentation 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 | 101 | 102 |
103 | 104 | 105 | 111 | 112 | 113 |
114 | 115 |
116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |
136 | 137 |
    138 | 139 |
  • »
  • 140 | 141 |
  • Overview: module code
  • 142 | 143 | 144 |
  • 145 | 146 |
  • 147 | 148 |
149 | 150 | 151 |
152 |
153 |
154 | 178 | 179 |
180 | 200 |
201 |
202 | 203 |
204 | 205 |
206 | 207 | 208 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | -------------------------------------------------------------------------------- /docs/_sources/cnerator.rst.txt: -------------------------------------------------------------------------------- 1 | Cnerator module 2 | =============== 3 | 4 | .. automodule:: cnerator 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/_sources/core.rst.txt: -------------------------------------------------------------------------------- 1 | core package 2 | ============ 3 | 4 | .. automodule:: core 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | core.ast module 13 | --------------- 14 | 15 | .. automodule:: core.ast 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | core.generators module 21 | ---------------------- 22 | 23 | .. automodule:: core.generators 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | 29 | core.operators module 30 | --------------------- 31 | 32 | .. automodule:: core.operators 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | core.operators\_types module 38 | ---------------------------- 39 | 40 | .. automodule:: core.operators_types 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | core.probs module 46 | ----------------- 47 | 48 | .. automodule:: core.probs 49 | :members: 50 | :undoc-members: 51 | :show-inheritance: 52 | 53 | core.probs\_helper module 54 | ------------------------- 55 | 56 | .. automodule:: core.probs_helper 57 | :members: 58 | :undoc-members: 59 | :show-inheritance: 60 | 61 | core.type\_inference module 62 | --------------------------- 63 | 64 | .. automodule:: core.type_inference 65 | :members: 66 | :undoc-members: 67 | :show-inheritance: 68 | 69 | core.utils module 70 | ----------------- 71 | 72 | .. automodule:: core.utils 73 | :members: 74 | :undoc-members: 75 | :show-inheritance: 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/_sources/debug.rst.txt: -------------------------------------------------------------------------------- 1 | debug package 2 | ============= 3 | 4 | .. automodule:: debug 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | debug.graph module 13 | ------------------ 14 | 15 | .. automodule:: debug.graph 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | debug.call\_inspector module 21 | ---------------------------- 22 | 23 | .. automodule:: debug.call_inspector 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | debug.structure\_inspector module 29 | --------------------------------- 30 | 31 | .. automodule:: debug.structure_inspector 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | 37 | -------------------------------------------------------------------------------- /docs/_sources/getting_started.rst.txt: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | `Cnerator `_ is a C source code generation tool. 5 | It can be used to generate large amounts of 6 | `standard ANSI/ISO C source code `_, ready to be compiled 7 | by any standard language implementation. 8 | `Cnerator `_ is highly customizable 9 | to generate all the syntactic constructs of the C language, necessary to build 10 | accurate predictive models with machine learning algorithms. 11 | 12 | 13 | Installation 14 | ------------ 15 | 16 | You need a Python 3.7+ standard implementation. 17 | The only additional package to install is ``numpy``: 18 | 19 | 20 | .. code-block:: bash 21 | 22 | pip install numpy 23 | 24 | 25 | Usage 26 | ----- 27 | 28 | Then, you may just run `Cnerator `_ 29 | with no arguments to generate a random C program in the ``out`` directory: 30 | 31 | 32 | .. code-block:: bash 33 | 34 | python cnerator.py 35 | 36 | 37 | There are plenty of options to customize `Cnerator `_. 38 | To specify the probability of a particular language 39 | construct, you can use the ``-p`` or ``--probs`` option. 40 | The following command sets to 20% the probability of 41 | generating a function invocation when a new expression is required: 42 | 43 | .. code-block:: bash 44 | 45 | python cnerator.py -p "call_prob = {True: 0.2, False: 0.8}" 46 | 47 | 48 | If more sophisticated probabilities are required, you can specify them in a JSON file and pass it as 49 | a parameter (see the [documentation](documentation#probability-specification-files) to know the JSON file format). 50 | The following line passes an example JSON file in the ``json/probabilities`` folder where 51 | different probability distributions are specified for some syntactic constructs: 52 | 53 | .. code-block:: bash 54 | 55 | python cnerator.py -P json/probabilities/example_probs.json 56 | 57 | 58 | `Cnerator `_ also provides allows 59 | the user to control the number and characteristics of 60 | all the functions to be generated. A JSON file is used for that purpose 61 | (see the [documentation](documentation#function-generation-files)). 62 | The following command makes `Cnerator `_ 63 | generate one function for each high-level return 64 | type in the C programming language: 65 | 66 | 67 | .. code-block:: bash 68 | 69 | python cnerator.py -f json/functions/1-function-each-type.json 70 | 71 | 72 | Sometimes, the user needs the output program to fulfill some requirements not guaranteed by the 73 | stochastic generation process. 74 | To this aim, `Cnerator `_ allows 75 | the specification of an ordered collection of Python 76 | post-process specification files (see the [documentation](documentation#post-processing-specification-files)). 77 | These post-processing files can modify the generated code to satisfy those requirements. 78 | The following execution generates a random program and then executes two visitors: 79 | one to rename ``func`` functions to ``proc`` (and their invocations) when they return ``void``; 80 | and another one to add a ``__RETURN__`` label before each return statement: 81 | 82 | .. code-block:: bash 83 | 84 | python cnerator.py -V visitors.func_to_proc:visitors.return_instrumentation 85 | 86 | 87 | To see all the options, just run the ``-h`` or ``--help`` options. 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/_sources/index.rst.txt: -------------------------------------------------------------------------------- 1 | .. Cnerator documentation master file, created by 2 | sphinx-quickstart on Wed Jan 20 14:07:57 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Cnerator's documentation! 7 | ==================================== 8 | 9 | .. image:: https://img.shields.io/github/license/ComputationalReflection/cnerator 10 | :alt: License 11 | :target: https://github.com/ComputationalReflection/Cnerator/blob/main/LICENSE 12 | 13 | .. image:: https://img.shields.io/github/v/release/computationalreflection/cnerator?include_prereleases 14 | :alt: Latest release 15 | :target: https://github.com/ComputationalReflection/cnerator/releases 16 | 17 | .. image:: https://img.shields.io/static/v1?label=docs&message=Sphinx&color=blue 18 | :alt: Documentation 19 | :target: https://computationalreflection.github.io/Cnerator/ 20 | 21 | .. image:: https://img.shields.io/github/languages/code-size/computationalreflection/cnerator 22 | :alt: Code size 23 | :target: https://github.com/ComputationalReflection/Cnerator 24 | 25 | .. image:: https://img.shields.io/github/repo-size/computationalreflection/cnerator 26 | :alt: Repo size 27 | :target: https://github.com/ComputationalReflection/Cnerator 28 | 29 | 30 | `Cnerator `_ is a C source code generation tool. 31 | Generated programs can be compiled with any standard ANSI C compiler. 32 | The user may define different parameters such as the number of function to be generated or the probabilities 33 | of all the different syntactic constructs. 34 | 35 | 36 | Contents: 37 | --------- 38 | 39 | .. toctree:: 40 | :maxdepth: 2 41 | 42 | getting_started 43 | user_manual 44 | modules 45 | 46 | 47 | 48 | Indices and tables: 49 | ------------------- 50 | 51 | * :ref:`genindex` 52 | * :ref:`modindex` 53 | 54 | | 55 | 56 | .. image:: _static/transparent.png 57 | :alt: Computational Reflection research group 58 | :align: center 59 | :target: http://www.reflection.uniovi.es 60 | :width: 25% 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/_sources/modules.rst.txt: -------------------------------------------------------------------------------- 1 | Cnerator API 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | cnerator 8 | core 9 | debug 10 | params 11 | run 12 | visitors 13 | -------------------------------------------------------------------------------- /docs/_sources/params.rst.txt: -------------------------------------------------------------------------------- 1 | params package 2 | ============== 3 | 4 | .. automodule:: params 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | params.epilog module 14 | -------------------- 15 | 16 | .. automodule:: params.epilog 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | params.json\_probs module 22 | ------------------------- 23 | 24 | .. automodule:: params.json_probs 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | params.parameters module 30 | ------------------------ 31 | 32 | .. automodule:: params.parameters 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | params.writter module 38 | --------------------- 39 | 40 | .. automodule:: params.writter 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/_sources/run.rst.txt: -------------------------------------------------------------------------------- 1 | run package 2 | =========== 3 | 4 | .. automodule:: run 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | run.1\-function\-each\-type module 13 | ---------------------------------- 14 | 15 | .. automodule:: run.1_function_each_type 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | run.15\-function\-each\-type module 21 | ----------------------------------- 22 | 23 | .. automodule:: run.15_function_each_type 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | run.2000\-function\-void\-no\-void module 29 | ----------------------------------------- 30 | 31 | .. automodule:: run.2000_function_void_no_void 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | run.300\-function\-each\-type module 37 | ------------------------------------ 38 | 39 | .. automodule:: run.300_function_each_type 40 | :members: 41 | :undoc-members: 42 | :show-inheritance: 43 | 44 | run.article module 45 | ------------------ 46 | 47 | .. automodule:: run.article 48 | :members: 49 | :undoc-members: 50 | :show-inheritance: 51 | 52 | run.defaults module 53 | ------------------- 54 | 55 | .. automodule:: run.defaults 56 | :members: 57 | :undoc-members: 58 | :show-inheritance: 59 | 60 | run.defaults\_one\_file module 61 | ------------------------------ 62 | 63 | .. automodule:: run.defaults_one_file 64 | :members: 65 | :undoc-members: 66 | :show-inheritance: 67 | 68 | run.help module 69 | --------------- 70 | 71 | .. automodule:: run.help 72 | :members: 73 | :undoc-members: 74 | :show-inheritance: 75 | 76 | run.probs module 77 | ---------------- 78 | 79 | .. automodule:: run.probs 80 | :members: 81 | :undoc-members: 82 | :show-inheritance: 83 | 84 | run.probs\_file module 85 | ---------------------- 86 | 87 | .. automodule:: run.probs_file 88 | :members: 89 | :undoc-members: 90 | :show-inheritance: 91 | 92 | -------------------------------------------------------------------------------- /docs/_sources/setup.rst.txt: -------------------------------------------------------------------------------- 1 | setup module 2 | ============ 3 | 4 | .. automodule:: setup 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/_sources/visitors.rst.txt: -------------------------------------------------------------------------------- 1 | visitors package 2 | ================ 3 | 4 | .. automodule:: visitors 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | visitors.fix\_ptr\_literal module 14 | --------------------------------- 15 | 16 | .. automodule:: visitors.fix_ptr_literal 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | visitors.func\_to\_proc module 22 | ------------------------------ 23 | 24 | .. automodule:: visitors.func_to_proc 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | visitors.function\_subs module 30 | ------------------------------ 31 | 32 | .. automodule:: visitors.function_subs 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | visitors.return\_instrumentation module 38 | --------------------------------------- 39 | 40 | .. automodule:: visitors.return_instrumentation 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | -------------------------------------------------------------------------------- /docs/_static/cr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/cr.png -------------------------------------------------------------------------------- /docs/_static/css/badge_only.css: -------------------------------------------------------------------------------- 1 | .fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-style:normal;font-weight:400;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#FontAwesome) format("svg")}.fa:before{font-family:FontAwesome;font-style:normal;font-weight:400;line-height:1}.fa:before,a .fa{text-decoration:inherit}.fa:before,a .fa,li .fa{display:inline-block}li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before,.icon-book:before{content:"\f02d"}.fa-caret-down:before,.icon-caret-down:before{content:"\f0d7"}.fa-caret-up:before,.icon-caret-up:before{content:"\f0d8"}.fa-caret-left:before,.icon-caret-left:before{content:"\f0d9"}.fa-caret-right:before,.icon-caret-right:before{content:"\f0da"}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60}.rst-versions .rst-current-version:after{clear:both;content:"";display:block}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} -------------------------------------------------------------------------------- /docs/_static/css/fonts/Roboto-Slab-Bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/Roboto-Slab-Bold.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/Roboto-Slab-Bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/Roboto-Slab-Bold.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/Roboto-Slab-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/Roboto-Slab-Regular.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/Roboto-Slab-Regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/Roboto-Slab-Regular.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /docs/_static/css/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /docs/_static/css/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-bold-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-bold-italic.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-bold-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-bold-italic.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-bold.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-bold.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-normal-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-normal-italic.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-normal-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-normal-italic.woff2 -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-normal.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-normal.woff -------------------------------------------------------------------------------- /docs/_static/css/fonts/lato-normal.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/css/fonts/lato-normal.woff2 -------------------------------------------------------------------------------- /docs/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | var DOCUMENTATION_OPTIONS = { 2 | URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), 3 | VERSION: 'latest', 4 | LANGUAGE: 'None', 5 | COLLAPSE_INDEX: false, 6 | BUILDER: 'html', 7 | FILE_SUFFIX: '.html', 8 | LINK_SUFFIX: '.html', 9 | HAS_SOURCE: true, 10 | SOURCELINK_SUFFIX: '.txt', 11 | NAVIGATION_WITH_KEYS: false 12 | }; -------------------------------------------------------------------------------- /docs/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/docs/_static/file.png -------------------------------------------------------------------------------- /docs/_static/footer.html: -------------------------------------------------------------------------------- 1 |
2 | Footer 3 |
-------------------------------------------------------------------------------- /docs/_static/js/badge_only.js: -------------------------------------------------------------------------------- 1 | !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=4)}({4:function(e,t,r){}}); -------------------------------------------------------------------------------- /docs/_static/js/html5shiv-printshiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3-pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /docs/_static/js/html5shiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /docs/_static/js/theme.js: -------------------------------------------------------------------------------- 1 | !function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("
"),n("table.docutils.footnote").wrap("
"),n("table.docutils.citation").wrap("
"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n(''),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}t.length>0&&($(".wy-menu-vertical .current").removeClass("current"),t.addClass("current"),t.closest("li.toctree-l1").addClass("current"),t.closest("li.toctree-l1").parent().addClass("current"),t.closest("li.toctree-l1").addClass("current"),t.closest("li.toctree-l2").addClass("current"),t.closest("li.toctree-l3").addClass("current"),t.closest("li.toctree-l4").addClass("current"),t.closest("li.toctree-l5").addClass("current"),t[0].scrollIntoView())}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current"),e.siblings().find("li.current").removeClass("current"),e.find("> ul li.current").removeClass("current"),e.toggleClass("current")}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t 4 | 5 | 6 | 7 | 8 | 9 | 10 | Search — Cnerator latest documentation 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |
50 | 51 | 104 | 105 |
106 | 107 | 108 | 114 | 115 | 116 |
117 | 118 |
119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 |
139 | 140 |
    141 | 142 |
  • »
  • 143 | 144 |
  • Search
  • 145 | 146 | 147 |
  • 148 | 149 |
  • 150 | 151 |
152 | 153 | 154 |
155 |
156 |
157 |
158 | 159 | 166 | 167 | 168 |
169 | 170 |
171 | 172 |
173 | 174 |
175 |
176 | 177 |
178 | 179 |
180 |

181 | © Copyright 2021, Francisco Ortin and Javier Escalada. 182 | 183 |

184 |
185 | 186 | 187 | 188 | Built with Sphinx using a 189 | 190 | theme 191 | 192 | provided by Read the Docs. 193 | 194 |
195 |
196 |
197 | 198 |
199 | 200 |
201 | 202 | 203 | 208 | 209 | 210 | 211 | 212 | 213 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | -------------------------------------------------------------------------------- /docs/setup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | setup module — Cnerator 1.0.0 documentation 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 |
49 | 50 | 110 | 111 |
112 | 113 | 114 | 120 | 121 | 122 |
123 | 124 |
125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 |
145 | 146 |
    147 | 148 |
  • »
  • 149 | 150 |
  • cnerator »
  • 151 | 152 |
  • setup module
  • 153 | 154 | 155 |
  • 156 | 157 | 158 | 159 |
  • 160 | 161 |
162 | 163 | 164 |
165 |
166 |
167 |
168 | 169 |
170 |

setup module

171 |
172 | 173 | 174 |
175 | 176 |
177 |
178 | 182 | 183 |
184 | 185 |
186 |

187 | © Copyright 2021, Francisco Ortin and Javier Escalada. 188 | 189 |

190 |
191 | 192 | 193 | 194 | Built with Sphinx using a 195 | 196 | theme 197 | 198 | provided by Read the Docs. 199 | 200 |
201 |
202 |
203 | 204 |
205 | 206 |
207 | 208 | 209 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | -------------------------------------------------------------------------------- /json/functions/1-function-each-type.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 1, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_returning_bool": { 7 | "total": 1, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "functions_returning_char": { 11 | "total": 1, 12 | "condition": "lambda f: isinstance(f.return_type, ast.SignedChar)" 13 | }, 14 | "functions_returning_short": { 15 | "total": 1, 16 | "condition": "lambda f: isinstance(f.return_type, ast.SignedShortInt)" 17 | }, 18 | "functions_returning_int": { 19 | "total": 1, 20 | "condition": "lambda f: isinstance(f.return_type, ast.SignedInt)" 21 | }, 22 | "functions_returning_long_long": { 23 | "total": 1, 24 | "condition": "lambda f: isinstance(f.return_type, ast.SignedLongLongInt)" 25 | }, 26 | "functions_returning_float": { 27 | "total": 1, 28 | "condition": "lambda f: isinstance(f.return_type, ast.Float)" 29 | }, 30 | "functions_returning_double": { 31 | "total": 1, 32 | "condition": "lambda f: isinstance(f.return_type, ast.Double)" 33 | }, 34 | "functions_returning_pointer": { 35 | "total": 1, 36 | "condition": "lambda f: isinstance(f.return_type, ast.Pointer)" 37 | }, 38 | "functions_returning_struct": { 39 | "total": 1, 40 | "condition": "lambda f: isinstance(f.return_type, ast.Struct)" 41 | } 42 | } -------------------------------------------------------------------------------- /json/functions/15-function-each-type.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 15, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_returning_bool": { 7 | "total": 15, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "functions_returning_char": { 11 | "total": 15, 12 | "condition": "lambda f: isinstance(f.return_type, ast.SignedChar)" 13 | }, 14 | "functions_returning_short": { 15 | "total": 15, 16 | "condition": "lambda f: isinstance(f.return_type, ast.SignedShortInt)" 17 | }, 18 | "functions_returning_int": { 19 | "total": 15, 20 | "condition": "lambda f: isinstance(f.return_type, ast.SignedInt)" 21 | }, 22 | "functions_returning_long_long": { 23 | "total": 15, 24 | "condition": "lambda f: isinstance(f.return_type, ast.SignedLongLongInt)" 25 | }, 26 | "functions_returning_float": { 27 | "total": 15, 28 | "condition": "lambda f: isinstance(f.return_type, ast.Float)" 29 | }, 30 | "functions_returning_double": { 31 | "total": 15, 32 | "condition": "lambda f: isinstance(f.return_type, ast.Double)" 33 | }, 34 | "functions_returning_pointer": { 35 | "total": 15, 36 | "condition": "lambda f: isinstance(f.return_type, ast.Pointer)" 37 | }, 38 | "functions_returning_struct": { 39 | "total": 15, 40 | "condition": "lambda f: isinstance(f.return_type, ast.Struct)" 41 | } 42 | } -------------------------------------------------------------------------------- /json/functions/150-functions-total.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 22, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_returning_bool": { 7 | "total": 11, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "functions_returning_char": { 11 | "total": 10, 12 | "condition": "lambda f: isinstance(f.return_type, ast.SignedChar)" 13 | }, 14 | "functions_returning_short": { 15 | "total": 21, 16 | "condition": "lambda f: isinstance(f.return_type, ast.SignedShortInt)" 17 | }, 18 | "functions_returning_int": { 19 | "total": 7, 20 | "condition": "lambda f: isinstance(f.return_type, ast.SignedInt)" 21 | }, 22 | "functions_returning_long_long": { 23 | "total": 21, 24 | "condition": "lambda f: isinstance(f.return_type, ast.SignedLongLongInt)" 25 | }, 26 | "functions_returning_float": { 27 | "total": 22, 28 | "condition": "lambda f: isinstance(f.return_type, ast.Float)" 29 | }, 30 | "functions_returning_double": { 31 | "total": 22, 32 | "condition": "lambda f: isinstance(f.return_type, ast.Double)" 33 | }, 34 | "functions_returning_pointer": { 35 | "total": 7, 36 | "condition": "lambda f: isinstance(f.return_type, ast.Pointer)" 37 | }, 38 | "functions_returning_struct": { 39 | "total": 7, 40 | "condition": "lambda f: isinstance(f.return_type, ast.Struct)" 41 | } 42 | } -------------------------------------------------------------------------------- /json/functions/2000-function-void-no-void.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 2, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_not_returning_void": { 7 | "total": 2, 8 | "condition": "lambda f: not isinstance(f.return_type, ast.Void)" 9 | } 10 | } -------------------------------------------------------------------------------- /json/functions/300-function-each-type.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 300, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_returning_bool": { 7 | "total": 300, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "functions_returning_char": { 11 | "total": 300, 12 | "condition": "lambda f: isinstance(f.return_type, ast.SignedChar)" 13 | }, 14 | "functions_returning_short": { 15 | "total": 300, 16 | "condition": "lambda f: isinstance(f.return_type, ast.SignedShortInt)" 17 | }, 18 | "functions_returning_int": { 19 | "total": 300, 20 | "condition": "lambda f: isinstance(f.return_type, ast.SignedInt)" 21 | }, 22 | "functions_returning_long_long": { 23 | "total": 300, 24 | "condition": "lambda f: isinstance(f.return_type, ast.SignedLongLongInt)" 25 | }, 26 | "functions_returning_float": { 27 | "total": 300, 28 | "condition": "lambda f: isinstance(f.return_type, ast.Float)" 29 | }, 30 | "functions_returning_double": { 31 | "total": 300, 32 | "condition": "lambda f: isinstance(f.return_type, ast.Double)" 33 | }, 34 | "functions_returning_pointer": { 35 | "total": 300, 36 | "condition": "lambda f: isinstance(f.return_type, ast.Pointer)" 37 | }, 38 | "functions_returning_struct": { 39 | "total": 300, 40 | "condition": "lambda f: isinstance(f.return_type, ast.Struct)" 41 | } 42 | } -------------------------------------------------------------------------------- /json/functions/3000-functions-total.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions_returning_void": { 3 | "total": 429, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "functions_returning_bool": { 7 | "total": 215, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "functions_returning_char": { 11 | "total": 214, 12 | "condition": "lambda f: isinstance(f.return_type, ast.SignedChar)" 13 | }, 14 | "functions_returning_short": { 15 | "total": 428, 16 | "condition": "lambda f: isinstance(f.return_type, ast.SignedShortInt)" 17 | }, 18 | "functions_returning_int": { 19 | "total": 142, 20 | "condition": "lambda f: isinstance(f.return_type, ast.SignedInt)" 21 | }, 22 | "functions_returning_long_long": { 23 | "total": 428, 24 | "condition": "lambda f: isinstance(f.return_type, ast.SignedLongLongInt)" 25 | }, 26 | "functions_returning_float": { 27 | "total": 429, 28 | "condition": "lambda f: isinstance(f.return_type, ast.Float)" 29 | }, 30 | "functions_returning_double": { 31 | "total": 429, 32 | "condition": "lambda f: isinstance(f.return_type, ast.Double)" 33 | }, 34 | "functions_returning_pointer": { 35 | "total": 143, 36 | "condition": "lambda f: isinstance(f.return_type, ast.Pointer)" 37 | }, 38 | "functions_returning_struct": { 39 | "total": 143, 40 | "condition": "lambda f: isinstance(f.return_type, ast.Struct)" 41 | } 42 | } -------------------------------------------------------------------------------- /json/functions/article.json: -------------------------------------------------------------------------------- 1 | { 2 | "function_returning_void": { 3 | "total": 1, 4 | "condition": "lambda f: isinstance(f.return_type, ast.Void)" 5 | }, 6 | "function_returning_bool": { 7 | "total": 1, 8 | "condition": "lambda f: isinstance(f.return_type, ast.Bool)" 9 | }, 10 | "function_with_if_else": { 11 | "total": 1, 12 | "condition": "lambda f: any(stmt for stmt in f.children if isinstance(stmt, ast.If) and any(stmt.else_statements))" 13 | } 14 | } -------------------------------------------------------------------------------- /json/functions/n-functions.json: -------------------------------------------------------------------------------- 1 | { 2 | "number_of_functions": { 3 | "total": 5000, 4 | "condition": "lambda f: True" 5 | } 6 | } -------------------------------------------------------------------------------- /json/probabilities/article.json: -------------------------------------------------------------------------------- 1 | { 2 | "function_basic_stmt_prob":{ 3 | "assignment":0.5, 4 | "invocation":0.2, 5 | "incdec":0.1, 6 | "augmented_assignment":0.1, 7 | "return": 0.1 8 | }, 9 | "array_literal_initialization_prob":{ 10 | "True":0.1, 11 | "False":0.9 12 | }, 13 | "primitive_types_prob":{ 14 | "__prob_distribution__":"equal_prob", 15 | "__values__":[ 16 | "ast.Bool", 17 | "ast.SignedChar", 18 | "ast.UnsignedChar", 19 | "ast.SignedShortInt" 20 | ] 21 | }, 22 | "param_number_prob":{ 23 | "__prob_distribution__":"proportional_prob", 24 | "__values__":{ 25 | "0":1, 26 | "1":2, 27 | "2":3, 28 | "3":3, 29 | "4":2, 30 | "5":1 31 | } 32 | }, 33 | "number_stmts_main_prob":{ 34 | "__prob_distribution__":"normal_prob", 35 | "__mean__": 10, 36 | "__stdev__": 3 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /json/probabilities/example_probs.json: -------------------------------------------------------------------------------- 1 | { 2 | "function_basic_stmt_prob":{ 3 | "assignment":0.5, 4 | "invocation":0.2, 5 | "incdec":0.1, 6 | "augmented_assignment":0.1, 7 | "return": 0.1 8 | }, 9 | "array_literal_initialization_prob":{ 10 | "True":0.1, 11 | "False":0.9 12 | }, 13 | "primitive_types_prob":{ 14 | "__prob_distribution__":"equal_prob", 15 | "__values__":[ 16 | "ast.Bool", 17 | "ast.SignedChar", 18 | "ast.UnsignedChar", 19 | "ast.SignedShortInt", 20 | "ast.UnsignedShortInt", 21 | "ast.SignedInt", 22 | "ast.UnsignedInt", 23 | "ast.SignedLongInt", 24 | "ast.UnsignedLongInt", 25 | "ast.SignedLongLongInt", 26 | "ast.UnsignedLongLongInt", 27 | "ast.Float", 28 | "ast.Double", 29 | "ast.LongDouble" 30 | ] 31 | }, 32 | "param_number_prob":{ 33 | "__prob_distribution__":"proportional_prob", 34 | "__values__":{ 35 | "0":1, 36 | "1":2, 37 | "2":3, 38 | "3":3, 39 | "4":2, 40 | "5":1 41 | } 42 | }, 43 | "number_stmts_main_prob":{ 44 | "__prob_distribution__":"normal_prob", 45 | "__mean__": 10, 46 | "__stdev__": 3 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /params/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Package that provides all the functionality to parse and process the command line arguments of Cnerator. 6 | To see all the parameters, run Cnerator with ``-h`` or ``--help`` parameters. 7 | """ 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /params/epilog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This module is aimed at building the epilog of the help message. 6 | Such message shows the different syntactic constructs provided by Cnerator. 7 | """ 8 | 9 | import core.probs as probs 10 | from typing import List, Tuple 11 | 12 | OPTION_PREFIX = " - " 13 | NEW_LINE_PREFIX = " " 14 | MESSAGE_PRELUDE = "What follows is the available probabilities, which can be customized by the " \ 15 | "user with the -p and -P options (see examples in json/probabilities directory):\n" 16 | MAX_LINE_WITH = 80 17 | 18 | 19 | def build_epilog() -> str: 20 | """Builds the epilog of the help message""" 21 | description_list = [f"{OPTION_PREFIX}{prob_name}: {prob_description}" for (prob_name, prob_description) 22 | in probs.__dict__[probs.DOC_NAME].items()] 23 | message = "\n".join(description_list) 24 | lines = _break_text_into_lines(message, MAX_LINE_WITH) 25 | lines = [line if line.startswith(OPTION_PREFIX) else NEW_LINE_PREFIX + line for line in lines] 26 | predule_lines = _break_text_into_lines(MESSAGE_PRELUDE, MAX_LINE_WITH) 27 | predule_lines.extend(lines) 28 | return "\n".join(predule_lines) 29 | 30 | 31 | def _break_line(line: str, max_chars_per_line: int) -> List[str]: 32 | """Breaks a line into a list of strings with maximum characters per line""" 33 | lines = _break_line_in_two(line, max_chars_per_line) 34 | if len(lines) == 1: 35 | return lines 36 | return [lines[0]] + _break_line(lines[1], max_chars_per_line) 37 | 38 | 39 | def _break_line_in_two(line: str, max_chars_per_line: int) -> List[str]: 40 | """Breaks a line into the first line lower than max_char_per_line and the remaining string""" 41 | if len(line) <= max_chars_per_line: 42 | return [line] 43 | position = 0 44 | while position < max_chars_per_line: 45 | new_position = line.find(" ", position) 46 | if new_position == -1 or new_position >= max_chars_per_line-1: 47 | return [line[:position-1], line[position:]] 48 | position = new_position + 1 49 | return [line] 50 | 51 | 52 | def _break_text_into_lines(text: str, max_chars_per_line: int) -> List[str]: 53 | """Breaks a text into lines""" 54 | input_lines = text.split("\n") 55 | output_lines = list() 56 | for line in input_lines: 57 | output_lines.extend(_break_line(line, max_chars_per_line)) 58 | return output_lines 59 | -------------------------------------------------------------------------------- /params/json_probs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This module is aimed at processing input json files specifying the probabilities of the syntactic constructs to 6 | be created by Cnerator (command line option -P). See json/probabilities for particular examples. 7 | """ 8 | 9 | from core import probs_helper 10 | from typing import Union, Dict 11 | import json 12 | import sys 13 | 14 | 15 | def parse_probabilities_specification_json_file(file_name: str) -> Dict[str, dict]: 16 | """Parses a json file with probabilities specifications and returns a valid representation""" 17 | with open(file_name) as json_file: 18 | data = json.load(json_file) 19 | dictionary = _process_json_probs_data(data) 20 | return dictionary 21 | 22 | 23 | def _process_json_probs_data(data: dict)-> Dict[str, dict]: 24 | """Takes the data extracted from the json file a dictionary of probabilities""" 25 | result = dict() 26 | for prob_name, prob_dictionary in data.items(): 27 | _process_json_probs_entry(prob_name, prob_dictionary, result) 28 | return result 29 | 30 | 31 | def _process_json_probs_entry(prob_name: str, prob_dictionary: dict, result: dict) -> None: 32 | """Takes one entry of the json probability specification file, process it 33 | and adds the correct representation to result""" 34 | from core import probs 35 | if not probs.does_this_probability_exist(prob_name): 36 | print(f"Unknown probability '{prob_name}'.", file=sys.stderr) # probability name is not in probs module 37 | elif "__prob_distribution__" not in prob_dictionary.keys(): 38 | # 1) fixed probability set by the user 39 | result[prob_name] = {_eval_str(key): content for (key, content) in prob_dictionary.items()} 40 | elif prob_dictionary["__prob_distribution__"] == "equal_prob": 41 | # 2) equal probability for a set of values 42 | if "__values__" not in prob_dictionary.keys(): 43 | print(f"Equal probability distribution requires a __values__ entry.", file=sys.stderr) 44 | else: 45 | values = set() 46 | for value_str in prob_dictionary["__values__"]: 47 | values.add(_eval_str(value_str)) 48 | result[prob_name] = probs_helper.compute_equal_prob(values) 49 | elif prob_dictionary["__prob_distribution__"] in ["proportional_prob", "inverse_proportional_prob"]: 50 | # 3) (inverse and direct) proportional probability for a set of values that do not sum 0 51 | if "__values__" not in prob_dictionary.keys(): 52 | print(f"Proportional probability distribution requires a __values__ entry.", file=sys.stderr) 53 | else: 54 | # keys of the dict must be evaluated (e.g., "3" -> 3, "ast.Int" -> ast.Int) 55 | values_dict = {_eval_str(key): content for (key, content) in prob_dictionary["__values__"].items()} 56 | if prob_name == "proportional_prob": # direct proportional 57 | result[prob_name] = probs_helper.compute_proportional_prob(values_dict) 58 | else: # inverse proportional 59 | result[prob_name] = probs_helper.compute_inverse_proportional_prob(values_dict) 60 | elif prob_dictionary["__prob_distribution__"] == "normal_prob": 61 | # 5) normal probability, given a mean and standard deviation 62 | if not {"__mean__", "__stdev__"}.issubset(prob_dictionary.keys()): 63 | print(f"Normal probability distribution requires __mean__ and __stdev__ entries.", file=sys.stderr) 64 | else: 65 | result[prob_name] = probs_helper.compute_normal_prob(prob_dictionary["__mean__"], 66 | prob_dictionary["__stdev__"]) 67 | else: 68 | print(f"Unknown probability distribution '{prob_dictionary['__prob_distribution__']}'.", file=sys.stderr) 69 | 70 | 71 | def _eval_str(string: str) -> object: 72 | """Evaluates a string and returns its evaluation""" 73 | import core 74 | from core import ast 75 | global_variables = {"core": core, "cnerator": core, "ast": ast} 76 | try: 77 | return eval(string, global_variables) 78 | except: 79 | return string # if the string is not evaluable, then we just return the string 80 | -------------------------------------------------------------------------------- /params/parameters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Module where the command line arguments are parsed. 6 | """ 7 | 8 | import argparse 9 | import json 10 | import sys 11 | from typing import List, Dict, Union 12 | 13 | 14 | def get_app_args(): 15 | global __ARGS 16 | return __ARGS 17 | 18 | 19 | def parse_args(): 20 | from params.epilog import build_epilog 21 | parser = argparse.ArgumentParser(description='Generates a compilable C program', epilog=build_epilog(), 22 | formatter_class=argparse.RawDescriptionHelpFormatter) 23 | parser.add_argument("-O", "--output_dir", metavar="PATH", default="out", 24 | help="Output directory (default: %(default)s)") 25 | parser.add_argument("-o", "--output", metavar="NAME", default="main", 26 | help="C output file name, without the .c extension (default: %(default)s)") 27 | parser.add_argument("-n", "--nfiles", metavar="NUMBER", type=int, default=2, 28 | help="Split the program in different C files (default: %(default)s)") 29 | parser.add_argument("-p", "--probs", metavar="PROBS", default="", 30 | help="Semicolon-separated list of probabilities and their values " 31 | "(e.g., call_prob={True:0.2,False: 0.8}; param_number_prob={0:0.2,1:0.3,2:0.3,3:0.2})") 32 | parser.add_argument("-P", "--probsfile", metavar="PROBSFILE", default="", 33 | help="json file specifying some probatilities (e.g. json/probabilities/example_probs.json) " 34 | "(see json/probabilities/ for examples)") 35 | parser.add_argument("-r", "--recursion", metavar="RECURSION_LIMIT", type=int, default=50000, 36 | help="Python recursion limit (default: %(default)s)") 37 | parser.add_argument("-f", "--functions", metavar="FUNCTIONS", default="", 38 | help="json file specifying conditions of the functions to be created" 39 | "(e.g., json/functions/1-function-each-type.json)") 40 | parser.add_argument("-V", "--visitors", metavar="VISITORS", default="", 41 | help="Colon-separated list of visitors, in order " 42 | "(e.g., visitors.func_to_proc:visitors.return_instrumentation)") 43 | parser.add_argument("-v", "--verbose", action="store_true", 44 | help="Verbose messages (default: %(default)s)") 45 | parser.add_argument("-d", "--debug", action="store_true", 46 | help="Generate debug info (call graph and struct structure) in .dot files " 47 | "(default: %(default)s)") 48 | global __ARGS 49 | __ARGS = parser.parse_args() 50 | return __ARGS 51 | 52 | 53 | 54 | def get_modules_to_import(vst_param: str) -> List: 55 | """Returns the list of visitors to import, given the args.visitors option""" 56 | import importlib 57 | params = vst_param.split(":") 58 | try: 59 | modules = [importlib.import_module(visitor_module_name) for visitor_module_name in params 60 | if len(visitor_module_name.replace(" ", "")) > 0] 61 | return modules 62 | except Exception as error: 63 | import core 64 | core.utils.print_to_std_error(f"Error parsing the -V param ({vst_param}).\n" 65 | f"Exception message: {error}.\n" 66 | f"Example format visitors.func_to_proc:visitors.return_instrumentation.") 67 | return list() 68 | 69 | 70 | def parse_function_specification_json_file(file_name: str) -> Dict[str, Dict]: 71 | """Parses a json file with function specifications and returns a valid representation""" 72 | import core 73 | from core import ast 74 | global_variables = {"cnerator": core, "core": core, "ast": ast} 75 | with open(file_name) as json_file: 76 | data = json.load(json_file) 77 | for key, content in data.items(): 78 | lambda_function = eval(content["condition"], global_variables) 79 | content["condition"] = lambda_function 80 | return data 81 | 82 | 83 | def get_probs_to_override(probs_param: str) -> Union[Dict[str, dict], None]: 84 | """Parses the args.probs parameter and returns the dictionary with their values""" 85 | if not probs_param: 86 | return None # no parameter 87 | local_dict = dict() 88 | try: 89 | exec(probs_param, dict(), local_dict) 90 | except: 91 | print(f"Wrong probability format '{probs_param}'.", file=sys.stderr) 92 | return None # wrong probability 93 | result_dict = dict() 94 | for prob_key, prob_dict in local_dict.items(): 95 | import core 96 | if not core.probs.does_this_probability_exist(prob_key): 97 | print(f"Unknown probability '{prob_key}'.", file=sys.stderr) 98 | elif type(prob_dict) is not dict: 99 | print(f"The probability value must be a dictionary ({prob_dict} is wrong).", file=sys.stderr) 100 | else: 101 | result_dict[prob_key] = prob_dict 102 | return result_dict 103 | 104 | 105 | def parse_probabilities_specification_json_file(file_name: str) -> Union[Dict[str, dict], None]: 106 | """Parses a json file with probabilities specifications and returns a valid representation""" 107 | import core 108 | global_variables = {"cnerator": core, "core": core} 109 | with open(file_name) as json_file: 110 | data = json.load(json_file) 111 | for key, content in data.items(): 112 | lambda_function = eval(content["condition"], global_variables) 113 | content["condition"] = lambda_function 114 | return data 115 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | -------------------------------------------------------------------------------- /run/15_function_each_type.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator to create a particular number of functions. 6 | It creates a program using the ``15-function-each-type.json`` file, running different visitors. 7 | Run it from the parent folder with ``python -m run.15_function_each_type``. 8 | """ 9 | 10 | import sys 11 | import cnerator 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | sys.argv.append('-f') # controlled function generation 19 | sys.argv.append('json/functions/15-function-each-type.json') # controlled function generation 20 | sys.argv.append('-V') # visitor post-processing 21 | sys.argv.append('visitors.func_to_proc:visitors.return_instrumentation:visitors.fix_ptr_literal') 22 | if VERBOSE: 23 | sys.argv.append("-v") 24 | cnerator.main() 25 | -------------------------------------------------------------------------------- /run/1_function_each_type.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator to create a particular number of functions. 6 | It creates a program using the ``1_function-each-type-10.json`` file, running different visitors. 7 | Run it from the parent folder with ``python -m run.1_function_each_type``. 8 | """ 9 | 10 | import sys 11 | import cnerator 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | sys.argv.append('-f') # controlled function generation 19 | sys.argv.append('json/functions/1-function-each-type.json') # controlled function generation 20 | sys.argv.append('-V') # visitor post-processing 21 | sys.argv.append('visitors.func_to_proc:visitors.return_instrumentation:visitors.fix_ptr_literal') 22 | sys.argv.append('-n') # generate all the code in one file 23 | sys.argv.append('1') # generate all the code in one file 24 | if VERBOSE: 25 | sys.argv.append("-v") 26 | cnerator.main() 27 | -------------------------------------------------------------------------------- /run/2000_function_void_no_void.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator to create a particular number of functions. 6 | It creates a program using the ``2000-function-void-no-void.json`` file, running different visitors. 7 | Run it from the parent folder with ``python -m run.2000_function_void_no_void``. 8 | """ 9 | 10 | import sys 11 | import cnerator 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | sys.argv.append('-f') # controlled function generation 19 | sys.argv.append('json/functions/2000-function-void-no-void.json') # controlled function generation 20 | sys.argv.append('-V') # visitor post-processing 21 | sys.argv.append('visitors.func_to_proc:visitors.return_instrumentation:visitors.fix_ptr_literal') 22 | if VERBOSE: 23 | sys.argv.append("-v") 24 | cnerator.main() 25 | -------------------------------------------------------------------------------- /run/300_function_each_type.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator to create a particular number of functions. 6 | It creates a program using the ``300-function-each-type.json`` file, running different visitors. 7 | Run it from the parent folder with ``python -m run.300_function_each_type``. 8 | """ 9 | 10 | import sys 11 | import cnerator 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | sys.argv.append('-f') # controlled function generation 19 | sys.argv.append('json/functions/300-function-each-type.json') # controlled function generation 20 | sys.argv.append('-V') # visitor post-processing 21 | sys.argv.append('visitors.func_to_proc:visitors.return_instrumentation:visitors.fix_ptr_literal') 22 | if VERBOSE: 23 | sys.argv.append("-v") 24 | cnerator.main() 25 | -------------------------------------------------------------------------------- /run/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This package provides different example pre-configured executions of Cnerator. 6 | """ 7 | 8 | -------------------------------------------------------------------------------- /run/article.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator to create particular functions. 6 | It creates a program using the ``article.json`` file, running different visitors. 7 | Run it from the parent folder with ``python -m run.article``. 8 | """ 9 | 10 | import cnerator 11 | import sys 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | sys.argv.append('-f') # controlled function generation 19 | sys.argv.append('json/functions/article.json') # controlled function generation 20 | sys.argv.append('-V') # visitor post-processing 21 | sys.argv.append('visitors.return_instrumentation:visitors.fix_ptr_literal') # visitor post-processing 22 | sys.argv.append('-P') # probabilities file 23 | sys.argv.append('json/probabilities/article.json') # probabilities file 24 | sys.argv.append('-n') # generate all the code in one file 25 | sys.argv.append('1') # generate all the code in one file 26 | if VERBOSE: 27 | sys.argv.append("-v") 28 | cnerator.main() 29 | -------------------------------------------------------------------------------- /run/defaults.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator passing no parameters. 6 | It creates a random program considering the default probabilities. 7 | Run it from the parent folder with ``python -m run.defaults`. 8 | """ 9 | 10 | import sys 11 | import cnerator 12 | 13 | VERBOSE = True 14 | 15 | if __name__ == "__main__": 16 | sys.argv.append('-O') # generate output files in ../out 17 | sys.argv.append('out') # generate output files in ../out 18 | if VERBOSE: 19 | sys.argv.append("-v") 20 | cnerator.main() 21 | -------------------------------------------------------------------------------- /run/defaults_one_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator passing no parameters but generation in one file (``-n 1``). 6 | Run it from the parent folder with ``python -m run.defaults_one_file``. 7 | """ 8 | 9 | import sys 10 | import cnerator 11 | 12 | VERBOSE = True 13 | 14 | if __name__ == "__main__": 15 | sys.argv.append('-O') # generate output files in ../out 16 | sys.argv.append('out') # generate output files in ../out 17 | sys.argv.append('-n') # generate all the code in one file 18 | sys.argv.append('1') # generate all the code in one file 19 | if VERBOSE: 20 | sys.argv.append("-v") 21 | cnerator.main() 22 | -------------------------------------------------------------------------------- /run/help.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator passing the ``--help`` parameter. 6 | Run it from the parent folder with ``python -m run.help``. 7 | """ 8 | 9 | import sys 10 | import cnerator 11 | 12 | if __name__ == "__main__": 13 | sys.argv.append('-h') # generate output files in ../out 14 | cnerator.main() 15 | -------------------------------------------------------------------------------- /run/probs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator passing the ``-p`` parameter to specify the probabilities of two language constructs. 6 | Run it from the parent folder with ``python -m run.probs``. 7 | """ 8 | 9 | import sys 10 | import cnerator 11 | 12 | if __name__ == "__main__": 13 | sys.argv.append('-O') # generate output files in ../out 14 | sys.argv.append('out') # generate output files in ../out 15 | sys.argv.append('-p') # set the value of two probabilities 16 | sys.argv.append('call_prob={True:0.1,False: 0.9};param_number_prob={0:0.2,1:0.3,2:0.3,3:0.2}') 17 | cnerator.main() 18 | -------------------------------------------------------------------------------- /run/probs_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example execution of Cnerator specifying probabilities in a json file (``example_probs.json``). 6 | Run it from the parent folder with ``python -m run.probs_file``. 7 | """ 8 | 9 | import sys 10 | import cnerator 11 | 12 | VERBOSE = True 13 | 14 | if __name__ == "__main__": 15 | sys.argv.append('-O') # generate output files in ../out 16 | sys.argv.append('out') # generate output files in ../out 17 | sys.argv.append('-P') # set different probabilities with a specification file 18 | sys.argv.append('json/probabilities/example_probs.json') # set different probabilities with a specification file 19 | if VERBOSE: 20 | sys.argv.append("-v") 21 | cnerator.main() 22 | -------------------------------------------------------------------------------- /sphinx/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | cp -R _build/html/. ../docs/. 22 | -------------------------------------------------------------------------------- /sphinx/_build/doctrees/cnerator.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/cnerator.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/core.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/core.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/debug.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/debug.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/environment.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/environment.pickle -------------------------------------------------------------------------------- /sphinx/_build/doctrees/getting_started.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/getting_started.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/index.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/index.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/modules.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/modules.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/params.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/params.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/run.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/run.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/user_manual.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/user_manual.doctree -------------------------------------------------------------------------------- /sphinx/_build/doctrees/visitors.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/doctrees/visitors.doctree -------------------------------------------------------------------------------- /sphinx/_build/html/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 0955bf54aa55ff5c9a24cfc47ed04c59 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /sphinx/_build/html/_modules/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Overview: module code — Cnerator latest documentation 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 | 101 | 102 |
103 | 104 | 105 | 111 | 112 | 113 |
114 | 115 |
116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |
136 | 137 |
    138 | 139 |
  • »
  • 140 | 141 |
  • Overview: module code
  • 142 | 143 | 144 |
  • 145 | 146 |
  • 147 | 148 |
149 | 150 | 151 |
152 |
153 |
154 | 178 | 179 |
180 |
181 | 182 |
183 | 184 |
185 |

186 | © Copyright 2021, Francisco Ortin and Javier Escalada. 187 | 188 |

189 |
190 | 191 | 192 | 193 | Built with Sphinx using a 194 | 195 | theme 196 | 197 | provided by Read the Docs. 198 | 199 |
200 |
201 |
202 | 203 |
204 | 205 |
206 | 207 | 208 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/cnerator.rst.txt: -------------------------------------------------------------------------------- 1 | Cnerator module 2 | =============== 3 | 4 | .. automodule:: cnerator 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/core.rst.txt: -------------------------------------------------------------------------------- 1 | core package 2 | ============ 3 | 4 | .. automodule:: core 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | core.ast module 13 | --------------- 14 | 15 | .. automodule:: core.ast 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | core.generators module 21 | ---------------------- 22 | 23 | .. automodule:: core.generators 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | 29 | core.operators module 30 | --------------------- 31 | 32 | .. automodule:: core.operators 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | core.operators\_types module 38 | ---------------------------- 39 | 40 | .. automodule:: core.operators_types 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | core.probs module 46 | ----------------- 47 | 48 | .. automodule:: core.probs 49 | :members: 50 | :undoc-members: 51 | :show-inheritance: 52 | 53 | core.probs\_helper module 54 | ------------------------- 55 | 56 | .. automodule:: core.probs_helper 57 | :members: 58 | :undoc-members: 59 | :show-inheritance: 60 | 61 | core.type\_inference module 62 | --------------------------- 63 | 64 | .. automodule:: core.type_inference 65 | :members: 66 | :undoc-members: 67 | :show-inheritance: 68 | 69 | core.utils module 70 | ----------------- 71 | 72 | .. automodule:: core.utils 73 | :members: 74 | :undoc-members: 75 | :show-inheritance: 76 | 77 | 78 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/debug.rst.txt: -------------------------------------------------------------------------------- 1 | debug package 2 | ============= 3 | 4 | .. automodule:: debug 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | debug.graph module 13 | ------------------ 14 | 15 | .. automodule:: debug.graph 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | debug.call\_inspector module 21 | ---------------------------- 22 | 23 | .. automodule:: debug.call_inspector 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | debug.structure\_inspector module 29 | --------------------------------- 30 | 31 | .. automodule:: debug.structure_inspector 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | 37 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/getting_started.rst.txt: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | `Cnerator `_ is a C source code generation tool. 5 | It can be used to generate large amounts of 6 | `standard ANSI/ISO C source code `_, ready to be compiled 7 | by any standard language implementation. 8 | `Cnerator `_ is highly customizable 9 | to generate all the syntactic constructs of the C language, necessary to build 10 | accurate predictive models with machine learning algorithms. 11 | 12 | 13 | Installation 14 | ------------ 15 | 16 | You need a Python 3.7+ standard implementation. 17 | The only additional package to install is ``numpy``: 18 | 19 | 20 | .. code-block:: bash 21 | 22 | pip install numpy 23 | 24 | 25 | Usage 26 | ----- 27 | 28 | Then, you may just run `Cnerator `_ 29 | with no arguments to generate a random C program in the ``out`` directory: 30 | 31 | 32 | .. code-block:: bash 33 | 34 | python cnerator.py 35 | 36 | 37 | There are plenty of options to customize `Cnerator `_. 38 | To specify the probability of a particular language 39 | construct, you can use the ``-p`` or ``--probs`` option. 40 | The following command sets to 20% the probability of 41 | generating a function invocation when a new expression is required: 42 | 43 | .. code-block:: bash 44 | 45 | python cnerator.py -p "call_prob = {True: 0.2, False: 0.8}" 46 | 47 | 48 | If more sophisticated probabilities are required, you can specify them in a JSON file and pass it as 49 | a parameter (see the [documentation](documentation#probability-specification-files) to know the JSON file format). 50 | The following line passes an example JSON file in the ``json/probabilities`` folder where 51 | different probability distributions are specified for some syntactic constructs: 52 | 53 | .. code-block:: bash 54 | 55 | python cnerator.py -P json/probabilities/example_probs.json 56 | 57 | 58 | `Cnerator `_ also provides allows 59 | the user to control the number and characteristics of 60 | all the functions to be generated. A JSON file is used for that purpose 61 | (see the [documentation](documentation#function-generation-files)). 62 | The following command makes `Cnerator `_ 63 | generate one function for each high-level return 64 | type in the C programming language: 65 | 66 | 67 | .. code-block:: bash 68 | 69 | python cnerator.py -f json/functions/1-function-each-type.json 70 | 71 | 72 | Sometimes, the user needs the output program to fulfill some requirements not guaranteed by the 73 | stochastic generation process. 74 | To this aim, `Cnerator `_ allows 75 | the specification of an ordered collection of Python 76 | post-process specification files (see the [documentation](documentation#post-processing-specification-files)). 77 | These post-processing files can modify the generated code to satisfy those requirements. 78 | The following execution generates a random program and then executes two visitors: 79 | one to rename ``func`` functions to ``proc`` (and their invocations) when they return ``void``; 80 | and another one to add a ``__RETURN__`` label before each return statement: 81 | 82 | .. code-block:: bash 83 | 84 | python cnerator.py -V visitors.func_to_proc:visitors.return_instrumentation 85 | 86 | 87 | To see all the options, just run the ``-h`` or ``--help`` options. 88 | 89 | 90 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/index.rst.txt: -------------------------------------------------------------------------------- 1 | .. Cnerator documentation master file, created by 2 | sphinx-quickstart on Wed Jan 20 14:07:57 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Cnerator's documentation! 7 | ==================================== 8 | 9 | .. image:: https://img.shields.io/github/license/ComputationalReflection/cnerator 10 | :alt: License 11 | :target: https://github.com/ComputationalReflection/Cnerator/blob/main/LICENSE 12 | 13 | .. image:: https://img.shields.io/github/v/release/computationalreflection/cnerator?include_prereleases 14 | :alt: Latest release 15 | :target: https://github.com/ComputationalReflection/cnerator/releases 16 | 17 | .. image:: https://img.shields.io/static/v1?label=docs&message=Sphinx&color=blue 18 | :alt: Documentation 19 | :target: https://computationalreflection.github.io/Cnerator/ 20 | 21 | .. image:: https://img.shields.io/github/languages/code-size/computationalreflection/cnerator 22 | :alt: Code size 23 | :target: https://github.com/ComputationalReflection/Cnerator 24 | 25 | .. image:: https://img.shields.io/github/repo-size/computationalreflection/cnerator 26 | :alt: Repo size 27 | :target: https://github.com/ComputationalReflection/Cnerator 28 | 29 | 30 | `Cnerator `_ is a C source code generation tool. 31 | Generated programs can be compiled with any standard ANSI C compiler. 32 | The user may define different parameters such as the number of function to be generated or the probabilities 33 | of all the different syntactic constructs. 34 | 35 | 36 | Contents: 37 | --------- 38 | 39 | .. toctree:: 40 | :maxdepth: 2 41 | 42 | getting_started 43 | user_manual 44 | modules 45 | 46 | 47 | 48 | Indices and tables: 49 | ------------------- 50 | 51 | * :ref:`genindex` 52 | * :ref:`modindex` 53 | 54 | | 55 | 56 | .. image:: _static/transparent.png 57 | :alt: Computational Reflection research group 58 | :align: center 59 | :target: http://www.reflection.uniovi.es 60 | :width: 25% 61 | 62 | 63 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/modules.rst.txt: -------------------------------------------------------------------------------- 1 | Cnerator API 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | cnerator 8 | core 9 | debug 10 | params 11 | run 12 | visitors 13 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/params.rst.txt: -------------------------------------------------------------------------------- 1 | params package 2 | ============== 3 | 4 | .. automodule:: params 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | params.epilog module 14 | -------------------- 15 | 16 | .. automodule:: params.epilog 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | params.json\_probs module 22 | ------------------------- 23 | 24 | .. automodule:: params.json_probs 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | params.parameters module 30 | ------------------------ 31 | 32 | .. automodule:: params.parameters 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | params.writter module 38 | --------------------- 39 | 40 | .. automodule:: params.writter 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | 46 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/run.rst.txt: -------------------------------------------------------------------------------- 1 | run package 2 | =========== 3 | 4 | .. automodule:: run 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | run.1\-function\-each\-type module 13 | ---------------------------------- 14 | 15 | .. automodule:: run.1_function_each_type 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | run.15\-function\-each\-type module 21 | ----------------------------------- 22 | 23 | .. automodule:: run.15_function_each_type 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | run.2000\-function\-void\-no\-void module 29 | ----------------------------------------- 30 | 31 | .. automodule:: run.2000_function_void_no_void 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | run.300\-function\-each\-type module 37 | ------------------------------------ 38 | 39 | .. automodule:: run.300_function_each_type 40 | :members: 41 | :undoc-members: 42 | :show-inheritance: 43 | 44 | run.article module 45 | ------------------ 46 | 47 | .. automodule:: run.article 48 | :members: 49 | :undoc-members: 50 | :show-inheritance: 51 | 52 | run.defaults module 53 | ------------------- 54 | 55 | .. automodule:: run.defaults 56 | :members: 57 | :undoc-members: 58 | :show-inheritance: 59 | 60 | run.defaults\_one\_file module 61 | ------------------------------ 62 | 63 | .. automodule:: run.defaults_one_file 64 | :members: 65 | :undoc-members: 66 | :show-inheritance: 67 | 68 | run.help module 69 | --------------- 70 | 71 | .. automodule:: run.help 72 | :members: 73 | :undoc-members: 74 | :show-inheritance: 75 | 76 | run.probs module 77 | ---------------- 78 | 79 | .. automodule:: run.probs 80 | :members: 81 | :undoc-members: 82 | :show-inheritance: 83 | 84 | run.probs\_file module 85 | ---------------------- 86 | 87 | .. automodule:: run.probs_file 88 | :members: 89 | :undoc-members: 90 | :show-inheritance: 91 | 92 | -------------------------------------------------------------------------------- /sphinx/_build/html/_sources/visitors.rst.txt: -------------------------------------------------------------------------------- 1 | visitors package 2 | ================ 3 | 4 | .. automodule:: visitors 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | visitors.fix\_ptr\_literal module 14 | --------------------------------- 15 | 16 | .. automodule:: visitors.fix_ptr_literal 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | visitors.func\_to\_proc module 22 | ------------------------------ 23 | 24 | .. automodule:: visitors.func_to_proc 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | visitors.function\_subs module 30 | ------------------------------ 31 | 32 | .. automodule:: visitors.function_subs 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | visitors.return\_instrumentation module 38 | --------------------------------------- 39 | 40 | .. automodule:: visitors.return_instrumentation 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | -------------------------------------------------------------------------------- /sphinx/_build/html/_static/cr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/cr.png -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/badge_only.css: -------------------------------------------------------------------------------- 1 | .fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-style:normal;font-weight:400;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#FontAwesome) format("svg")}.fa:before{font-family:FontAwesome;font-style:normal;font-weight:400;line-height:1}.fa:before,a .fa{text-decoration:inherit}.fa:before,a .fa,li .fa{display:inline-block}li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before,.icon-book:before{content:"\f02d"}.fa-caret-down:before,.icon-caret-down:before{content:"\f0d7"}.fa-caret-up:before,.icon-caret-up:before{content:"\f0d8"}.fa-caret-left:before,.icon-caret-left:before{content:"\f0d9"}.fa-caret-right:before,.icon-caret-right:before{content:"\f0da"}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60}.rst-versions .rst-current-version:after{clear:both;content:"";display:block}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-bold-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-bold-italic.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-bold-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-bold-italic.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-bold.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-bold.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-normal-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-normal-italic.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-normal-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-normal-italic.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-normal.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-normal.woff -------------------------------------------------------------------------------- /sphinx/_build/html/_static/css/fonts/lato-normal.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/css/fonts/lato-normal.woff2 -------------------------------------------------------------------------------- /sphinx/_build/html/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | var DOCUMENTATION_OPTIONS = { 2 | URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), 3 | VERSION: 'latest', 4 | LANGUAGE: 'None', 5 | COLLAPSE_INDEX: false, 6 | BUILDER: 'html', 7 | FILE_SUFFIX: '.html', 8 | LINK_SUFFIX: '.html', 9 | HAS_SOURCE: true, 10 | SOURCELINK_SUFFIX: '.txt', 11 | NAVIGATION_WITH_KEYS: false 12 | }; -------------------------------------------------------------------------------- /sphinx/_build/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_build/html/_static/file.png -------------------------------------------------------------------------------- /sphinx/_build/html/_static/js/badge_only.js: -------------------------------------------------------------------------------- 1 | !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=4)}({4:function(e,t,r){}}); -------------------------------------------------------------------------------- /sphinx/_build/html/_static/js/html5shiv-printshiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3-pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /sphinx/_build/html/_static/js/html5shiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /sphinx/_build/html/_static/js/theme.js: -------------------------------------------------------------------------------- 1 | !function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("
"),n("table.docutils.footnote").wrap("
"),n("table.docutils.citation").wrap("
"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n(''),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}t.length>0&&($(".wy-menu-vertical .current").removeClass("current"),t.addClass("current"),t.closest("li.toctree-l1").addClass("current"),t.closest("li.toctree-l1").parent().addClass("current"),t.closest("li.toctree-l1").addClass("current"),t.closest("li.toctree-l2").addClass("current"),t.closest("li.toctree-l3").addClass("current"),t.closest("li.toctree-l4").addClass("current"),t.closest("li.toctree-l5").addClass("current"),t[0].scrollIntoView())}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current"),e.siblings().find("li.current").removeClass("current"),e.find("> ul li.current").removeClass("current"),e.toggleClass("current")}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t 4 | 5 | 6 | 7 | 8 | 9 | 10 | Search — Cnerator latest documentation 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |
50 | 51 | 104 | 105 |
106 | 107 | 108 | 114 | 115 | 116 |
117 | 118 |
119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 |
139 | 140 |
    141 | 142 |
  • »
  • 143 | 144 |
  • Search
  • 145 | 146 | 147 |
  • 148 | 149 |
  • 150 | 151 |
152 | 153 | 154 |
155 |
156 |
157 |
158 | 159 | 166 | 167 | 168 |
169 | 170 |
171 | 172 |
173 | 174 |
175 |
176 | 177 |
178 | 179 |
180 |

181 | © Copyright 2021, Francisco Ortin and Javier Escalada. 182 | 183 |

184 |
185 | 186 | 187 | 188 | Built with Sphinx using a 189 | 190 | theme 191 | 192 | provided by Read the Docs. 193 | 194 |
195 |
196 |
197 | 198 |
199 | 200 |
201 | 202 | 203 | 208 | 209 | 210 | 211 | 212 | 213 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | -------------------------------------------------------------------------------- /sphinx/_static/cr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_static/cr.png -------------------------------------------------------------------------------- /sphinx/_static/transparent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_static/transparent.png -------------------------------------------------------------------------------- /sphinx/_static/uniovi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ComputationalReflection/Cnerator/e8791a10ad3ba1f9387f968543d559bc9ae7d99a/sphinx/_static/uniovi.png -------------------------------------------------------------------------------- /sphinx/cnerator.rst: -------------------------------------------------------------------------------- 1 | Cnerator module 2 | =============== 3 | 4 | .. automodule:: cnerator 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /sphinx/core.rst: -------------------------------------------------------------------------------- 1 | core package 2 | ============ 3 | 4 | .. automodule:: core 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | core.ast module 13 | --------------- 14 | 15 | .. automodule:: core.ast 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | core.generators module 21 | ---------------------- 22 | 23 | .. automodule:: core.generators 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | 29 | core.operators module 30 | --------------------- 31 | 32 | .. automodule:: core.operators 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | core.operators\_types module 38 | ---------------------------- 39 | 40 | .. automodule:: core.operators_types 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | core.probs module 46 | ----------------- 47 | 48 | .. automodule:: core.probs 49 | :members: 50 | :undoc-members: 51 | :show-inheritance: 52 | 53 | core.probs\_helper module 54 | ------------------------- 55 | 56 | .. automodule:: core.probs_helper 57 | :members: 58 | :undoc-members: 59 | :show-inheritance: 60 | 61 | core.type\_inference module 62 | --------------------------- 63 | 64 | .. automodule:: core.type_inference 65 | :members: 66 | :undoc-members: 67 | :show-inheritance: 68 | 69 | core.utils module 70 | ----------------- 71 | 72 | .. automodule:: core.utils 73 | :members: 74 | :undoc-members: 75 | :show-inheritance: 76 | 77 | 78 | -------------------------------------------------------------------------------- /sphinx/debug.rst: -------------------------------------------------------------------------------- 1 | debug package 2 | ============= 3 | 4 | .. automodule:: debug 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | debug.graph module 13 | ------------------ 14 | 15 | .. automodule:: debug.graph 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | debug.call\_inspector module 21 | ---------------------------- 22 | 23 | .. automodule:: debug.call_inspector 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | debug.structure\_inspector module 29 | --------------------------------- 30 | 31 | .. automodule:: debug.structure_inspector 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | 37 | -------------------------------------------------------------------------------- /sphinx/getting_started.rst: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | `Cnerator `_ is a C source code generation tool. 5 | It can be used to generate large amounts of 6 | `standard ANSI/ISO C source code `_, ready to be compiled 7 | by any standard language implementation. 8 | `Cnerator `_ is highly customizable 9 | to generate all the syntactic constructs of the C language, necessary to build 10 | accurate predictive models with machine learning algorithms. 11 | 12 | 13 | Installation 14 | ------------ 15 | 16 | You need a Python 3.7+ standard implementation. 17 | The only additional package to install is ``numpy``: 18 | 19 | 20 | .. code-block:: bash 21 | 22 | pip install numpy 23 | 24 | 25 | Usage 26 | ----- 27 | 28 | Then, you may just run `Cnerator `_ 29 | with no arguments to generate a random C program in the ``out`` directory: 30 | 31 | 32 | .. code-block:: bash 33 | 34 | python cnerator.py 35 | 36 | 37 | There are plenty of options to customize `Cnerator `_. 38 | To specify the probability of a particular language 39 | construct, you can use the ``-p`` or ``--probs`` option. 40 | The following command sets to 20% the probability of 41 | generating a function invocation when a new expression is required: 42 | 43 | .. code-block:: bash 44 | 45 | python cnerator.py -p "call_prob = {True: 0.2, False: 0.8}" 46 | 47 | 48 | If more sophisticated probabilities are required, you can specify them in a JSON file and pass it as 49 | a parameter (see the [documentation](documentation#probability-specification-files) to know the JSON file format). 50 | The following line passes an example JSON file in the ``json/probabilities`` folder where 51 | different probability distributions are specified for some syntactic constructs: 52 | 53 | .. code-block:: bash 54 | 55 | python cnerator.py -P json/probabilities/example_probs.json 56 | 57 | 58 | `Cnerator `_ also provides allows 59 | the user to control the number and characteristics of 60 | all the functions to be generated. A JSON file is used for that purpose 61 | (see the [documentation](documentation#function-generation-files)). 62 | The following command makes `Cnerator `_ 63 | generate one function for each high-level return 64 | type in the C programming language: 65 | 66 | 67 | .. code-block:: bash 68 | 69 | python cnerator.py -f json/functions/1-function-each-type.json 70 | 71 | 72 | Sometimes, the user needs the output program to fulfill some requirements not guaranteed by the 73 | stochastic generation process. 74 | To this aim, `Cnerator `_ allows 75 | the specification of an ordered collection of Python 76 | post-process specification files (see the [documentation](documentation#post-processing-specification-files)). 77 | These post-processing files can modify the generated code to satisfy those requirements. 78 | The following execution generates a random program and then executes two visitors: 79 | one to rename ``func`` functions to ``proc`` (and their invocations) when they return ``void``; 80 | and another one to add a ``__RETURN__`` label before each return statement: 81 | 82 | .. code-block:: bash 83 | 84 | python cnerator.py -V visitors.func_to_proc:visitors.return_instrumentation 85 | 86 | 87 | To see all the options, just run the ``-h`` or ``--help`` options. 88 | 89 | 90 | -------------------------------------------------------------------------------- /sphinx/index.rst: -------------------------------------------------------------------------------- 1 | .. Cnerator documentation master file, created by 2 | sphinx-quickstart on Wed Jan 20 14:07:57 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Cnerator's documentation! 7 | ==================================== 8 | 9 | .. image:: https://img.shields.io/github/license/ComputationalReflection/cnerator 10 | :alt: License 11 | :target: https://github.com/ComputationalReflection/Cnerator/blob/main/LICENSE 12 | 13 | .. image:: https://img.shields.io/github/v/release/computationalreflection/cnerator?include_prereleases 14 | :alt: Latest release 15 | :target: https://github.com/ComputationalReflection/cnerator/releases 16 | 17 | .. image:: https://img.shields.io/static/v1?label=docs&message=Sphinx&color=blue 18 | :alt: Documentation 19 | :target: https://computationalreflection.github.io/Cnerator/ 20 | 21 | .. image:: https://img.shields.io/github/languages/code-size/computationalreflection/cnerator 22 | :alt: Code size 23 | :target: https://github.com/ComputationalReflection/Cnerator 24 | 25 | .. image:: https://img.shields.io/github/repo-size/computationalreflection/cnerator 26 | :alt: Repo size 27 | :target: https://github.com/ComputationalReflection/Cnerator 28 | 29 | 30 | `Cnerator `_ is a C source code generation tool. 31 | Generated programs can be compiled with any standard ANSI C compiler. 32 | The user may define different parameters such as the number of function to be generated or the probabilities 33 | of all the different syntactic constructs. 34 | 35 | 36 | Contents: 37 | --------- 38 | 39 | .. toctree:: 40 | :maxdepth: 2 41 | 42 | getting_started 43 | user_manual 44 | modules 45 | 46 | 47 | 48 | Indices and tables: 49 | ------------------- 50 | 51 | * :ref:`genindex` 52 | * :ref:`modindex` 53 | 54 | | 55 | 56 | .. image:: _static/transparent.png 57 | :alt: Computational Reflection research group 58 | :align: center 59 | :target: http://www.reflection.uniovi.es 60 | :width: 25% 61 | 62 | 63 | -------------------------------------------------------------------------------- /sphinx/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /sphinx/modules.rst: -------------------------------------------------------------------------------- 1 | Cnerator API 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | cnerator 8 | core 9 | debug 10 | params 11 | run 12 | visitors 13 | -------------------------------------------------------------------------------- /sphinx/params.rst: -------------------------------------------------------------------------------- 1 | params package 2 | ============== 3 | 4 | .. automodule:: params 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | params.epilog module 14 | -------------------- 15 | 16 | .. automodule:: params.epilog 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | params.json\_probs module 22 | ------------------------- 23 | 24 | .. automodule:: params.json_probs 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | params.parameters module 30 | ------------------------ 31 | 32 | .. automodule:: params.parameters 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | params.writter module 38 | --------------------- 39 | 40 | .. automodule:: params.writter 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | 46 | -------------------------------------------------------------------------------- /sphinx/run.rst: -------------------------------------------------------------------------------- 1 | run package 2 | =========== 3 | 4 | .. automodule:: run 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | run.1\-function\-each\-type module 13 | ---------------------------------- 14 | 15 | .. automodule:: run.1_function_each_type 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | run.15\-function\-each\-type module 21 | ----------------------------------- 22 | 23 | .. automodule:: run.15_function_each_type 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | run.2000\-function\-void\-no\-void module 29 | ----------------------------------------- 30 | 31 | .. automodule:: run.2000_function_void_no_void 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | run.300\-function\-each\-type module 37 | ------------------------------------ 38 | 39 | .. automodule:: run.300_function_each_type 40 | :members: 41 | :undoc-members: 42 | :show-inheritance: 43 | 44 | run.article module 45 | ------------------ 46 | 47 | .. automodule:: run.article 48 | :members: 49 | :undoc-members: 50 | :show-inheritance: 51 | 52 | run.defaults module 53 | ------------------- 54 | 55 | .. automodule:: run.defaults 56 | :members: 57 | :undoc-members: 58 | :show-inheritance: 59 | 60 | run.defaults\_one\_file module 61 | ------------------------------ 62 | 63 | .. automodule:: run.defaults_one_file 64 | :members: 65 | :undoc-members: 66 | :show-inheritance: 67 | 68 | run.help module 69 | --------------- 70 | 71 | .. automodule:: run.help 72 | :members: 73 | :undoc-members: 74 | :show-inheritance: 75 | 76 | run.probs module 77 | ---------------- 78 | 79 | .. automodule:: run.probs 80 | :members: 81 | :undoc-members: 82 | :show-inheritance: 83 | 84 | run.probs\_file module 85 | ---------------------- 86 | 87 | .. automodule:: run.probs_file 88 | :members: 89 | :undoc-members: 90 | :show-inheritance: 91 | 92 | -------------------------------------------------------------------------------- /sphinx/visitors.rst: -------------------------------------------------------------------------------- 1 | visitors package 2 | ================ 3 | 4 | .. automodule:: visitors 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | 10 | Submodules 11 | ---------- 12 | 13 | visitors.fix\_ptr\_literal module 14 | --------------------------------- 15 | 16 | .. automodule:: visitors.fix_ptr_literal 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | visitors.func\_to\_proc module 22 | ------------------------------ 23 | 24 | .. automodule:: visitors.func_to_proc 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | visitors.function\_subs module 30 | ------------------------------ 31 | 32 | .. automodule:: visitors.function_subs 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | visitors.return\_instrumentation module 38 | --------------------------------------- 39 | 40 | .. automodule:: visitors.return_instrumentation 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | -------------------------------------------------------------------------------- /visitors/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Program representations (ASTs) in Cnerator can be processed / modified before the final generation 6 | of C source code. In order to do that, an introspective instance of the Visitor design pattern can be provided. 7 | If so, the ``-V`` or ``-Visitors`` options should be passed, including and ordered collection of visitors. 8 | In this package you can find different Visitor implementations. 9 | """ 10 | 11 | -------------------------------------------------------------------------------- /visitors/fix_ptr_literal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This visitor replaces all the pointer literals with a valid memory address. 6 | At code generation, pointers literals are just a 0 memory address. Here, they are replaced with memory 7 | addresses of global variables. 8 | """ 9 | 10 | from functools import singledispatch 11 | 12 | from core import ast, generators 13 | from core.utils import print_if_verbose 14 | 15 | 16 | @singledispatch 17 | def visit(node, program=None, function=None, **kwargs): 18 | raise TypeError("Unknown node type: " + node.__class__.__name__) 19 | 20 | 21 | @visit.register(ast.Program) 22 | def _(program: ast.Program, **kwargs) -> ast.Program: 23 | print_if_verbose() 24 | print_if_verbose("*" * 80) 25 | print_if_verbose("* FIX PTR LITERALS") 26 | print_if_verbose("*" * 80) 27 | 28 | for function in program.functions: 29 | visit(function, program, **kwargs) 30 | visit(program.main, program, **kwargs) 31 | return program 32 | 33 | 34 | @visit.register(ast.Function) 35 | def _(function: ast.Function, program: ast.Program, **kwargs) -> ast.Function: 36 | function.children = [ns for ns in (visit(s, program, function, **kwargs) for s in function.stmts) if ns is not None] 37 | return function 38 | 39 | 40 | @visit.register(ast.Invocation) 41 | def _(invocation: ast.Invocation, program: ast.Program, function: ast.Function, **kwargs) -> ast.Invocation: 42 | invocation.arguments = [visit(a, program, function, **kwargs) if isinstance(a, ast.ASTNode) else a 43 | for a in invocation.arguments] 44 | return invocation 45 | 46 | 47 | @visit.register(ast.Assignment) 48 | @visit.register(ast.BinaryExpression) 49 | @visit.register(ast.ArrayAccessExpression) 50 | @visit.register(ast.UnaryExpression) 51 | @visit.register(ast.Return) 52 | @visit.register(ast.StructAccessExpression) 53 | @visit.register(ast.TernaryExpression) 54 | @visit.register(ast.CastExpression) 55 | def _(node, program: ast.Program, function: ast.Function, **kwargs) -> ast.ASTNode: 56 | node.children = [visit(ch, program, function, **kwargs) if isinstance(ch, ast.ASTNode) else ch for ch in node.children] 57 | return node 58 | 59 | 60 | @visit.register(ast.Literal) 61 | def _(literal: ast.Literal, program: ast.Program, function: ast.Function, **kwargs) -> ast.ASTNode: 62 | if isinstance(literal.type, ast.Pointer): 63 | print_if_verbose("*" * 80) 64 | print_if_verbose(function.name) 65 | print_if_verbose(repr(literal.type)) 66 | try: 67 | global_var = program.global_vars[literal.type.type] 68 | except KeyError: 69 | print_if_verbose("NEW") 70 | global_var = generators.generate_global_var(program, function, literal.type.type) 71 | new_literal = ast.UnaryExpression("/* PTR LITERAL */ & ", global_var, literal.type.type, post_op=False) 72 | print_if_verbose(new_literal) 73 | print_if_verbose("*" * 80) 74 | return new_literal 75 | return literal 76 | 77 | 78 | @visit.register(ast.Block) 79 | def _(node: ast.Block, program: ast.Program, function: ast.Function, **kwargs): 80 | node.statements = [visit(stmt, program, function, **kwargs) for stmt in node.statements] 81 | return node 82 | 83 | 84 | @visit.register(ast.Do) 85 | @visit.register(ast.While) 86 | def _(node, program: ast.Program, function: ast.Function, **kwargs): 87 | node.condition = visit(node.condition, program, function, **kwargs) 88 | node.statements = [visit(stmt, program, function, **kwargs) if isinstance(stmt, ast.ASTNode) else stmt 89 | for stmt in node.statements] 90 | return node 91 | 92 | 93 | @visit.register(ast.If) 94 | def _(node: ast.If, program: ast.Program, function: ast.Function, **kwargs): 95 | node.condition = visit(node.condition, program, function, **kwargs) 96 | node.if_statements = [visit(stmt, program, function, **kwargs) for stmt in node.if_statements] 97 | node.else_statements = [visit(stmt, program, function, **kwargs) for stmt in node.else_statements] 98 | return node 99 | 100 | 101 | @visit.register(ast.For) 102 | def _(node: ast.For, program: ast.Program, function: ast.Function, **kwargs): 103 | node.initialization = visit(node.initialization, program, function, **kwargs) 104 | node.condition = visit(node.condition, program, function, **kwargs) 105 | node.increment = visit(node.increment, program, function, **kwargs) 106 | node.statements = [visit(stmt, program, function, **kwargs) for stmt in node.statements] 107 | return node 108 | 109 | 110 | @visit.register(ast.Switch) 111 | def _(node: ast.Switch, program: ast.Program, function: ast.Function, **kwargs): 112 | node.condition = visit(node.condition, program, function, **kwargs) 113 | for case_literal, case_statements in node.cases.items(): 114 | node.cases[case_literal] = [visit(stmt, program, function, **kwargs) for stmt in case_statements] 115 | node.default = [visit(stmt, program, function, **kwargs) for stmt in node.default] 116 | return node 117 | 118 | 119 | @visit.register(ast.Variable) 120 | @visit.register(ast.Label) 121 | @visit.register(ast.Break) 122 | def _(node, program: ast.Program, function: ast.Function, **kwargs) -> ast.ASTNode: 123 | return node 124 | 125 | -------------------------------------------------------------------------------- /visitors/func_to_proc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Example visitor that replaces the name of functions returning void. 5 | Its name prefix is changed from ``func`` to ``proc``. 6 | All the invocations are also renamed.""" 7 | 8 | 9 | from functools import singledispatch 10 | import core 11 | from core.utils import print_if_verbose 12 | from core import ast 13 | 14 | @singledispatch 15 | def visit(node): 16 | raise TypeError("Unknown node type: " + node.__class__.__name__) 17 | 18 | 19 | @visit.register(ast.Program) 20 | def _(program: ast.Program) -> None: 21 | print_if_verbose("") 22 | print_if_verbose("*" * 80) 23 | print_if_verbose("* FUNC TO PROC INSTRUMENTATION") 24 | print_if_verbose("*" * 80) 25 | for function in program.functions: 26 | visit(function) 27 | visit(program.main) 28 | 29 | 30 | @visit.register(ast.Function) 31 | def _(function: ast.Function) -> None: 32 | # Rename procedures 33 | if function.return_type == core.ast.Void(): 34 | print_if_verbose("Replacing func with proc: " + function.name) 35 | function.name = function.name.replace("func", "proc") 36 | for stmt in function.stmts: 37 | visit(stmt) 38 | 39 | 40 | @visit.register(ast.Invocation) 41 | def _(invocation: ast.Invocation) -> None: 42 | # Rename procedures 43 | if invocation.return_type == core.ast.Void(): 44 | invocation.func_name = invocation.func_name.replace("func", "proc") 45 | print_if_verbose("Replacing: " + invocation.func_name) 46 | 47 | 48 | @visit.register(ast.Block) 49 | def _(node: ast.Block) -> None: 50 | _visit_ast_nodes(node.statements) 51 | 52 | 53 | @visit.register(ast.Do) 54 | @visit.register(ast.While) 55 | def _(node) -> None: 56 | visit(node.condition) 57 | _visit_ast_nodes(node.statements) 58 | 59 | 60 | @visit.register(ast.If) 61 | def _(node: ast.If) -> None: 62 | visit(node.condition) 63 | _visit_ast_nodes(node.if_statements) 64 | _visit_ast_nodes(node.else_statements) 65 | 66 | 67 | @visit.register(ast.For) 68 | def _(node: ast.For) -> None: 69 | visit(node.initialization) 70 | visit(node.condition) 71 | visit(node.increment) 72 | _visit_ast_nodes(node.statements) 73 | 74 | 75 | @visit.register(ast.Switch) 76 | def _(node: ast.Switch) -> None: 77 | visit(node.condition) 78 | for case_literal, case_statements in node.cases.items(): 79 | _visit_ast_nodes(case_statements) 80 | _visit_ast_nodes(node.default) 81 | 82 | 83 | @visit.register(ast.Assignment) 84 | @visit.register(ast.BinaryASTNode) 85 | @visit.register(ast.UnaryASTNode) 86 | @visit.register(ast.TernaryASTNode) 87 | @visit.register(ast.Return) 88 | @visit.register(ast.Literal) 89 | @visit.register(ast.Variable) 90 | @visit.register(ast.Break) 91 | def _(_: ast.ASTNode) -> None: 92 | pass 93 | 94 | 95 | def _visit_ast_nodes(nodes: list) -> None: 96 | """Traverses the nodes and returns the new ones""" 97 | # the statement could be a type, and then it is not traversed (visited) 98 | for node in nodes: 99 | if isinstance(node, ast.ASTNode): 100 | visit(node) 101 | -------------------------------------------------------------------------------- /visitors/function_subs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Visitor to replace the invocations to functions that have been removed with the controlled function 5 | generation functionality (i.e., ``-f`` or ``--functions`` options).""" 6 | 7 | from functools import singledispatch 8 | from core import ast, generators, probs 9 | from params.parameters import get_app_args 10 | from typing import List, Union 11 | 12 | 13 | @singledispatch 14 | def visit(node, targets: List[str], function: ast.Function, is_statement: bool): 15 | raise TypeError("Unknown node type: " + node.__class__.__name__) 16 | 17 | _program = None 18 | 19 | @visit.register(ast.Program) 20 | def _(program: ast.Program, targets: List[str], function: ast.Function = None, is_statement: bool = True) -> ast.Program: 21 | # Pointers, Struct and Arrays only generate literals in declarations. The normal solution is to 22 | # generate a lvalue instead, this solution can cause the creation of new functions. The solution to this new problem 23 | # is to eliminate the probability of invocation before generate a new literal. 24 | global _program 25 | _program = program 26 | 27 | new_probs = {False: 1, True: 0} 28 | old_probs = dict(probs.call_prob) 29 | probs.call_prob = new_probs 30 | 31 | for function in program.functions: 32 | visit(function, targets, function, True) 33 | visit(program.main, targets, program.main, True) 34 | 35 | # Restore the old probability 36 | probs.call_prob = dict(old_probs) 37 | return program 38 | 39 | 40 | @visit.register(ast.Function) 41 | def _(node: ast.Function, targets: List[str], function: ast.Function, is_statement: bool) -> ast.Function: 42 | node.children = _visit_ast_nodes(node.stmts, targets, node, True) 43 | return node 44 | 45 | 46 | @visit.register(ast.Invocation) 47 | def _(invocation: ast.Invocation, targets: List[str], function: ast.Function, is_statement: bool) \ 48 | -> Union[ast.ASTNode, None]: 49 | if invocation.func_name in targets and not isinstance(invocation.return_type, ast.Void): 50 | # If invocation is a statement 51 | if is_statement: 52 | if get_app_args().verbose: 53 | print("{}: Remove call {}".format(function.name, invocation.func_name)) 54 | return None 55 | # If invocation is an expression 56 | else: 57 | literal = generators.generate_literal( 58 | _program, function, invocation.return_type, from_declaration=False) 59 | if get_app_args().verbose: 60 | print("{} Subs call {} -> ({}) {}".format( 61 | function.name, invocation.func_name, invocation.return_type.name, literal.to_str())) 62 | return literal 63 | else: 64 | invocation.arguments = _visit_ast_nodes(invocation.arguments, targets, function, False) 65 | return invocation 66 | 67 | 68 | @visit.register(ast.Assignment) 69 | @visit.register(ast.BinaryExpression) 70 | @visit.register(ast.ArrayAccessExpression) 71 | @visit.register(ast.UnaryExpression) 72 | @visit.register(ast.Return) 73 | @visit.register(ast.StructAccessExpression) 74 | @visit.register(ast.TernaryExpression) 75 | def _(node, targets: List[str], function: ast.Function, is_statement: bool) -> ast.ASTNode: 76 | node.children = _visit_ast_nodes(node.children, targets, function, False) 77 | return node 78 | 79 | 80 | @visit.register(ast.Block) 81 | def _(node: ast.Block, targets: List[str], function: ast.Function, is_statement: bool) -> ast.Block: 82 | node.statements = _visit_ast_nodes(node.statements, targets, function, True) 83 | return node 84 | 85 | 86 | @visit.register(ast.Do) 87 | @visit.register(ast.While) 88 | def _(node, targets: List[str], function: ast.Function, is_statement: bool) -> ast.ASTNode: 89 | node.condition = visit(node.condition, targets, function, False) 90 | node.statements = _visit_ast_nodes(node.statements, targets, function, True) 91 | return node 92 | 93 | 94 | @visit.register(ast.If) 95 | def _(node: ast.If, targets: List[str], function: ast.Function, is_statement: bool) -> ast.If: 96 | node.condition = visit(node.condition, targets, function, False) 97 | node.if_statements = _visit_ast_nodes(node.if_statements, targets, function, True) 98 | node.else_statements = _visit_ast_nodes(node.else_statements, targets, function, True) 99 | return node 100 | 101 | 102 | @visit.register(ast.For) 103 | def _(node: ast.For, targets: List[str], function: ast.Function, is_statement: bool) -> ast.For: 104 | node.initialization = visit(node.initialization, targets, function, False) 105 | node.condition = visit(node.condition, targets, function, False) 106 | node.increment = visit(node.increment, targets, function, False) 107 | node.statements = _visit_ast_nodes(node.statements, targets, function, True) 108 | return node 109 | 110 | 111 | @visit.register(ast.Switch) 112 | def _(node: ast.Switch, targets: List[str], function: ast.Function, is_statement: bool) -> ast.Switch: 113 | node.condition = visit(node.condition, targets, function, False) 114 | for case_literal, case_statements in node.cases.items(): 115 | node.cases[case_literal] = _visit_ast_nodes(case_statements, targets, function, True) 116 | node.default = _visit_ast_nodes(node.default, targets, function, True) 117 | return node 118 | 119 | 120 | @visit.register(ast.Literal) 121 | @visit.register(ast.Variable) 122 | @visit.register(ast.Break) 123 | @visit.register(ast.Label) 124 | def _(node, targets: List[str], function: ast.Function, is_statement: bool) -> ast.ASTNode: 125 | return node 126 | 127 | 128 | def _visit_ast_nodes(nodes: list, targets: List[str], function: ast.Function, is_statement: bool) -> list: 129 | """Traverses the nodes and returns the new ones""" 130 | # the statement could be a type, and then it is not traversed (visited) 131 | result_nodes = list() 132 | for node in nodes: 133 | if isinstance(node, ast.ASTNode): 134 | # it is an ASTNode (not a type) 135 | new_node = visit(node, targets, function, is_statement) 136 | if new_node is not None: # this visitor removes invocations, so there might be stmts removed 137 | result_nodes.append(new_node) 138 | else: # not an ASTNode 139 | result_nodes.append(node) 140 | return result_nodes 141 | -------------------------------------------------------------------------------- /visitors/return_instrumentation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Example visitor that adds a return label before every expression in a return statement. 5 | The purpose is to identify the binary code used to return from a function. 6 | If the function returns ``void``, a label and an explicit return function is added at the end of the function.""" 7 | 8 | 9 | from functools import singledispatch 10 | from core.utils import print_if_verbose 11 | from typing import List 12 | from core import ast 13 | 14 | _return_label_counter = 0 15 | 16 | 17 | def generate_label() -> str: 18 | """Generates a new unique label string""" 19 | global _return_label_counter 20 | _return_label_counter += 1 21 | return f"__RETURN{_return_label_counter}__" 22 | 23 | 24 | @singledispatch 25 | def visit(node): 26 | raise TypeError("Unknown node type: " + node.__class__.__name__) 27 | 28 | 29 | @visit.register(ast.Program) 30 | def _(program: ast.Program): 31 | print_if_verbose("") 32 | print_if_verbose("*" * 80) 33 | print_if_verbose("* RETURN INSTRUMENTATION") 34 | print_if_verbose("*" * 80) 35 | for function in program.functions: 36 | visit(function) 37 | visit(program.main) 38 | 39 | 40 | def _instrument_statements(statements: List[ast.ASTNode]) -> List[ast.ASTNode]: 41 | """Includes a label before the return statements""" 42 | instrumented_stmts = [] 43 | for stmt in statements: 44 | if isinstance(stmt, ast.Return): 45 | print_if_verbose(f"Return stmt: {stmt.to_str()}") 46 | label_ast = ast.Label(generate_label()) 47 | instrumented_stmts.append(label_ast) 48 | visit(stmt) 49 | instrumented_stmts.append(stmt) 50 | return instrumented_stmts 51 | 52 | 53 | @visit.register(ast.Function) 54 | def _(function: ast.Function): 55 | """Traverses a function definition to add a RETURN label before each return statement""" 56 | function.stmts = _instrument_statements(function.stmts) 57 | # If is a procedure add at the end a return statement 58 | if isinstance(function.return_type, ast.Void): 59 | function.stmts.append(ast.Label(generate_label())) 60 | function.stmts.append(ast.Return()) 61 | 62 | 63 | @visit.register(ast.Block) 64 | @visit.register(ast.Do) 65 | @visit.register(ast.While) 66 | @visit.register(ast.For) 67 | def _(node): 68 | """Traverses a control flow statement to add a RETURN label before each return statement""" 69 | node.statements = _instrument_statements(node.statements) 70 | 71 | 72 | @visit.register(ast.If) 73 | def _(node: ast.If): 74 | # include RETURN label before return statements in if and else bodies 75 | node.if_statements = _instrument_statements(node.if_statements) 76 | node.else_statements = _instrument_statements(node.else_statements) 77 | 78 | 79 | @visit.register(ast.Switch) 80 | def _(node: ast.Switch): 81 | # include RETURN label before return statements in case and default blocks 82 | for case_literal, case_statements in node.cases.items(): 83 | node.cases[case_literal] = _instrument_statements(node.cases[case_literal]) 84 | node.default = _instrument_statements(node.default) 85 | 86 | 87 | @visit.register(ast.Assignment) 88 | @visit.register(ast.UnaryExpression) 89 | @visit.register(ast.Return) 90 | @visit.register(ast.Invocation) 91 | @visit.register(ast.Variable) 92 | @visit.register(ast.Literal) 93 | @visit.register(ast.TernaryASTNode) 94 | @visit.register(ast.BinaryASTNode) 95 | @visit.register(ast.UnaryASTNode) 96 | @visit.register(ast.Break) 97 | @visit.register(ast.Label) 98 | def _(statement): 99 | pass 100 | 101 | 102 | --------------------------------------------------------------------------------