├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── modparc.rst ├── modparc.syntax.rst ├── modules.rst ├── readme.rst ├── syntax_class_definition.dot ├── syntax_class_definition.svg ├── syntax_component_clause.dot ├── syntax_component_clause.svg ├── syntax_equation.dot ├── syntax_equation.svg ├── syntax_expression.dot ├── syntax_expression.svg ├── syntax_extends.dot ├── syntax_extends.svg ├── syntax_full.dot ├── syntax_full.svg ├── syntax_modification.dot ├── syntax_modification.svg ├── syntax_stored_definition.dot ├── syntax_stored_definition.svg └── usage.rst ├── modparc ├── __init__.py ├── parse.py ├── specification.py └── syntax │ ├── __init__.py │ ├── class_definition.py │ ├── component_clause.py │ ├── equations.py │ ├── expressions.py │ ├── extends.py │ ├── modification.py │ ├── stored_definition.py │ └── syntax_elements.py ├── pylintrc ├── requirements.txt ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py └── test_modparc.py ├── tox.ini └── travis_pypi_setup.py /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Modelica Parser version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ``` 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /.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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # pyenv python configuration file 62 | .python-version 63 | 64 | # pycharm 65 | .idea 66 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | # This file will be regenerated if you run travis_pypi_setup.py 3 | 4 | language: python 5 | python: 6 | - "3.5" 7 | 8 | env: 9 | - TOXENV=py35 10 | - TOXENV=py34 11 | - TOXENV=py27 12 | 13 | # command to install dependencies, e.g. pip install -r requirements.txt 14 | install: pip install -r requirements_dev.txt 15 | 16 | # command to run tests, e.g. python setup.py test 17 | script: tox -e ${TOXENV} 18 | 19 | # After you create the Github repo and add it to Travis, run the 20 | # travis_pypi_setup.py script to finish PyPI deployment setup 21 | deploy: 22 | provider: pypi 23 | distributions: sdist bdist_wheel 24 | user: xie-dongping 25 | password: 26 | secure: ${PYPI_PASSWORD} 27 | on: 28 | tags: true 29 | repo: xie-dongping/modparc 30 | condition: $TOXENV == py35 31 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Author 6 | ---------------- 7 | 8 | * 谢东平 Dongping XIE 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every 8 | little bit helps, and credit will always be given. 9 | 10 | You can contribute in many ways: 11 | 12 | Types of Contributions 13 | ---------------------- 14 | 15 | Report Bugs 16 | ~~~~~~~~~~~ 17 | 18 | Report bugs at https://github.com/xie-dongping/modparc/issues. 19 | 20 | If you are reporting a bug, please include: 21 | 22 | * Your Python version and the result of a `pip list` 23 | * Detailed steps to reproduce the bug, ideally a test case. 24 | 25 | Fix Bugs 26 | ~~~~~~~~ 27 | 28 | Look through the GitHub issues for bugs. Anything tagged with "bug" 29 | and "help wanted" is open to whoever wants to implement it. 30 | 31 | Implement Features 32 | ~~~~~~~~~~~~~~~~~~ 33 | 34 | Look through the GitHub issues for features. Anything tagged with "enhancement" 35 | and "help wanted" is open to whoever wants to implement it. 36 | 37 | Write Documentation 38 | ~~~~~~~~~~~~~~~~~~~ 39 | 40 | Modelica Parser could always use more documentation, whether as part of the 41 | official Parser docs, in docstrings, or even on the web in blog posts, 42 | articles, and such. 43 | 44 | Submit Feedback 45 | ~~~~~~~~~~~~~~~ 46 | 47 | The best way to send feedback is to file an issue at https://github.com/xie-dongping/modparc/issues. 48 | 49 | If you are proposing a feature: 50 | 51 | * Explain in detail how it would work. 52 | * Keep the scope as narrow as possible, to make it easier to implement. 53 | * Remember that this is a volunteer-driven project, and that contributions 54 | are welcome :) 55 | 56 | Get Started! 57 | ------------ 58 | 59 | Ready to contribute? Here's how to set up `modparc` for local development. 60 | 61 | 1. Fork the `modparc` repo on GitHub. 62 | 2. Clone your fork locally:: 63 | 64 | $ git clone git@github.com:your_name_here/modparc.git 65 | 66 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 67 | 68 | $ mkvirtualenv modparc 69 | $ cd modparc/ 70 | $ python setup.py develop 71 | 72 | 4. Create a branch for local development:: 73 | 74 | $ git checkout -b name-of-your-bugfix-or-feature 75 | 76 | Now you can make your changes locally. 77 | 78 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 modparc tests 81 | $ python setup.py test or py.test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests, unless it is a minor fix. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check 104 | https://travis-ci.org/xie-dongping/modparc/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ py.test tests.test_modparc 113 | 114 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | History 3 | ======= 4 | 5 | 0.1.5 (2016-10-22) 6 | ------------------ 7 | 8 | * First release on PyPI. 9 | 10 | 0.2.0 (2016-10-22) 11 | ------------------ 12 | 13 | * Get names and types of the defintions 14 | * Roundtripping of the defintions 15 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | 2 | include AUTHORS.rst 3 | 4 | include CONTRIBUTING.rst 5 | include HISTORY.rst 6 | include LICENSE 7 | include README.rst 8 | 9 | recursive-include tests * 10 | recursive-exclude * __pycache__ 11 | recursive-exclude * *.py[co] 12 | 13 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 14 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | flake8 modparc tests 52 | 53 | test: ## run tests quickly with the default Python 54 | py.test 55 | 56 | 57 | test-all: ## run tests on every Python version with tox 58 | tox 59 | 60 | coverage: ## check code coverage quickly with the default Python 61 | coverage run --source modparc py.test 62 | 63 | coverage report -m 64 | coverage html 65 | $(BROWSER) htmlcov/index.html 66 | 67 | docs: ## generate Sphinx HTML documentation, including API docs 68 | rm -f docs/modparc.rst 69 | rm -f docs/modules.rst 70 | sphinx-apidoc -o docs/ modparc 71 | $(MAKE) -C docs clean 72 | $(MAKE) -C docs html 73 | $(BROWSER) docs/_build/html/index.html 74 | 75 | servedocs: docs ## compile the docs watching for changes 76 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 77 | 78 | release: clean ## package and upload a release 79 | python setup.py sdist upload 80 | python setup.py bdist_wheel upload 81 | 82 | dist: clean ## builds source and wheel package 83 | python setup.py sdist 84 | python setup.py bdist_wheel 85 | ls -l dist 86 | 87 | install: clean ## install the package to the active Python's site-packages 88 | python setup.py install 89 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | modparc 3 | =============================== 4 | 5 | 6 | .. image:: https://img.shields.io/pypi/v/modparc.svg 7 | :target: https://pypi.python.org/pypi/modparc 8 | 9 | .. image:: https://img.shields.io/travis/xie-dongping/modparc.svg 10 | :target: https://travis-ci.org/xie-dongping/modparc 11 | 12 | .. image:: https://readthedocs.org/projects/modparc/badge/?version=latest 13 | :target: https://modparc.readthedocs.io/en/latest/?badge=latest 14 | :alt: Documentation Status 15 | 16 | .. image:: https://pyup.io/repos/github/xie-dongping/modparc/shield.svg 17 | :target: https://pyup.io/repos/github/xie-dongping/modparc/ 18 | :alt: Updates 19 | 20 | 21 | modparc is a Modelica parser in Python based on parser combinator. 22 | 23 | 24 | * Free software: GNU General Public License v3 25 | * Source code: https://github.com/xie-dongping/modparc. 26 | * Documentation: https://modparc.readthedocs.io. 27 | 28 | .. contents:: 29 | 30 | Quickstart 31 | ---------- 32 | 33 | Install the package from PyPI: 34 | 35 | .. code-block:: bash 36 | 37 | $ pip install modparc 38 | 39 | 40 | To parse a Modelica source file `"your_modelica_file.mo"`: 41 | 42 | .. code-block:: python 43 | 44 | import modparc 45 | model_definition = modparc.parse_file("your_modelica_file.mo") 46 | 47 | To list all the equations in the `model_definition` instance: 48 | 49 | .. code-block:: python 50 | 51 | all_equations = model_definition.search('Equation') 52 | for equation in all_equations: 53 | print(equation.code()) # The code of the equation as string 54 | 55 | To get the name of the model loaded: 56 | 57 | .. code-block:: python 58 | 59 | print(model_definition.name()) # get the name of the stored class 60 | print(model_definition.class_type()) # get the type of the class 61 | 62 | Features 63 | -------- 64 | 65 | * Experimentally parses Modelica Standard Library 3.2.1 66 | * Search element of a certain class 67 | 68 | Known Issues 69 | ------------ 70 | 71 | * Handling tokenization of Q-IDENT and comments, which comes first? 72 | * Assertion syntax not defined in Modelica specification 73 | * Default recursion depth is not enough for long vector literals 74 | * Cyclic import is neccessary for the Modelica syntax definition 75 | 76 | Credits 77 | ------- 78 | 79 | This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. 80 | 81 | The test cases used code from the `ModelicaByExample library (MIT License by Michael Tiller)`_. 82 | 83 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 84 | .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 85 | .. _`ModelicaByExample`: https://github.com/xogeny/ModelicaBook 86 | 87 | 88 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/modparc.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/modparc.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/modparc" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/modparc" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # modparc documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import modparc 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'Modelica Parser' 59 | copyright = u"2016, 谢东平 Dongping XIE" 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = modparc.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = modparc.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'modparcdoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'modparc.tex', 212 | u'Modelica Parser Documentation', 213 | u'谢东平 Dongping XIE', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'modparc', 243 | u'Modelica Parser Documentation', 244 | [u'谢东平 Dongping XIE'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'modparc', 258 | u'Modelica Parser Documentation', 259 | u'谢东平 Dongping XIE', 260 | 'modparc', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. modparc documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 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 modparc Modelica Parser's documentation! 7 | ================================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | 21 | Indices and tables 22 | ================== 23 | 24 | * :ref:`genindex` 25 | * :ref:`modindex` 26 | * :ref:`search` 27 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | 8 | Stable release 9 | -------------- 10 | 11 | To install Modelica Parser, run this command in your terminal: 12 | 13 | .. code-block:: console 14 | 15 | $ pip install modparc 16 | 17 | This is the preferred method to install Modelica Parser, as it will always install the most recent stable release. 18 | 19 | If you don't have `pip`_ installed, this `Python installation guide`_ can guide 20 | you through the process. 21 | 22 | .. _pip: https://pip.pypa.io 23 | .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ 24 | 25 | 26 | From sources 27 | ------------ 28 | 29 | The sources for Modelica Parser can be downloaded from the `Github repo`_. 30 | 31 | You can either clone the public repository: 32 | 33 | .. code-block:: console 34 | 35 | $ git clone git://github.com/xie-dongping/modparc 36 | 37 | Or download the `tarball`_: 38 | 39 | .. code-block:: console 40 | 41 | $ curl -OL https://github.com/xie-dongping/modparc/tarball/master 42 | 43 | Once you have a copy of the source, you can install it with: 44 | 45 | .. code-block:: console 46 | 47 | $ python setup.py install 48 | 49 | 50 | .. _Github repo: https://github.com/xie-dongping/modparc 51 | .. _tarball: https://github.com/xie-dongping/modparc/tarball/master 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\modparc.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\modparc.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/modparc.rst: -------------------------------------------------------------------------------- 1 | modparc package 2 | =============== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | modparc.syntax 10 | 11 | Submodules 12 | ---------- 13 | 14 | modparc.parse module 15 | -------------------- 16 | 17 | .. automodule:: modparc.parse 18 | :members: 19 | :undoc-members: 20 | :show-inheritance: 21 | 22 | modparc.specification module 23 | ---------------------------- 24 | 25 | .. automodule:: modparc.specification 26 | :members: 27 | :undoc-members: 28 | :show-inheritance: 29 | 30 | 31 | Module contents 32 | --------------- 33 | 34 | .. automodule:: modparc 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | -------------------------------------------------------------------------------- /docs/modparc.syntax.rst: -------------------------------------------------------------------------------- 1 | modparc.syntax package 2 | ====================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | modparc.syntax.class_definition module 8 | -------------------------------------- 9 | 10 | .. automodule:: modparc.syntax.class_definition 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | modparc.syntax.component_clause module 16 | -------------------------------------- 17 | 18 | .. automodule:: modparc.syntax.component_clause 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | modparc.syntax.equations module 24 | ------------------------------- 25 | 26 | .. automodule:: modparc.syntax.equations 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | modparc.syntax.expressions module 32 | --------------------------------- 33 | 34 | .. automodule:: modparc.syntax.expressions 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | modparc.syntax.extends module 40 | ----------------------------- 41 | 42 | .. automodule:: modparc.syntax.extends 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | modparc.syntax.modification module 48 | ---------------------------------- 49 | 50 | .. automodule:: modparc.syntax.modification 51 | :members: 52 | :undoc-members: 53 | :show-inheritance: 54 | 55 | modparc.syntax.stored_definition module 56 | --------------------------------------- 57 | 58 | .. automodule:: modparc.syntax.stored_definition 59 | :members: 60 | :undoc-members: 61 | :show-inheritance: 62 | 63 | modparc.syntax.syntax_elements module 64 | ------------------------------------- 65 | 66 | .. automodule:: modparc.syntax.syntax_elements 67 | :members: 68 | :undoc-members: 69 | :show-inheritance: 70 | 71 | 72 | Module contents 73 | --------------- 74 | 75 | .. automodule:: modparc.syntax 76 | :members: 77 | :undoc-members: 78 | :show-inheritance: 79 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | modparc 2 | ======= 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | modparc 8 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/syntax_class_definition.dot: -------------------------------------------------------------------------------- 1 | digraph class_definition { 2 | "class_definition" -> "class_prefixes" 3 | "class_definition" -> "class_specifier" 4 | "class_specifier" -> "string_comment" 5 | "class_specifier" -> "composition" 6 | "class_specifier" -> "base_prefix" 7 | "class_specifier" -> "name" 8 | "class_specifier" -> "array_subscripts" 9 | "class_specifier" -> "class_modification" 10 | "class_specifier" -> "comment" 11 | "class_specifier" -> "enumeration" 12 | "class_specifier" -> "enum_list" 13 | "class_specifier" -> "class_modification" 14 | "class_specifier" -> "string_comment" 15 | "class_specifier" -> "composition" 16 | "base_prefix" -> "type_prefix" 17 | "enum_list" -> "enumeration_literal" 18 | "enumeration_literal" -> "comment" 19 | "composition" -> "element_list" 20 | "composition" -> "equation_section" 21 | "composition" -> "algorithm_section" 22 | "composition" -> "language_specification" 23 | "composition" -> "external_function_call" 24 | "composition" -> "annotation" 25 | "external_function_call" -> "component_reference" 26 | "external_function_call" -> "expression_list" 27 | "element_list" -> "element" 28 | "element" -> "import_clause" 29 | "extends_clause" -> "class_definition" 30 | "extends_clause" -> "component_clause" 31 | "extends_clause" -> "constraining_clause" 32 | "extends_clause" -> "comment" 33 | "import_clause" -> "name" 34 | "import_clause" -> "import_list" 35 | "import_clause" -> "comment" 36 | "import_list" -> "import_list" 37 | } 38 | -------------------------------------------------------------------------------- /docs/syntax_class_definition.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | class_definition 11 | 12 | 13 | class_definition 14 | 15 | class_definition 16 | 17 | 18 | class_prefixes 19 | 20 | class_prefixes 21 | 22 | 23 | class_definition->class_prefixes 24 | 25 | 26 | 27 | 28 | class_specifier 29 | 30 | class_specifier 31 | 32 | 33 | class_definition->class_specifier 34 | 35 | 36 | 37 | 38 | string_comment 39 | 40 | string_comment 41 | 42 | 43 | class_specifier->string_comment 44 | 45 | 46 | 47 | 48 | class_specifier->string_comment 49 | 50 | 51 | 52 | 53 | composition 54 | 55 | composition 56 | 57 | 58 | class_specifier->composition 59 | 60 | 61 | 62 | 63 | class_specifier->composition 64 | 65 | 66 | 67 | 68 | base_prefix 69 | 70 | base_prefix 71 | 72 | 73 | class_specifier->base_prefix 74 | 75 | 76 | 77 | 78 | name 79 | 80 | name 81 | 82 | 83 | class_specifier->name 84 | 85 | 86 | 87 | 88 | array_subscripts 89 | 90 | array_subscripts 91 | 92 | 93 | class_specifier->array_subscripts 94 | 95 | 96 | 97 | 98 | class_modification 99 | 100 | class_modification 101 | 102 | 103 | class_specifier->class_modification 104 | 105 | 106 | 107 | 108 | class_specifier->class_modification 109 | 110 | 111 | 112 | 113 | comment 114 | 115 | comment 116 | 117 | 118 | class_specifier->comment 119 | 120 | 121 | 122 | 123 | enumeration 124 | 125 | enumeration 126 | 127 | 128 | class_specifier->enumeration 129 | 130 | 131 | 132 | 133 | enum_list 134 | 135 | enum_list 136 | 137 | 138 | class_specifier->enum_list 139 | 140 | 141 | 142 | 143 | element_list 144 | 145 | element_list 146 | 147 | 148 | composition->element_list 149 | 150 | 151 | 152 | 153 | equation_section 154 | 155 | equation_section 156 | 157 | 158 | composition->equation_section 159 | 160 | 161 | 162 | 163 | algorithm_section 164 | 165 | algorithm_section 166 | 167 | 168 | composition->algorithm_section 169 | 170 | 171 | 172 | 173 | language_specification 174 | 175 | language_specification 176 | 177 | 178 | composition->language_specification 179 | 180 | 181 | 182 | 183 | external_function_call 184 | 185 | external_function_call 186 | 187 | 188 | composition->external_function_call 189 | 190 | 191 | 192 | 193 | annotation 194 | 195 | annotation 196 | 197 | 198 | composition->annotation 199 | 200 | 201 | 202 | 203 | type_prefix 204 | 205 | type_prefix 206 | 207 | 208 | base_prefix->type_prefix 209 | 210 | 211 | 212 | 213 | enumeration_literal 214 | 215 | enumeration_literal 216 | 217 | 218 | enum_list->enumeration_literal 219 | 220 | 221 | 222 | 223 | enumeration_literal->comment 224 | 225 | 226 | 227 | 228 | element 229 | 230 | element 231 | 232 | 233 | element_list->element 234 | 235 | 236 | 237 | 238 | component_reference 239 | 240 | component_reference 241 | 242 | 243 | external_function_call->component_reference 244 | 245 | 246 | 247 | 248 | expression_list 249 | 250 | expression_list 251 | 252 | 253 | external_function_call->expression_list 254 | 255 | 256 | 257 | 258 | import_clause 259 | 260 | import_clause 261 | 262 | 263 | element->import_clause 264 | 265 | 266 | 267 | 268 | import_clause->name 269 | 270 | 271 | 272 | 273 | import_clause->comment 274 | 275 | 276 | 277 | 278 | import_list 279 | 280 | import_list 281 | 282 | 283 | import_clause->import_list 284 | 285 | 286 | 287 | 288 | extends_clause 289 | 290 | extends_clause 291 | 292 | 293 | extends_clause->class_definition 294 | 295 | 296 | 297 | 298 | extends_clause->comment 299 | 300 | 301 | 302 | 303 | component_clause 304 | 305 | component_clause 306 | 307 | 308 | extends_clause->component_clause 309 | 310 | 311 | 312 | 313 | constraining_clause 314 | 315 | constraining_clause 316 | 317 | 318 | extends_clause->constraining_clause 319 | 320 | 321 | 322 | 323 | import_list->import_list 324 | 325 | 326 | 327 | 328 | 329 | -------------------------------------------------------------------------------- /docs/syntax_component_clause.dot: -------------------------------------------------------------------------------- 1 | digraph component_clause { 2 | "component_clause" -> "type_prefix" 3 | "component_clause" -> "type_specifier" 4 | "component_clause" -> "array_subscripts" 5 | "component_clause" -> "component_list" 6 | "type_specifier" -> "name" 7 | "component_list" -> "component_declaration" 8 | "component_declaration" -> "declaration" 9 | "component_declaration" -> "comment" 10 | "component_declaration" -> "condition_attribute" 11 | "condition_attribute" -> "expression" 12 | "declaration" -> "array_subscripts" 13 | "declaration" -> "modification" 14 | } 15 | -------------------------------------------------------------------------------- /docs/syntax_component_clause.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | component_clause 11 | 12 | 13 | component_clause 14 | 15 | component_clause 16 | 17 | 18 | type_prefix 19 | 20 | type_prefix 21 | 22 | 23 | component_clause->type_prefix 24 | 25 | 26 | 27 | 28 | type_specifier 29 | 30 | type_specifier 31 | 32 | 33 | component_clause->type_specifier 34 | 35 | 36 | 37 | 38 | array_subscripts 39 | 40 | array_subscripts 41 | 42 | 43 | component_clause->array_subscripts 44 | 45 | 46 | 47 | 48 | component_list 49 | 50 | component_list 51 | 52 | 53 | component_clause->component_list 54 | 55 | 56 | 57 | 58 | name 59 | 60 | name 61 | 62 | 63 | type_specifier->name 64 | 65 | 66 | 67 | 68 | component_declaration 69 | 70 | component_declaration 71 | 72 | 73 | component_list->component_declaration 74 | 75 | 76 | 77 | 78 | declaration 79 | 80 | declaration 81 | 82 | 83 | component_declaration->declaration 84 | 85 | 86 | 87 | 88 | comment 89 | 90 | comment 91 | 92 | 93 | component_declaration->comment 94 | 95 | 96 | 97 | 98 | condition_attribute 99 | 100 | condition_attribute 101 | 102 | 103 | component_declaration->condition_attribute 104 | 105 | 106 | 107 | 108 | declaration->array_subscripts 109 | 110 | 111 | 112 | 113 | modification 114 | 115 | modification 116 | 117 | 118 | declaration->modification 119 | 120 | 121 | 122 | 123 | expression 124 | 125 | expression 126 | 127 | 128 | condition_attribute->expression 129 | 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /docs/syntax_equation.dot: -------------------------------------------------------------------------------- 1 | digraph equations { 2 | "equation_section" -> "equation" 3 | "algorithm_section" -> "statement" 4 | "equation" -> "simple_expression" 5 | "equation" -> "expression" 6 | "equation" -> "if_equation" 7 | "equation" -> "for_equation" 8 | "equation" -> "connect_clause" 9 | "equation" -> "when_equation" 10 | "equation" -> "name" 11 | "equation" -> "function_call_args" 12 | "equation" -> "comment" 13 | "statement" -> "component_reference" 14 | "statement" -> "expression" 15 | "statement" -> "function_call_args" 16 | "statement" -> "output_expression_list" 17 | "statement" -> "if_statement" 18 | "statement" -> "for_statement" 19 | "statement" -> "while_statement" 20 | "statement" -> "when_statement" 21 | "statement" -> "comment" 22 | "if_equation" -> "expression" 23 | "if_equation" -> "equation" 24 | "if_statement" -> "expression" 25 | "if_statement" -> "statement" 26 | "for_equation" -> "for_indices" 27 | "for_equation" -> "equation" 28 | "for_statement" -> "for_indices" 29 | "for_statement" -> "statement" 30 | "for_indices" -> "for_index" 31 | "for_index" -> "expression" 32 | "while_statement" -> "expression" 33 | "while_statement" -> "statement" 34 | "when_equation" -> "expression" 35 | "when_equation" -> "equation" 36 | "when_statement" -> "expression" 37 | "when_statement" -> "statement" 38 | "connect_clause" -> "component_reference" 39 | } 40 | -------------------------------------------------------------------------------- /docs/syntax_equation.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | equations 11 | 12 | 13 | equation_section 14 | 15 | equation_section 16 | 17 | 18 | equation 19 | 20 | equation 21 | 22 | 23 | equation_section->equation 24 | 25 | 26 | 27 | 28 | simple_expression 29 | 30 | simple_expression 31 | 32 | 33 | equation->simple_expression 34 | 35 | 36 | 37 | 38 | expression 39 | 40 | expression 41 | 42 | 43 | equation->expression 44 | 45 | 46 | 47 | 48 | if_equation 49 | 50 | if_equation 51 | 52 | 53 | equation->if_equation 54 | 55 | 56 | 57 | 58 | for_equation 59 | 60 | for_equation 61 | 62 | 63 | equation->for_equation 64 | 65 | 66 | 67 | 68 | connect_clause 69 | 70 | connect_clause 71 | 72 | 73 | equation->connect_clause 74 | 75 | 76 | 77 | 78 | when_equation 79 | 80 | when_equation 81 | 82 | 83 | equation->when_equation 84 | 85 | 86 | 87 | 88 | name 89 | 90 | name 91 | 92 | 93 | equation->name 94 | 95 | 96 | 97 | 98 | function_call_args 99 | 100 | function_call_args 101 | 102 | 103 | equation->function_call_args 104 | 105 | 106 | 107 | 108 | comment 109 | 110 | comment 111 | 112 | 113 | equation->comment 114 | 115 | 116 | 117 | 118 | algorithm_section 119 | 120 | algorithm_section 121 | 122 | 123 | statement 124 | 125 | statement 126 | 127 | 128 | algorithm_section->statement 129 | 130 | 131 | 132 | 133 | statement->expression 134 | 135 | 136 | 137 | 138 | statement->function_call_args 139 | 140 | 141 | 142 | 143 | statement->comment 144 | 145 | 146 | 147 | 148 | component_reference 149 | 150 | component_reference 151 | 152 | 153 | statement->component_reference 154 | 155 | 156 | 157 | 158 | output_expression_list 159 | 160 | output_expression_list 161 | 162 | 163 | statement->output_expression_list 164 | 165 | 166 | 167 | 168 | if_statement 169 | 170 | if_statement 171 | 172 | 173 | statement->if_statement 174 | 175 | 176 | 177 | 178 | for_statement 179 | 180 | for_statement 181 | 182 | 183 | statement->for_statement 184 | 185 | 186 | 187 | 188 | while_statement 189 | 190 | while_statement 191 | 192 | 193 | statement->while_statement 194 | 195 | 196 | 197 | 198 | when_statement 199 | 200 | when_statement 201 | 202 | 203 | statement->when_statement 204 | 205 | 206 | 207 | 208 | if_equation->equation 209 | 210 | 211 | 212 | 213 | if_equation->expression 214 | 215 | 216 | 217 | 218 | for_equation->equation 219 | 220 | 221 | 222 | 223 | for_indices 224 | 225 | for_indices 226 | 227 | 228 | for_equation->for_indices 229 | 230 | 231 | 232 | 233 | connect_clause->component_reference 234 | 235 | 236 | 237 | 238 | when_equation->equation 239 | 240 | 241 | 242 | 243 | when_equation->expression 244 | 245 | 246 | 247 | 248 | if_statement->statement 249 | 250 | 251 | 252 | 253 | if_statement->expression 254 | 255 | 256 | 257 | 258 | for_statement->statement 259 | 260 | 261 | 262 | 263 | for_statement->for_indices 264 | 265 | 266 | 267 | 268 | while_statement->statement 269 | 270 | 271 | 272 | 273 | while_statement->expression 274 | 275 | 276 | 277 | 278 | when_statement->statement 279 | 280 | 281 | 282 | 283 | when_statement->expression 284 | 285 | 286 | 287 | 288 | for_index 289 | 290 | for_index 291 | 292 | 293 | for_indices->for_index 294 | 295 | 296 | 297 | 298 | for_index->expression 299 | 300 | 301 | 302 | 303 | 304 | -------------------------------------------------------------------------------- /docs/syntax_expression.dot: -------------------------------------------------------------------------------- 1 | digraph expressions { 2 | "expression" -> "simple_expression" 3 | "expression" -> "expression" 4 | "simple_expression" -> "logical_expression" 5 | "logical_expression" -> "logical_term" 6 | "logical_term" -> "logical_factor" 7 | "logical_factor" -> "relation" 8 | "relation" -> "arithmetic_expression" 9 | "relation" -> "rel_op" 10 | "arithmetic_expression" -> "add_op" 11 | "arithmetic_expression" -> "term" 12 | "term" -> "factor" 13 | "term" -> "mul_op" 14 | "factor" -> "primary" 15 | "primary" -> "name" 16 | "primary" -> "function_call_args" 17 | "primary" -> "component_reference" 18 | "primary" -> "output_expression_list" 19 | "primary" -> "expression_list" 20 | "primary" -> "function_arguments" 21 | "component_reference" -> "array_subscripts" 22 | "function_call_args" -> "function_arguments" 23 | "function_arguments" -> "function_argument" 24 | "function_arguments" -> "for_indices" 25 | "function_arguments" -> "named_arguments" 26 | "named_arguments" -> "named_argument" 27 | "named_argument" -> "function_argument" 28 | "function_argument" -> "name" 29 | "function_argument" -> "named_arguments" 30 | "function_argument" -> "expression" 31 | "output_expression_list" -> "expression" 32 | "expression_list" -> "expression" 33 | "array_subscripts" -> "subscript" 34 | "subscript" -> "expression" 35 | "comment" -> "string_comment" 36 | "comment" -> "annotation" 37 | "annotation" -> "class_modification" 38 | } 39 | -------------------------------------------------------------------------------- /docs/syntax_expression.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | expressions 11 | 12 | 13 | expression 14 | 15 | expression 16 | 17 | 18 | expression->expression 19 | 20 | 21 | 22 | 23 | simple_expression 24 | 25 | simple_expression 26 | 27 | 28 | expression->simple_expression 29 | 30 | 31 | 32 | 33 | logical_expression 34 | 35 | logical_expression 36 | 37 | 38 | simple_expression->logical_expression 39 | 40 | 41 | 42 | 43 | logical_term 44 | 45 | logical_term 46 | 47 | 48 | logical_expression->logical_term 49 | 50 | 51 | 52 | 53 | logical_factor 54 | 55 | logical_factor 56 | 57 | 58 | logical_term->logical_factor 59 | 60 | 61 | 62 | 63 | relation 64 | 65 | relation 66 | 67 | 68 | logical_factor->relation 69 | 70 | 71 | 72 | 73 | arithmetic_expression 74 | 75 | arithmetic_expression 76 | 77 | 78 | relation->arithmetic_expression 79 | 80 | 81 | 82 | 83 | rel_op 84 | 85 | rel_op 86 | 87 | 88 | relation->rel_op 89 | 90 | 91 | 92 | 93 | add_op 94 | 95 | add_op 96 | 97 | 98 | arithmetic_expression->add_op 99 | 100 | 101 | 102 | 103 | term 104 | 105 | term 106 | 107 | 108 | arithmetic_expression->term 109 | 110 | 111 | 112 | 113 | factor 114 | 115 | factor 116 | 117 | 118 | term->factor 119 | 120 | 121 | 122 | 123 | mul_op 124 | 125 | mul_op 126 | 127 | 128 | term->mul_op 129 | 130 | 131 | 132 | 133 | primary 134 | 135 | primary 136 | 137 | 138 | factor->primary 139 | 140 | 141 | 142 | 143 | name 144 | 145 | name 146 | 147 | 148 | primary->name 149 | 150 | 151 | 152 | 153 | function_call_args 154 | 155 | function_call_args 156 | 157 | 158 | primary->function_call_args 159 | 160 | 161 | 162 | 163 | component_reference 164 | 165 | component_reference 166 | 167 | 168 | primary->component_reference 169 | 170 | 171 | 172 | 173 | output_expression_list 174 | 175 | output_expression_list 176 | 177 | 178 | primary->output_expression_list 179 | 180 | 181 | 182 | 183 | expression_list 184 | 185 | expression_list 186 | 187 | 188 | primary->expression_list 189 | 190 | 191 | 192 | 193 | function_arguments 194 | 195 | function_arguments 196 | 197 | 198 | primary->function_arguments 199 | 200 | 201 | 202 | 203 | function_call_args->function_arguments 204 | 205 | 206 | 207 | 208 | array_subscripts 209 | 210 | array_subscripts 211 | 212 | 213 | component_reference->array_subscripts 214 | 215 | 216 | 217 | 218 | output_expression_list->expression 219 | 220 | 221 | 222 | 223 | expression_list->expression 224 | 225 | 226 | 227 | 228 | function_argument 229 | 230 | function_argument 231 | 232 | 233 | function_arguments->function_argument 234 | 235 | 236 | 237 | 238 | for_indices 239 | 240 | for_indices 241 | 242 | 243 | function_arguments->for_indices 244 | 245 | 246 | 247 | 248 | named_arguments 249 | 250 | named_arguments 251 | 252 | 253 | function_arguments->named_arguments 254 | 255 | 256 | 257 | 258 | subscript 259 | 260 | subscript 261 | 262 | 263 | array_subscripts->subscript 264 | 265 | 266 | 267 | 268 | function_argument->expression 269 | 270 | 271 | 272 | 273 | function_argument->name 274 | 275 | 276 | 277 | 278 | function_argument->named_arguments 279 | 280 | 281 | 282 | 283 | named_argument 284 | 285 | named_argument 286 | 287 | 288 | named_arguments->named_argument 289 | 290 | 291 | 292 | 293 | named_argument->function_argument 294 | 295 | 296 | 297 | 298 | subscript->expression 299 | 300 | 301 | 302 | 303 | comment 304 | 305 | comment 306 | 307 | 308 | string_comment 309 | 310 | string_comment 311 | 312 | 313 | comment->string_comment 314 | 315 | 316 | 317 | 318 | annotation 319 | 320 | annotation 321 | 322 | 323 | comment->annotation 324 | 325 | 326 | 327 | 328 | class_modification 329 | 330 | class_modification 331 | 332 | 333 | annotation->class_modification 334 | 335 | 336 | 337 | 338 | 339 | -------------------------------------------------------------------------------- /docs/syntax_extends.dot: -------------------------------------------------------------------------------- 1 | digraph extends { 2 | "extends_clause" -> "name" 3 | "extends_clause" -> "class_modification" 4 | "extends_clause" -> "annotation" 5 | "constraining_clause" -> "name" 6 | "constraining_clause" -> "class_modification" 7 | } 8 | -------------------------------------------------------------------------------- /docs/syntax_extends.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | extends 11 | 12 | 13 | extends_clause 14 | 15 | extends_clause 16 | 17 | 18 | name 19 | 20 | name 21 | 22 | 23 | extends_clause->name 24 | 25 | 26 | 27 | 28 | class_modification 29 | 30 | class_modification 31 | 32 | 33 | extends_clause->class_modification 34 | 35 | 36 | 37 | 38 | annotation 39 | 40 | annotation 41 | 42 | 43 | extends_clause->annotation 44 | 45 | 46 | 47 | 48 | constraining_clause 49 | 50 | constraining_clause 51 | 52 | 53 | constraining_clause->name 54 | 55 | 56 | 57 | 58 | constraining_clause->class_modification 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/syntax_full.dot: -------------------------------------------------------------------------------- 1 | digraph full_definition { 2 | "class_definition" -> "class_prefixes" 3 | "class_definition" -> "class_specifier" 4 | "class_specifier" -> "string_comment" 5 | "class_specifier" -> "composition" 6 | "class_specifier" -> "base_prefix" 7 | "class_specifier" -> "name" 8 | "class_specifier" -> "array_subscripts" 9 | "class_specifier" -> "class_modification" 10 | "class_specifier" -> "comment" 11 | "class_specifier" -> "enumeration" 12 | "class_specifier" -> "enum_list" 13 | "class_specifier" -> "class_modification" 14 | "class_specifier" -> "string_comment" 15 | "class_specifier" -> "composition" 16 | "base_prefix" -> "type_prefix" 17 | "enum_list" -> "enumeration_literal" 18 | "enumeration_literal" -> "comment" 19 | "composition" -> "element_list" 20 | "composition" -> "equation_section" 21 | "composition" -> "algorithm_section" 22 | "composition" -> "language_specification" 23 | "composition" -> "external_function_call" 24 | "composition" -> "annotation" 25 | "external_function_call" -> "component_reference" 26 | "external_function_call" -> "expression_list" 27 | "element_list" -> "element" 28 | "element" -> "import_clause" 29 | "extends_clause" -> "class_definition" 30 | "extends_clause" -> "component_clause" 31 | "extends_clause" -> "constraining_clause" 32 | "extends_clause" -> "comment" 33 | "import_clause" -> "name" 34 | "import_clause" -> "import_list" 35 | "import_clause" -> "comment" 36 | "import_list" -> "import_list" 37 | "component_clause" -> "type_prefix" 38 | "component_clause" -> "type_specifier" 39 | "component_clause" -> "array_subscripts" 40 | "component_clause" -> "component_list" 41 | "type_specifier" -> "name" 42 | "component_list" -> "component_declaration" 43 | "component_declaration" -> "declaration" 44 | "component_declaration" -> "comment" 45 | "component_declaration" -> "condition_attribute" 46 | "condition_attribute" -> "expression" 47 | "declaration" -> "array_subscripts" 48 | "declaration" -> "modification" 49 | "equation_section" -> "equation" 50 | "algorithm_section" -> "statement" 51 | "equation" -> "simple_expression" 52 | "equation" -> "expression" 53 | "equation" -> "if_equation" 54 | "equation" -> "for_equation" 55 | "equation" -> "connect_clause" 56 | "equation" -> "when_equation" 57 | "equation" -> "name" 58 | "equation" -> "function_call_args" 59 | "equation" -> "comment" 60 | "statement" -> "component_reference" 61 | "statement" -> "expression" 62 | "statement" -> "function_call_args" 63 | "statement" -> "output_expression_list" 64 | "statement" -> "if_statement" 65 | "statement" -> "for_statement" 66 | "statement" -> "while_statement" 67 | "statement" -> "when_statement" 68 | "statement" -> "comment" 69 | "if_equation" -> "expression" 70 | "if_equation" -> "equation" 71 | "if_statement" -> "expression" 72 | "if_statement" -> "statement" 73 | "for_equation" -> "for_indices" 74 | "for_equation" -> "equation" 75 | "for_statement" -> "for_indices" 76 | "for_statement" -> "statement" 77 | "for_indices" -> "for_index" 78 | "for_index" -> "expression" 79 | "while_statement" -> "expression" 80 | "while_statement" -> "statement" 81 | "when_equation" -> "expression" 82 | "when_equation" -> "equation" 83 | "when_statement" -> "expression" 84 | "when_statement" -> "statement" 85 | "connect_clause" -> "component_reference" 86 | "expression" -> "simple_expression" 87 | "expression" -> "expression" 88 | "simple_expression" -> "logical_expression" 89 | "logical_expression" -> "logical_term" 90 | "logical_term" -> "logical_factor" 91 | "logical_factor" -> "relation" 92 | "relation" -> "arithmetic_expression" 93 | "relation" -> "rel_op" 94 | "arithmetic_expression" -> "add_op" 95 | "arithmetic_expression" -> "term" 96 | "term" -> "factor" 97 | "term" -> "mul_op" 98 | "factor" -> "primary" 99 | "primary" -> "name" 100 | "primary" -> "function_call_args" 101 | "primary" -> "component_reference" 102 | "primary" -> "output_expression_list" 103 | "primary" -> "expression_list" 104 | "primary" -> "function_arguments" 105 | "component_reference" -> "array_subscripts" 106 | "function_call_args" -> "function_arguments" 107 | "function_arguments" -> "function_argument" 108 | "function_arguments" -> "for_indices" 109 | "function_arguments" -> "named_arguments" 110 | "named_arguments" -> "named_argument" 111 | "named_argument" -> "function_argument" 112 | "function_argument" -> "name" 113 | "function_argument" -> "named_arguments" 114 | "function_argument" -> "expression" 115 | "output_expression_list" -> "expression" 116 | "expression_list" -> "expression" 117 | "array_subscripts" -> "subscript" 118 | "subscript" -> "expression" 119 | "comment" -> "string_comment" 120 | "comment" -> "annotation" 121 | "annotation" -> "class_modification" 122 | "extends_clause" -> "name" 123 | "extends_clause" -> "class_modification" 124 | "extends_clause" -> "annotation" 125 | "constraining_clause" -> "name" 126 | "constraining_clause" -> "class_modification" 127 | "modification" -> "class_modification" 128 | "modification" -> "expression" 129 | "class_modification" -> "argument_list" 130 | "argument_list" -> "argument" 131 | "argument" -> "element_modification_or_replaceable" 132 | "argument" -> "element_redeclaration" 133 | "element_modification_or_replaceable" -> "element_modification" 134 | "element_modification_or_replaceable" -> "element_replaceable" 135 | "element_modification" -> "modification" 136 | "element_modification" -> "string_comment" 137 | "element_redeclaration" -> "short_class_definition" 138 | "element_redeclaration" -> "component_clause1" 139 | "element_redeclaration" -> "element_replaceable" 140 | "element_replaceable" -> "short_class_definition" 141 | "element_replaceable" -> "component_clause1" 142 | "element_replaceable" -> "constraining_clause" 143 | "component_clause1" -> "type_prefix" 144 | "component_clause1" -> "type_specifier" 145 | "component_clause1" -> "component_declaration1" 146 | "component_declaration1" -> "declaration" 147 | "component_declaration1" -> "comment" 148 | "short_class_definition" -> "class_prefixes" 149 | "short_class_definition" -> "base_prefix" 150 | "short_class_definition" -> "array_subscripts" 151 | "short_class_definition" -> "class_modification" 152 | "short_class_definition" -> "comment" 153 | "short_class_definition" -> "enum_list" 154 | "stored_definition" -> "name" 155 | "stored_definition" -> "class_definition" 156 | } 157 | -------------------------------------------------------------------------------- /docs/syntax_modification.dot: -------------------------------------------------------------------------------- 1 | digraph modification { 2 | "modification" -> "class_modification" 3 | "modification" -> "expression" 4 | "class_modification" -> "argument_list" 5 | "argument_list" -> "argument" 6 | "argument" -> "element_modification_or_replaceable" 7 | "argument" -> "element_redeclaration" 8 | "element_modification_or_replaceable" -> "element_modification" 9 | "element_modification_or_replaceable" -> "element_replaceable" 10 | "element_modification" -> "modification" 11 | "element_modification" -> "string_comment" 12 | "element_redeclaration" -> "short_class_definition" 13 | "element_redeclaration" -> "component_clause1" 14 | "element_redeclaration" -> "element_replaceable" 15 | "element_replaceable" -> "short_class_definition" 16 | "element_replaceable" -> "component_clause1" 17 | "element_replaceable" -> "constraining_clause" 18 | "component_clause1" -> "type_prefix" 19 | "component_clause1" -> "type_specifier" 20 | "component_clause1" -> "component_declaration1" 21 | "component_declaration1" -> "declaration" 22 | "component_declaration1" -> "comment" 23 | "short_class_definition" -> "class_prefixes" 24 | "short_class_definition" -> "base_prefix" 25 | "short_class_definition" -> "array_subscripts" 26 | "short_class_definition" -> "class_modification" 27 | "short_class_definition" -> "comment" 28 | "short_class_definition" -> "enum_list" 29 | } 30 | -------------------------------------------------------------------------------- /docs/syntax_modification.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | modification 11 | 12 | 13 | modification 14 | 15 | modification 16 | 17 | 18 | class_modification 19 | 20 | class_modification 21 | 22 | 23 | modification->class_modification 24 | 25 | 26 | 27 | 28 | expression 29 | 30 | expression 31 | 32 | 33 | modification->expression 34 | 35 | 36 | 37 | 38 | argument_list 39 | 40 | argument_list 41 | 42 | 43 | class_modification->argument_list 44 | 45 | 46 | 47 | 48 | argument 49 | 50 | argument 51 | 52 | 53 | argument_list->argument 54 | 55 | 56 | 57 | 58 | element_modification_or_replaceable 59 | 60 | element_modification_or_replaceable 61 | 62 | 63 | argument->element_modification_or_replaceable 64 | 65 | 66 | 67 | 68 | element_redeclaration 69 | 70 | element_redeclaration 71 | 72 | 73 | argument->element_redeclaration 74 | 75 | 76 | 77 | 78 | element_modification 79 | 80 | element_modification 81 | 82 | 83 | element_modification_or_replaceable->element_modification 84 | 85 | 86 | 87 | 88 | element_replaceable 89 | 90 | element_replaceable 91 | 92 | 93 | element_modification_or_replaceable->element_replaceable 94 | 95 | 96 | 97 | 98 | element_redeclaration->element_replaceable 99 | 100 | 101 | 102 | 103 | short_class_definition 104 | 105 | short_class_definition 106 | 107 | 108 | element_redeclaration->short_class_definition 109 | 110 | 111 | 112 | 113 | component_clause1 114 | 115 | component_clause1 116 | 117 | 118 | element_redeclaration->component_clause1 119 | 120 | 121 | 122 | 123 | element_modification->modification 124 | 125 | 126 | 127 | 128 | string_comment 129 | 130 | string_comment 131 | 132 | 133 | element_modification->string_comment 134 | 135 | 136 | 137 | 138 | element_replaceable->short_class_definition 139 | 140 | 141 | 142 | 143 | element_replaceable->component_clause1 144 | 145 | 146 | 147 | 148 | constraining_clause 149 | 150 | constraining_clause 151 | 152 | 153 | element_replaceable->constraining_clause 154 | 155 | 156 | 157 | 158 | short_class_definition->class_modification 159 | 160 | 161 | 162 | 163 | comment 164 | 165 | comment 166 | 167 | 168 | short_class_definition->comment 169 | 170 | 171 | 172 | 173 | class_prefixes 174 | 175 | class_prefixes 176 | 177 | 178 | short_class_definition->class_prefixes 179 | 180 | 181 | 182 | 183 | base_prefix 184 | 185 | base_prefix 186 | 187 | 188 | short_class_definition->base_prefix 189 | 190 | 191 | 192 | 193 | array_subscripts 194 | 195 | array_subscripts 196 | 197 | 198 | short_class_definition->array_subscripts 199 | 200 | 201 | 202 | 203 | enum_list 204 | 205 | enum_list 206 | 207 | 208 | short_class_definition->enum_list 209 | 210 | 211 | 212 | 213 | type_prefix 214 | 215 | type_prefix 216 | 217 | 218 | component_clause1->type_prefix 219 | 220 | 221 | 222 | 223 | type_specifier 224 | 225 | type_specifier 226 | 227 | 228 | component_clause1->type_specifier 229 | 230 | 231 | 232 | 233 | component_declaration1 234 | 235 | component_declaration1 236 | 237 | 238 | component_clause1->component_declaration1 239 | 240 | 241 | 242 | 243 | declaration 244 | 245 | declaration 246 | 247 | 248 | component_declaration1->declaration 249 | 250 | 251 | 252 | 253 | component_declaration1->comment 254 | 255 | 256 | 257 | 258 | 259 | -------------------------------------------------------------------------------- /docs/syntax_stored_definition.dot: -------------------------------------------------------------------------------- 1 | digraph stored_definition { 2 | "stored_definition" -> "name" 3 | "stored_definition" -> "class_definition" 4 | } 5 | -------------------------------------------------------------------------------- /docs/syntax_stored_definition.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | stored_definition 11 | 12 | 13 | stored_definition 14 | 15 | stored_definition 16 | 17 | 18 | name 19 | 20 | name 21 | 22 | 23 | stored_definition->name 24 | 25 | 26 | 27 | 28 | class_definition 29 | 30 | class_definition 31 | 32 | 33 | stored_definition->class_definition 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | To use modparc in a project: 6 | 7 | .. code-block:: python 8 | :linenos: 9 | :emphasize-lines: 4 10 | 11 | import modparc 12 | with open("your_modelica_file.mo", 'r') as f: 13 | modelica_source_code = f.read() 14 | model_definition = modparc.parse(modelica_source_code) 15 | 16 | To list all the equations in the `model_definition` instance: 17 | 18 | .. code-block:: python 19 | :emphasize-lines: 1,3 20 | :lineno-start: 5 21 | 22 | all_equations = model_definition.search('Equation') 23 | for equation in all_equations: 24 | print(equation.code()) # The code of the equation as string 25 | 26 | One could also parse a certain syntax element in Modelica: 27 | 28 | .. code-block:: python 29 | :linenos: 30 | :emphasize-lines: 11-13 31 | 32 | import modparc 33 | from modparc.syntax import tokenize 34 | source_code = """ 35 | if init==InitializationOptions.FixedPopulation then 36 | population = initial_population; 37 | elseif init==InitializationOptions.SteadyState then 38 | der(population) = 0; 39 | else 40 | end if 41 | """ 42 | tokens_list = tokenize(source_code) 43 | if_equation_element = modparc.syntax.equations.if_equation(tokens_list) 44 | sub_equations = if_equation_element.search('Equation') 45 | for equation in sub_equations: 46 | print(equation.code()) # The code of the equation as string 47 | 48 | 49 | -------------------------------------------------------------------------------- /modparc/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | modparc 4 | ---------------------------------- 5 | 6 | A Modelica parser using parser combinator. 7 | """ 8 | import sys 9 | 10 | import modparc.specification 11 | import modparc.syntax 12 | import modparc.syntax.class_definition 13 | import modparc.syntax.component_clause 14 | import modparc.syntax.equations 15 | import modparc.syntax.expressions 16 | import modparc.syntax.extends 17 | import modparc.syntax.modification 18 | import modparc.syntax.stored_definition # noqa: F401 19 | from modparc.parse import (parse, parse_file) # noqa: F401 20 | 21 | 22 | try: 23 | import resource 24 | resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1)) 25 | except: 26 | print("Warning: stack size in Windows might not be enough for arrays") 27 | 28 | sys.setrecursionlimit(10**6) 29 | 30 | __author__ = """谢东平 Dongping XIE""" 31 | __email__ = 'dongping.xie.tud@gmail.com' 32 | __version__ = '0.2.1' 33 | -------------------------------------------------------------------------------- /modparc/parse.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | parse 5 | ---------------------------------- 6 | 7 | High-level helper functions for the package 8 | """ 9 | 10 | from modparc.syntax.stored_definition import stored_definition 11 | from modparc.syntax import tokenize 12 | 13 | 14 | def parse(source_code): 15 | """ 16 | Parse Modelica source code and return the parsed structure 17 | 18 | :param source_code: code lines to be parsed 19 | :return: an instance of StoredDefinition 20 | """ 21 | tokens = tokenize(source_code) 22 | return stored_definition.parse(tokens) 23 | 24 | def parse_file(source_file): 25 | """ 26 | Parse Modelica source file and return the parsed structure 27 | 28 | :param source_file: Modelica source code file 29 | :return: an instance of StoredDefinition 30 | """ 31 | with open(source_file, 'r') as file_object: 32 | mo_file_content = file_object.read() 33 | return parse(mo_file_content) 34 | -------------------------------------------------------------------------------- /modparc/specification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | specification 4 | ---------------------------------- 5 | 6 | Constants used in the library according to the specification 7 | """ 8 | 9 | KEYWORDS = ['algorithm', 'and', 'annotation', 'assert', 'block', 10 | 'break', 'class', 'connect', 'connector', 'constant', 11 | 'constrainedby', 'der', 'discrete', 'each', 'else', 12 | 'elseif', 'elsewhen', 'encapsulated', 'end', 13 | 'enumeration', 'equation', 'expandable', 'extends', 14 | 'external', 'false', 'final', 'flow', 'for', 'function', 15 | 'if', 'import', 'impure', 'in', 'initial', 'inner', 16 | 'input', 'loop', 'model', 'not', 'operator', 'or', 17 | 'outer', 'output', 'package', 'parameter', 'partial', 18 | 'protected', 'public', 'pure', 'record', 'redeclare', 19 | 'replaceable', 'return', 'stream', 'then', 'true', 20 | 'type', 'when', 'while', 'within', ] 21 | -------------------------------------------------------------------------------- /modparc/syntax/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | syntax 4 | ---------------------------------- 5 | 6 | The main utilities module for the parser implementation, with tokenizer 7 | and parser creation functions. 8 | """ 9 | 10 | from re import MULTILINE 11 | 12 | from funcparserlib.lexer import Token 13 | from funcparserlib.parser import some, a, maybe 14 | import funcparserlib.lexer 15 | 16 | from modparc.specification import KEYWORDS 17 | 18 | 19 | def token_type(tok_type): 20 | """ 21 | Get a parser matching a certain type of tokens 22 | 23 | :param tok_type: predefined token type to be matched 24 | :return: a parser that matches token of type `tok_type` 25 | """ 26 | return some(lambda tok: tok.type == tok_type) 27 | 28 | 29 | def language_element(key, tok_type, combinator=a): 30 | """ 31 | Parser to match language element by using a certain combinator 32 | 33 | :param key: exact key of the token, e.g.: `begin`, `model`, `)` 34 | :param tok_type: predefined token type to be matched 35 | :param combinator: use the combinator to create a parser 36 | :return: a parser that matches elements using the above condition 37 | """ 38 | if combinator == a: 39 | return combinator(Token(tok_type, key)) 40 | elif combinator == some: 41 | return combinator(lambda tok: tok == Token(tok_type, key)) 42 | elif combinator == maybe: 43 | return combinator(a(Token(tok_type, key))) 44 | else: 45 | raise Exception("Parser creation error") 46 | 47 | 48 | def keyword(key, combinator=a): 49 | """ 50 | Parser to match a keyword token with a key and a combinator 51 | 52 | :param key: exact key of the keyword, e.g.: `begin`, `assert` etc. 53 | :param combinator: use the combinator to create a parser 54 | :return: a parser that matches a keyword 55 | """ 56 | return language_element(key, tok_type='keyword', combinator=combinator) 57 | 58 | 59 | def op(key, combinator=a): 60 | """ 61 | Parser to match a operator token with a key and a combinator 62 | 63 | :param key: exact key of the operator, e.g.: `+`, `.*` etc. 64 | :param combinator: use the combinator to create a parser 65 | :return: a parser that matches an operator 66 | """ 67 | return language_element(key, tok_type='op', combinator=combinator) 68 | 69 | 70 | def tokenize(source_code): 71 | """ 72 | Tokenizer according to Modelica Specification §2 and Appendix B.1 73 | 74 | :param source_code: source code to be tokenized 75 | :return: list of tokens created 76 | """ 77 | token_specs = [ 78 | ('string', (r'"([^\\\"]|\\.|[\r\n])*?"', MULTILINE)), 79 | ('comment', (r'/\*(.|[\r\n])*?\*/', MULTILINE)), 80 | ('ident', (r"'" + r'([a-zA-Z_0-9' + 81 | r'!#%&()*+,\-\./:;<>=?@\[\]\^{}|~ ' + 82 | r'\"\?\\\a\b\f\n\r\t\v]|[^\x00-\x7F])*' + r"'",)), 83 | ('comment', (r'//.*',)), 84 | ('newline', (r'[\r\n]+',)), 85 | ('whitespace', (r'[ \t\r\n]+',)), 86 | ('keyword', (r'(' + r'\b|'.join(KEYWORDS) + r'\b)',)), 87 | ('number', (r'\d+(\.(\d+)?)?([eE][\+-]?\d+)?',)), 88 | ('ident', (r'[a-zA-Z_][a-zA-Z_0-9]*',)), 89 | ('op', (r'(<>|<=|>=|==)',)), 90 | ('op', (r'[<>]',)), 91 | ('op', (r'(\.\+|\.-)',)), 92 | ('op', (r'[+\-]',)), 93 | ('op', (r'(\.\*|\./)',)), 94 | ('op', (r':=',)), 95 | ('op', (r'\.\^',)), 96 | ('op', (r'[\[\]\.(){}\^+\-*/=\,;\:]',)), 97 | ] 98 | inner_tokenize = funcparserlib.lexer.make_tokenizer(token_specs) 99 | useless = ['comment', 'newline', 'whitespace'] 100 | 101 | return [tok for tok in inner_tokenize(source_code) 102 | if tok.type not in useless] 103 | -------------------------------------------------------------------------------- /modparc/syntax/class_definition.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # pylint: disable=no-name-in-module, missing-docstring 4 | """ 5 | class_definition 6 | ---------------------------------- 7 | 8 | Parser definition for funcparserlib. The parsers that need forward declaration 9 | are defined as function annotated by the `Parser` decorator. 10 | 11 | The definitions are specified in the Appendix B.2.2 of the Modelica 12 | Specification 3.3. 13 | """ 14 | 15 | 16 | from funcparserlib.parser import many, maybe, Parser 17 | 18 | from modparc.syntax import keyword, op, token_type 19 | from modparc.syntax.component_clause import type_prefix, component_clause 20 | from modparc.syntax.equations import equation_section, algorithm_section 21 | from modparc.syntax.expressions import (name, comment, annotation, 22 | string_comment, component_reference, 23 | array_subscript, expression_list) 24 | from modparc.syntax.extends import extends_clause, constraining_clause 25 | from modparc.syntax.modification import class_modification 26 | from modparc.syntax.syntax_elements import (LanguageSpecification, BasePrefix, 27 | ExternalFunctionCall, 28 | ClassDefinition, Element, 29 | ElementList, Composition, 30 | ClassSpecifier, ClassPrefixes, 31 | EnumerationLiteral, EnumList, 32 | ImportList, ImportClause) 33 | # pylint: enable=no-name-in-module 34 | 35 | language_specification = token_type('string') >> LanguageSpecification 36 | 37 | base_prefix = type_prefix >> BasePrefix 38 | 39 | external_function_call = (maybe(component_reference + op("=")) + 40 | token_type('ident') + op("(") + 41 | maybe(expression_list) + op(")") 42 | >> ExternalFunctionCall) 43 | 44 | 45 | @Parser 46 | def class_definition(tokens, state): 47 | parser = maybe(keyword("encapsulated")) + class_prefixes + class_specifier 48 | return (parser >> ClassDefinition).run(tokens, state) 49 | 50 | 51 | def km(key): 52 | return maybe(keyword(key)) 53 | 54 | 55 | @Parser 56 | def element(tokens, state): 57 | kw = keyword 58 | parser = (import_clause | 59 | extends_clause | 60 | km('redeclare') + km('final') + 61 | km('inner') + km('outer') + 62 | ((class_definition | component_clause) | 63 | kw('replaceable') + (class_definition | 64 | component_clause) 65 | + maybe(constraining_clause + comment))) 66 | return (parser >> Element).run(tokens, state) 67 | 68 | element_list = maybe(many(element + op(';'))) >> ElementList 69 | 70 | composition = (element_list + 71 | maybe(many(keyword("public") + element_list | 72 | keyword("protected") + element_list | 73 | equation_section | 74 | algorithm_section)) + 75 | maybe(keyword("external") + maybe(language_specification) + 76 | maybe(external_function_call) + maybe(annotation) + 77 | op(";")) + 78 | maybe(annotation + op(";")) >> Composition) 79 | 80 | 81 | @Parser 82 | def class_specifier(tokens, state): 83 | normal = (token_type('ident') + string_comment + composition 84 | + keyword('end') + token_type('ident')) 85 | derived = (token_type('ident') + op("=") + base_prefix + name + 86 | maybe(array_subscript) + maybe(class_modification) + comment) 87 | enum_def = (token_type('ident') + op("=") + keyword('enumeration') 88 | + op("(") + (maybe(enum_list) | op(":")) + op(")") + comment) 89 | derivative = (token_type('ident') + op("=") + keyword('der') 90 | + op("(") + name + op(",") + token_type('ident') 91 | + maybe(many(op(",") + token_type('ident'))) 92 | + op(")") + comment) 93 | extended = (keyword('extends') + token_type('ident') + 94 | maybe(class_modification) + string_comment + composition + 95 | keyword("end") + token_type('ident')) 96 | 97 | parser = (normal | derived | enum_def | derivative | extended) 98 | return (parser >> ClassSpecifier).run(tokens, state) 99 | 100 | 101 | @Parser 102 | def class_prefixes(tokens, state): 103 | kw = keyword 104 | function_prefix = (maybe(kw("pure") | kw("impure")) + km("operator") 105 | + kw("function")) 106 | parser = (km("partial") 107 | + ((kw("class") | kw("model") | 108 | km("operator") + kw("record") | 109 | kw("block") | 110 | (km("expandable") + kw("connector")) | 111 | kw("type") | kw("package") | 112 | function_prefix | kw("operator")))) 113 | 114 | return (parser >> ClassPrefixes).run(tokens, state) 115 | 116 | enumeration_literal = token_type("ident") + comment >> EnumerationLiteral 117 | 118 | enum_list = enumeration_literal + maybe(many(op(",") + 119 | enumeration_literal)) >> EnumList 120 | 121 | import_list = (token_type("ident") + maybe(many(op(",") + 122 | token_type("ident"))) 123 | >> ImportList) 124 | 125 | import_clause = (keyword('import') + 126 | (token_type("ident") + op('=') + name | 127 | name + maybe(op(".*") 128 | | op(".") + op("{") + import_list + op("}"))) 129 | + comment) >> ImportClause 130 | -------------------------------------------------------------------------------- /modparc/syntax/component_clause.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | component_clause 4 | ---------------------------------- 5 | 6 | Parser definition for funcparserlib. The parsers that need forward declaration 7 | are defined as function annotated by the `Parser` decorator. 8 | 9 | The definitions are specified in the Appendix B.2.4 of the Modelica 10 | Specification 3.3. 11 | """ 12 | 13 | from funcparserlib.parser import (many, maybe, Parser) 14 | 15 | # pylint: disable=no-name-in-module, missing-docstring 16 | from modparc.syntax import keyword, op, token_type 17 | from modparc.syntax.expressions import (name, comment, expression, 18 | array_subscript) 19 | from modparc.syntax.syntax_elements import (TypePrefix, TypeSpecifier, 20 | ConditionAttribute, Declaration, 21 | ComponentDeclaration, 22 | ComponentList, ComponentClause) 23 | 24 | # pylint: enable=no-name-in-module 25 | 26 | kw = keyword 27 | 28 | type_prefix = (maybe(kw("flow") | kw("stream")) + 29 | maybe(kw("discrete") | kw("parameter") | kw("constant")) + 30 | maybe(kw("input") | kw("output"))) >> TypePrefix 31 | 32 | type_specifier = name >> TypeSpecifier 33 | 34 | condition_attribute = keyword('if') + expression >> ConditionAttribute 35 | 36 | 37 | @Parser 38 | def declaration(tokens, state): 39 | from .modification import modification 40 | parser = (token_type('ident') + maybe(array_subscript) 41 | + maybe(modification)) >> Declaration 42 | return parser.run(tokens, state) 43 | 44 | component_declaration = (declaration + maybe(condition_attribute) + comment 45 | >> ComponentDeclaration) 46 | 47 | component_list = (component_declaration + maybe(many(op(",") + 48 | component_declaration)) 49 | >> ComponentList) 50 | 51 | component_clause = (type_prefix + type_specifier + maybe(array_subscript) 52 | + component_list) >> ComponentClause 53 | -------------------------------------------------------------------------------- /modparc/syntax/equations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | equations 4 | ---------------------------------- 5 | 6 | Parser definition for funcparserlib. The parsers that need forward declaration 7 | are defined as function annotated by the `Parser` decorator 8 | 9 | The definitions are specified in the Appendix B.2.6 of the Modelica 10 | Specification 3.3. 11 | 12 | Note that there's no definition for the assertion statement/calls in the 13 | specification, so the Assertion parser is separately defined. 14 | """ 15 | 16 | from funcparserlib.parser import many, maybe, Parser 17 | 18 | # pylint: disable=no-name-in-module, missing-docstring 19 | from modparc.syntax import keyword, op, token_type 20 | from modparc.syntax.expressions import (expression, simple_expression, name, 21 | comment, function_call_args, 22 | component_reference, 23 | output_expression_list) 24 | from modparc.syntax.syntax_elements import (ForIndex, ForIndices, 25 | ConnectClause, Equation, 26 | IfEquation, ForEquation, 27 | WhileEquation, WhenEquation, 28 | Statement, IfStatement, 29 | ForStatement, WhileStatement, 30 | WhenStatement, EquationSection, 31 | AlgorithmSection, Assertion) 32 | # pylint: enable=no-name-in-module 33 | 34 | for_index = (token_type('ident') + maybe(keyword('in') + expression) 35 | >> ForIndex) 36 | 37 | for_indices = for_index + maybe(many(op(',') + for_index)) >> ForIndices 38 | 39 | connect_clause = (keyword("connect") + op("(") + component_reference 40 | + op(",") + component_reference + op(")")) >> ConnectClause 41 | 42 | assertion = keyword("assert") + function_call_args >> Assertion 43 | 44 | 45 | @Parser 46 | def equation(tokens, state): 47 | parser = ((simple_expression + op("=") + expression 48 | | if_equation 49 | | for_equation 50 | | connect_clause 51 | | when_equation 52 | | assertion 53 | | name + function_call_args) 54 | + comment) >> Equation 55 | return parser.run(tokens, state) 56 | 57 | 58 | @Parser 59 | def if_equation(tokens, state): 60 | kw = keyword 61 | parser = (kw("if") + expression + kw("then") + 62 | maybe(many(equation + op(";"))) + 63 | maybe(many(kw("elseif") + expression + kw("then") + 64 | maybe(many(equation + op(";"))))) + 65 | maybe(kw("else") + 66 | maybe(many(equation + op(";")))) + 67 | kw("end") + kw("if")) >> IfEquation 68 | return parser.run(tokens, state) 69 | 70 | 71 | @Parser 72 | def for_equation(tokens, state): 73 | kw = keyword 74 | parser = (kw("for") + for_indices + kw("loop") + 75 | maybe(many(equation + op(";"))) + 76 | kw("end") + kw("for")) >> ForEquation 77 | return parser.run(tokens, state) 78 | 79 | 80 | @Parser 81 | def while_equation(tokens, state): 82 | kw = keyword 83 | parser = (kw("while") + expression + kw("loop") + 84 | maybe(many(equation + op(";"))) + 85 | kw("end") + kw("while")) >> WhileEquation 86 | return parser.run(tokens, state) 87 | 88 | 89 | @Parser 90 | def when_equation(tokens, state): 91 | kw = keyword 92 | parser = (kw("when") + expression + kw("then") + 93 | maybe(many(equation + op(";"))) + 94 | maybe(many(kw("elsewhen") + expression + kw("then") + 95 | maybe(many(equation + op(";"))))) + 96 | kw("end") + kw("when")) >> WhenEquation 97 | return parser.run(tokens, state) 98 | 99 | 100 | @Parser 101 | def statement(tokens, state): 102 | parser = ((component_reference + (op(":=") + expression 103 | | function_call_args) 104 | | (op('(') + output_expression_list + op(')') + op(':=') 105 | + component_reference + function_call_args) 106 | | keyword('break') 107 | | keyword('return') 108 | | assertion 109 | | if_statement 110 | | for_statement 111 | | while_statement 112 | | connect_clause 113 | | when_statement) 114 | + comment) >> Statement 115 | return parser.run(tokens, state) 116 | 117 | 118 | @Parser 119 | def if_statement(tokens, state): 120 | kw = keyword 121 | parser = (kw("if") + expression + kw("then") + 122 | maybe(many(statement + op(";"))) + 123 | maybe(many(kw("elseif") + expression + kw("then") + 124 | maybe(many(statement + op(";"))))) + 125 | maybe(kw("else") + 126 | maybe(many(statement + op(";")))) + 127 | kw("end") + kw("if")) >> IfStatement 128 | return parser.run(tokens, state) 129 | 130 | 131 | @Parser 132 | def for_statement(tokens, state): 133 | kw = keyword 134 | parser = (kw("for") + for_indices + kw("loop") + 135 | maybe(many(statement + op(";"))) + 136 | kw("end") + kw("for")) >> ForStatement 137 | return parser.run(tokens, state) 138 | 139 | 140 | @Parser 141 | def while_statement(tokens, state): 142 | kw = keyword 143 | parser = (kw("while") + expression + kw("loop") + 144 | maybe(many(statement + op(";"))) + 145 | kw("end") + kw("while")) >> WhileStatement 146 | return parser.run(tokens, state) 147 | 148 | 149 | @Parser 150 | def when_statement(tokens, state): 151 | kw = keyword 152 | parser = (kw("when") + expression + kw("then") + 153 | maybe(many(statement + op(";"))) + 154 | maybe(many(kw("elsewhen") + expression + kw("then") + 155 | maybe(many(statement + op(";"))))) + 156 | kw("end") + kw("when")) >> WhenStatement 157 | return parser.run(tokens, state) 158 | 159 | equation_section = (maybe(keyword("initial")) + keyword("equation") + 160 | maybe(many(equation + op(';')))) >> EquationSection 161 | 162 | algorithm_section = (maybe(keyword("initial")) + keyword("algorithm") + 163 | maybe(many(statement + op(';')))) >> AlgorithmSection 164 | -------------------------------------------------------------------------------- /modparc/syntax/expressions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | expressions 5 | ---------------------------------- 6 | 7 | Parser definition for funcparserlib. The parsers that need forward declaration 8 | are defined as function annotated by the `Parser` decorator 9 | 10 | The definitions are specified in the Appendix B.2.7 of the Modelica 11 | Specification 3.3. 12 | """ 13 | 14 | from funcparserlib.parser import many, maybe, Parser 15 | 16 | # pylint: disable=no-name-in-module, missing-docstring 17 | from modparc.syntax import keyword, op, token_type 18 | from modparc.syntax.syntax_elements import (Expression, SimpleExpression, 19 | LogicalExpression, LogicalTerm, 20 | LogicalFactor, Relation, 21 | ArithmeticExpression, Term, Factor, 22 | Primary, RelOp, MulOp, AddOp, Name, 23 | NamedArgument, NamedArguments, 24 | FunctionArgument, 25 | FunctionArguments, 26 | FunctionCallArgs, ExpressionList, 27 | OutputExpressionList, Subscript, 28 | ArraySubscript, ComponentReference, 29 | StringComment, Annotation, Comment) 30 | # pylint: enable=no-name-in-module 31 | 32 | name = (maybe(op(".")) + (token_type("ident") | keyword("assert")) + 33 | maybe(many(op(".") + (token_type("ident") | keyword("assert")))) 34 | >> Name) 35 | 36 | rel_op = op("<") | op("<=") | op(">") | op(">=") | op("==") | op("<>") >> RelOp 37 | 38 | add_op = op("+") | op("-") | op(".+") | op(".-") >> AddOp 39 | 40 | mul_op = op("*") | op("/") | op(".*") | op("./") >> MulOp 41 | 42 | 43 | @Parser 44 | def primary(tokens, state): 45 | kw = keyword 46 | parser = (token_type("number") 47 | | token_type("string") 48 | | kw("false") 49 | | kw("true") 50 | | (name | kw("der") | kw("initial")) + function_call_args 51 | | component_reference 52 | | op("(") + output_expression_list + op(")") 53 | | (op("[") + expression_list 54 | + maybe(many(op(";") + expression_list)) + op("]")) 55 | | op("{") + function_arguments + op("}") 56 | | kw("end")) 57 | 58 | return (parser >> Primary).run(tokens, state) 59 | 60 | factor = primary + maybe((op("^") | op(".^")) + primary) >> Factor 61 | 62 | term = factor + maybe(many(mul_op + factor)) >> Term 63 | 64 | arithmetic_expression = (maybe(add_op) + term + maybe(many(add_op + term)) 65 | >> ArithmeticExpression) 66 | 67 | relation = (arithmetic_expression + maybe(rel_op + arithmetic_expression) 68 | >> Relation) 69 | 70 | logical_factor = maybe(keyword("not")) + relation >> LogicalFactor 71 | 72 | logical_term = (logical_factor + maybe(many(keyword("and") + logical_factor)) 73 | >> LogicalTerm) 74 | 75 | logical_expression = (logical_term + maybe(many(keyword("or") + logical_term)) 76 | >> LogicalExpression) 77 | 78 | simple_expression = (logical_expression + maybe(op(":") + logical_expression 79 | + maybe(op(":") + 80 | logical_expression)) 81 | >> SimpleExpression) 82 | 83 | 84 | @Parser 85 | def expression(tokens, state): 86 | kw = keyword 87 | parser = (simple_expression 88 | | kw("if") + expression + kw("then") + expression 89 | + maybe(many(kw("elseif") + expression 90 | + kw("then") + expression)) 91 | + kw("else") + expression) >> Expression 92 | return parser.run(tokens, state) 93 | 94 | 95 | @Parser 96 | def named_argument(tokens, state): 97 | parser = token_type('ident') + op('=') + function_argument 98 | return (parser >> NamedArgument).run(tokens, state) 99 | 100 | named_arguments = (named_argument + maybe(many(op(",") + named_argument)) 101 | >> NamedArguments) 102 | 103 | 104 | @Parser 105 | def function_argument(tokens, state): 106 | parser = (keyword("function") + name + 107 | op('(') + maybe(named_arguments) + op(')') 108 | | expression) 109 | return (parser >> FunctionArgument).run(tokens, state) 110 | 111 | 112 | @Parser 113 | def function_arguments(tokens, state): 114 | from modparc.syntax.equations import for_indices # circular dependency 115 | # Since funcparserlib doesn't have full backtracking 116 | # the `named_arguments` parser is matched first to avoid problems 117 | parser = (named_arguments 118 | | function_argument + 119 | maybe(op(",") + function_arguments 120 | | keyword('for') + for_indices)) 121 | return (parser >> FunctionArguments).run(tokens, state) 122 | 123 | 124 | function_call_args = (op("(") + maybe(function_arguments) + op(")") 125 | >> FunctionCallArgs) 126 | 127 | expression_list = (expression + maybe(many(op(",") + expression)) 128 | >> ExpressionList) 129 | 130 | output_expression_list = (maybe(expression) + 131 | maybe(many(op(",") + maybe(expression))) 132 | >> OutputExpressionList) 133 | 134 | 135 | subscript = op(":") | expression >> Subscript 136 | 137 | array_subscript = (op("[") + subscript + 138 | maybe(many(op(',') + subscript)) + op("]") 139 | >> ArraySubscript) 140 | 141 | component_reference = (maybe(op('.')) + token_type('ident') + 142 | maybe(array_subscript) + 143 | maybe(many(op('.') + token_type('ident') + 144 | maybe(array_subscript))) 145 | >> ComponentReference) 146 | 147 | string_comment = (maybe(token_type("string") + 148 | maybe(many(op("+") + token_type("string")))) 149 | >> StringComment) 150 | 151 | 152 | @Parser 153 | def annotation(tokens, state): 154 | from .modification import class_modification # circular dependency 155 | parser = keyword('annotation') + class_modification >> Annotation 156 | return parser.run(tokens, state) 157 | 158 | 159 | comment = string_comment + maybe(annotation) >> Comment 160 | -------------------------------------------------------------------------------- /modparc/syntax/extends.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | extends 4 | ---------------------------------- 5 | 6 | Parser definition for funcparserlib. The parsers that need forward declaration 7 | are defined as function annotated by the `Parser` decorator. 8 | 9 | The definitions are specified in the Appendix B.2.3 of the Modelica 10 | Specification 3.3. 11 | """ 12 | 13 | from funcparserlib.parser import maybe, Parser 14 | 15 | # pylint: disable=no-name-in-module, missing-docstring 16 | from modparc.syntax import keyword 17 | from modparc.syntax.expressions import annotation, name 18 | from modparc.syntax.syntax_elements import ExtendsClause, ConstrainingClause 19 | # pylint: enable=no-name-in-module 20 | 21 | 22 | @Parser 23 | def extends_clause(tokens, state): 24 | from .modification import class_modification 25 | parser = (keyword('extends') + name + maybe(class_modification) 26 | + maybe(annotation)) >> ExtendsClause 27 | return parser.run(tokens, state) 28 | 29 | 30 | @Parser 31 | def constraining_clause(tokens, state): 32 | from .modification import class_modification 33 | parser = keyword('constrainedby') + name + maybe(class_modification) 34 | return (parser >> ConstrainingClause).run(tokens, state) 35 | -------------------------------------------------------------------------------- /modparc/syntax/modification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | modification 4 | ---------------------------------- 5 | 6 | Parser definition for funcparserlib. The parsers that need forward declaration 7 | are defined as function annotated by the `Parser` decorator 8 | 9 | The definitions are specified in the Appendix B.2.5 of the Modelica 10 | Specification 3.3. 11 | """ 12 | 13 | from funcparserlib.parser import many, maybe, Parser 14 | 15 | # pylint: disable=no-name-in-module, missing-docstring 16 | from modparc.syntax import keyword, op, token_type 17 | from modparc.syntax.component_clause import (declaration, type_specifier, 18 | type_prefix) 19 | from modparc.syntax.expressions import (name, expression, string_comment, 20 | array_subscript, comment) 21 | from modparc.syntax.extends import constraining_clause 22 | from modparc.syntax.syntax_elements import (Modification, ShortClassDefinition, 23 | ComponentDeclaration1, 24 | ComponentClause1, 25 | ElementReplaceable, 26 | ElementRedeclaration, 27 | ElementModification, 28 | ElementModificationOrReplaceable, 29 | Argument, ArgumentList, 30 | ClassModification) 31 | # pylint: enable=no-name-in-module 32 | 33 | 34 | @Parser 35 | def modification(tokens, state): 36 | parser = (class_modification + maybe(op('=') + expression) 37 | | op('=') + expression 38 | | op(':=') + expression) >> Modification 39 | return parser.run(tokens, state) 40 | 41 | 42 | @Parser 43 | def short_class_definition(tokens, state): 44 | # circular import! 45 | from modparc.syntax.class_definition import (class_prefixes, enum_list, 46 | base_prefix) 47 | parser = (class_prefixes + token_type("ident") + op("=") 48 | + (base_prefix + name + maybe(array_subscript) 49 | + maybe(class_modification) + comment 50 | | keyword('enumeration') + op('(') + 51 | (maybe(enum_list) | op(":")) + op(')') + comment)) 52 | return (parser >> ShortClassDefinition).run(tokens, state) 53 | 54 | component_declaration1 = declaration + comment >> ComponentDeclaration1 55 | 56 | component_clause1 = (type_prefix + type_specifier + component_declaration1 57 | >> ComponentClause1) 58 | 59 | element_replaceable = (keyword("replaceable") + (short_class_definition 60 | | component_clause1) 61 | + maybe(constraining_clause)) >> ElementReplaceable 62 | 63 | element_redeclaration = (keyword("redeclare") + maybe(keyword("each")) 64 | + maybe(keyword("final")) + 65 | ((short_class_definition | component_clause1 66 | | element_replaceable))) >> ElementRedeclaration 67 | 68 | element_modification = (name + maybe(modification) + string_comment 69 | >> ElementModification) 70 | 71 | 72 | def km(key): 73 | return maybe(keyword(key)) 74 | 75 | element_modification_or_replaceable = (km('each') + km('final') + 76 | (element_modification | 77 | element_replaceable) 78 | >> ElementModificationOrReplaceable) 79 | 80 | argument = (element_modification_or_replaceable | element_redeclaration 81 | >> Argument) 82 | 83 | argument_list = argument + maybe(many(op(',') + argument)) >> ArgumentList 84 | 85 | 86 | @Parser 87 | def class_modification(tokens, state): 88 | parser = op('(') + maybe(argument_list) + op(')') >> ClassModification 89 | return parser.run(tokens, state) 90 | -------------------------------------------------------------------------------- /modparc/syntax/stored_definition.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | stored_definition 4 | ---------------------------------- 5 | 6 | Parser definition for funcparserlib. 7 | 8 | The definitions are specified in the Appendix B.2.1 of the Modelica 9 | Specification 3.3. 10 | 11 | This is the top-level module used by in the library api as it parses 12 | the contents of a Modelica source code file (files with suffix .mo). 13 | """ 14 | 15 | from funcparserlib.parser import many, maybe, skip, finished 16 | 17 | # pylint: disable=no-name-in-module, missing-docstring 18 | from modparc.syntax import keyword, op 19 | from modparc.syntax.class_definition import class_definition 20 | from modparc.syntax.expressions import name 21 | from modparc.syntax.syntax_elements import StoredDefinition 22 | # pylint: enable=no-name-in-module 23 | 24 | stored_definition = (maybe(keyword("within") + maybe(name) + op(";")) + 25 | many(maybe(keyword("final")) + 26 | class_definition + op(";")) + skip(finished) 27 | >> StoredDefinition) 28 | -------------------------------------------------------------------------------- /modparc/syntax/syntax_elements.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | syntax_element 4 | ---------------------------------- 5 | 6 | Each syntax element is defined as a class in the syntax_element module, to 7 | enable basic formatting and query function for the parse tree. 8 | """ 9 | 10 | 11 | class SyntaxElement(object): 12 | """ 13 | The class is a base implementation for all the syntax elements 14 | 15 | All the derived classes would inherit this syntax element, and they only 16 | differ in their names. 17 | 18 | The base implemenation provides possibility for inspection and querying 19 | the parsed syntax elements. 20 | """ 21 | 22 | def __init__(self, elements): 23 | """ 24 | Constructor used by `>>` operator after parsing 25 | 26 | This is a standard interface used in funcparserlib 27 | 28 | :param elements: the parsed subelements provided by parser 29 | """ 30 | self.elements = elements 31 | 32 | def __str__(self): 33 | return "{0}({1})".format(type(self).__name__, str(self.elements)) 34 | 35 | def __repr__(self): 36 | return self.__str__() 37 | 38 | def original_code(self): 39 | """ 40 | Return the token arranged by original string with only space and 41 | newline, and leave out all trailing newline and spaces 42 | 43 | Intended for roundtripping 44 | 45 | :return: string contained in the instance 46 | """ 47 | return SyntaxElement._create_string(self.search('Token')) 48 | 49 | def code(self): 50 | """ 51 | Create a predefined representation of all the tokens in the instance 52 | 53 | :return: formatted tokens contained in the instance 54 | """ 55 | ROW = 0 56 | COLUMN = 1 57 | 58 | tokens = self.search('Token') 59 | min_row_token = min(tokens, key=lambda t: t.start[ROW]) 60 | min_row_position = min_row_token.start[ROW] 61 | min_column_token = min(tokens, key=lambda t: t.start[COLUMN]) 62 | min_column_position = min_column_token.start[COLUMN] 63 | row_offset = 1 - min_row_position # nominal start position is 1 64 | column_offset = 1 - min_column_position # nominal start position is 1 65 | 66 | return SyntaxElement._create_string(tokens, row_offset, column_offset) 67 | 68 | @staticmethod 69 | def _create_string(tokens, row_offset=0, column_offset=0): 70 | """ 71 | Return the token arranged by original string with only space and 72 | newline, and leave out all trailing newline and spaces with a 73 | predefined offset. 74 | 75 | :return: string created by the tokens and offset 76 | """ 77 | def append_line(old_string, start_position, value): 78 | """ 79 | :return: appended string at predefined positions 80 | """ 81 | assert start_position >= len(old_string) 82 | no_of_missing_char = start_position - len(old_string) - 1 83 | old_string += ' ' * no_of_missing_char 84 | old_string += value 85 | return old_string 86 | ROW = 0 87 | COLUMN = 1 88 | return_results = [] 89 | for token in tokens: 90 | token_row = token.start[ROW] + row_offset 91 | token_column = token.start[COLUMN] + column_offset 92 | if token_row > len(return_results): 93 | no_of_missing_lines = token_row - len(return_results) 94 | return_results.extend([''] * (no_of_missing_lines - 1)) 95 | new_line = append_line('', token_column, token.value) 96 | return_results.append(new_line) 97 | else: 98 | old_line = return_results[token_row - 1] 99 | new_line = append_line(old_line, token_column, token.value) 100 | return_results[token_row - 1] = new_line 101 | 102 | return "\n".join(return_results) 103 | 104 | def search(self, type_name): 105 | """ 106 | Create a predefined representation of all the tokens in the instance 107 | 108 | :param type_name: use the class name to find all matching subelements 109 | :return: list of found elements of the class type_name 110 | """ 111 | found_elements = [] 112 | SyntaxElement.find(self, type_name, found_elements) 113 | return found_elements 114 | 115 | @staticmethod 116 | def find(syntax_element, type_name, result): 117 | """ 118 | Search the matching elements with pre-order tree trasversal 119 | 120 | :param syntax_element: the syntax element to be explored 121 | :param type_name: type name to be searched 122 | :param result: mutable list to store the results 123 | :return: no explicit return, communication through result variable 124 | """ 125 | if type(syntax_element).__name__ == type_name: 126 | result.append(syntax_element) 127 | 128 | if hasattr(syntax_element, 'elements'): 129 | SyntaxElement.find(syntax_element.elements, 130 | type_name, result) 131 | elif hasattr(syntax_element, '__getitem__'): 132 | for el in syntax_element: 133 | SyntaxElement.find(el, type_name, result) 134 | 135 | 136 | class _Definition(SyntaxElement): 137 | """ 138 | Base class for definition class, to support additional functionalities 139 | """ 140 | 141 | def name(self): 142 | """ 143 | :return: the name of the definition 144 | """ 145 | token_name = self.search('ClassSpecifier')[0].elements[0] 146 | assert token_name.type == 'ident' 147 | 148 | return token_name.value 149 | 150 | def prefix(self): 151 | """ 152 | :return: the prefix of the definition 153 | """ 154 | class_prefix = self.search('ClassPrefixes')[0] 155 | 156 | return class_prefix.code() 157 | 158 | def class_type(self): 159 | """ 160 | :return: the type of the definition 161 | """ 162 | class_prefix = self.search('ClassPrefixes')[0] 163 | 164 | return class_prefix.elements[-1].value 165 | 166 | classes = ['Expression', 'SimpleExpression', 'LogicalExpression', 167 | 'LogicalTerm', 'LogicalFactor', 'Relation', 168 | 'ArithmeticExpression', 'Term', 'Factor', 'Primary', 'RelOp', 169 | 'MulOp', 'AddOp', 'Name', 'NamedArgument', 'NamedArguments', 170 | 'FunctionArgument', 'FunctionArguments', 'FunctionCallArgs', 171 | 'ExpressionList', 'OutputExpressionList', 'Subscript', 172 | 'ArraySubscript', 'ComponentReference', 'StringComment', 173 | 'Annotation', 'Comment', "LanguageSpecification", "BasePrefix", 174 | "ExternalFunctionCall", "Element", "ElementList", 175 | "Composition", "ClassSpecifier", "ClassPrefixes", 176 | "EnumerationLiteral", "EnumList", "ImportList", "ImportClause", 177 | "TypePrefix", "TypeSpecifier", "ConditionAttribute", "Declaration", 178 | "ComponentDeclaration", "ComponentList", "ComponentClause", 179 | "ForIndex", "ForIndices", "ConnectClause", "Equation", "IfEquation", 180 | "ForEquation", "WhileEquation", "WhenEquation", "Statement", 181 | "IfStatement", "ForStatement", "WhileStatement", "WhenStatement", 182 | "EquationSection", "AlgorithmSection", "ExtendsClause", 183 | "ConstrainingClause", "Modification", "ShortClassDefinition", 184 | "ComponentDeclaration1", "ComponentClause1", "ElementReplaceable", 185 | "ElementRedeclaration", "ElementModification", 186 | "ElementModificationOrReplaceable", "Argument", "ArgumentList", 187 | "ClassModification", "Assertion"] 188 | definition_classes = ["ClassDefinition", "StoredDefinition"] 189 | 190 | variables = globals() 191 | 192 | for class_name in classes: 193 | variables[class_name] = type(class_name, (SyntaxElement,), {}) 194 | 195 | for class_name in definition_classes: 196 | variables[class_name] = type(class_name, (_Definition,), {}) 197 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Specify a configuration file. 4 | #rcfile= 5 | 6 | # Python code to execute, usually for sys.path manipulation such as 7 | # pygtk.require(). 8 | #init-hook= 9 | 10 | # Profiled execution. 11 | profile=no 12 | 13 | # Add files or directories to the blacklist. They should be base names, not 14 | # paths. 15 | ignore=CVS, migrations 16 | 17 | # Pickle collected data for later comparisons. 18 | persistent=yes 19 | 20 | # List of plugins (as comma separated values of python modules names) to load, 21 | # usually to register additional checkers. 22 | load-plugins= 23 | 24 | 25 | [MESSAGES CONTROL] 26 | 27 | # Enable the message, report, category or checker with the given id(s). You can 28 | # either give multiple identifier separated by comma (,) or put this option 29 | # multiple time. 30 | #enable= 31 | 32 | # Disable the message, report, category or checker with the given id(s). You 33 | # can either give multiple identifier separated by comma (,) or put this option 34 | # multiple time (only on the command line, not in the configuration file where 35 | # it should appear only once). 36 | disable= 37 | # Never going to use these 38 | # W0142: Used * or ** magic 39 | # W0141: Used builtin function 'map' 40 | # I0011: 36,0: Locally disabling E1101 41 | invalid-name, locally-disabled, locally-enabled, cyclic-import 42 | 43 | 44 | [REPORTS] 45 | 46 | # Set the output format. Available formats are text, parseable, colorized, msvs 47 | # (visual studio) and html 48 | output-format=text 49 | 50 | # Include message's id in output 51 | include-ids=yes 52 | 53 | # Put messages in a separate file for each module / package specified on the 54 | # command line instead of printing them on stdout. Reports (if any) will be 55 | # written in a file name "pylint_global.[txt|html]". 56 | files-output=no 57 | 58 | # Tells whether to display a full report or only the messages 59 | reports=no 60 | 61 | # Python expression which should return a note less than 10 (10 is the highest 62 | # note). You have access to the variables errors warning, statement which 63 | # respectively contain the number of errors / warnings messages and the total 64 | # number of statements analyzed. This is used by the global evaluation report 65 | # (RP0004). 66 | # evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 67 | 68 | # Add a comment according to your evaluation note. This is used by the global 69 | # evaluation report (RP0004). 70 | # comment=no 71 | 72 | 73 | [TYPECHECK] 74 | 75 | # Tells whether missing members accessed in mixin class should be ignored. A 76 | # mixin class is detected if its name ends with "mixin" (case insensitive). 77 | # ignore-mixin-members=yes 78 | 79 | # List of classes names for which member attributes should not be checked 80 | # (useful for classes with attributes dynamically set). 81 | ignored-classes=SQLObject 82 | 83 | # When zope mode is activated, add a predefined set of Zope acquired attributes 84 | # to generated-members. 85 | zope=no 86 | 87 | # List of members which are set dynamically and missed by pylint inference 88 | # system, and so shouldn't trigger E0201 when accessed. Python regular 89 | # expressions are accepted. 90 | generated-members= 91 | REQUEST, 92 | acl_users, 93 | aq_parent, 94 | objects, 95 | DoesNotExist, 96 | can_read, 97 | can_write, 98 | get_url, 99 | size, 100 | content, 101 | status_code 102 | 103 | 104 | [BASIC] 105 | 106 | # List of builtins function names that should not be used, separated by a comma 107 | bad-functions=map,filter,apply,input 108 | 109 | # Regular expression which should only match correct module names 110 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 111 | 112 | # Regular expression which should only match correct module level names 113 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__)|log|urlpatterns)$ 114 | 115 | # Regular expression which should only match correct class names 116 | class-rgx=[A-Z_][a-zA-Z0-9]+$ 117 | 118 | # Regular expression which should only match correct function names 119 | function-rgx=[a-z_][a-z0-9_]{2,30}$ 120 | 121 | # Regular expression which should only match correct method names 122 | method-rgx=([a-z_][a-z0-9_]{2,60}|setUp|set[Uu]pClass|tearDown|tear[Dd]ownClass|assert[A-Z]\w*)$ 123 | 124 | # Regular expression which should only match correct instance attribute names 125 | attr-rgx=[a-z_][a-z0-9_]{2,30}$ 126 | 127 | # Regular expression which should only match correct argument names 128 | argument-rgx=[a-z_][a-z0-9_]{2,30}$ 129 | 130 | # Regular expression which should only match correct variable names 131 | variable-rgx=[a-z_][a-z0-9_]{2,30}$ 132 | 133 | # Regular expression which should only match correct list comprehension / 134 | # generator expression variable names 135 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 136 | 137 | # Good variable names which should always be accepted, separated by a comma 138 | good-names=i,j,k,ex,Run,_ 139 | 140 | # Bad variable names which should always be refused, separated by a comma 141 | bad-names=foo,bar,baz,toto,tutu,tata 142 | 143 | # Regular expression which should only match functions or classes name which do 144 | # not require a docstring 145 | # no-docstring-rgx=(__.*__|test_.*|setUp|tearDown) 146 | 147 | 148 | [MISCELLANEOUS] 149 | 150 | # List of note tags to take in consideration, separated by a comma. 151 | notes=FIXME,XXX,TODO 152 | 153 | 154 | [FORMAT] 155 | 156 | # Maximum number of characters on a single line. 157 | max-line-length=120 158 | 159 | # Maximum number of lines in a module 160 | max-module-lines=1000 161 | 162 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 163 | # tab). 164 | indent-string=' ' 165 | 166 | 167 | [SIMILARITIES] 168 | 169 | # Minimum lines number of a similarity. 170 | min-similarity-lines=4 171 | 172 | # Ignore comments when computing similarities. 173 | ignore-comments=yes 174 | 175 | # Ignore docstrings when computing similarities. 176 | ignore-docstrings=yes 177 | 178 | 179 | [VARIABLES] 180 | 181 | # Tells whether we should check for unused import in __init__ files. 182 | init-import=no 183 | 184 | # A regular expression matching the beginning of the name of dummy variables 185 | # (i.e. not used). 186 | dummy-variables-rgx=_|dummy 187 | 188 | # List of additional names supposed to be defined in builtins. Remember that 189 | # you should avoid to define new builtins when possible. 190 | additional-builtins= 191 | 192 | 193 | [IMPORTS] 194 | 195 | # Deprecated modules which should not be used, separated by a comma 196 | deprecated-modules=regsub,string,TERMIOS,Bastion,rexec 197 | 198 | # Create a graph of every (i.e. internal and external) dependencies in the 199 | # given file (report RP0402 must not be disabled) 200 | import-graph= 201 | 202 | # Create a graph of external dependencies in the given file (report RP0402 must 203 | # not be disabled) 204 | ext-import-graph= 205 | 206 | # Create a graph of internal dependencies in the given file (report RP0402 must 207 | # not be disabled) 208 | int-import-graph= 209 | 210 | 211 | [DESIGN] 212 | 213 | # # Maximum number of arguments for function / method 214 | # max-args=5 215 | # 216 | # # Argument names that match this expression will be ignored. Default to name 217 | # # with leading underscore 218 | # ignored-argument-names=_.* 219 | # 220 | # # Maximum number of locals for function / method body 221 | # max-locals=15 222 | # 223 | # # Maximum number of return / yield for function / method body 224 | # max-returns=6 225 | # 226 | # # Maximum number of branch for function / method body 227 | # max-branchs=12 228 | # 229 | # # Maximum number of statements in function / method body 230 | # max-statements=50 231 | # 232 | # # Maximum number of parents for a class (see R0901). 233 | # max-parents=7 234 | # 235 | # # Maximum number of attributes for a class (see R0902). 236 | # max-attributes=7 237 | # 238 | # # Minimum number of public methods for a class (see R0903). 239 | # min-public-methods=2 240 | # 241 | # # Maximum number of public methods for a class (see R0904). 242 | # max-public-methods=20 243 | 244 | 245 | [CLASSES] 246 | 247 | 248 | [EXCEPTIONS] 249 | 250 | # Exceptions that will emit a warning when being caught. Defaults to 251 | # "Exception" 252 | overgeneral-exceptions=Exception 253 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | funcparserlib==0.3.6 2 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pip==9.0.1 2 | bumpversion==0.5.3 3 | wheel==0.29.0 4 | watchdog==0.8.3 5 | flake8==3.3.0 6 | tox==3.7.0 7 | coverage==4.4 8 | Sphinx==1.6.3 9 | cryptography==1.9 10 | PyYAML==3.12 11 | pytest==4.1.1 12 | funcparserlib==0.3.6 13 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.2.1 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:modparc/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [flake8] 18 | exclude = docs 19 | 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup 5 | 6 | with open('README.rst') as readme_file: 7 | readme = readme_file.read() 8 | 9 | with open('HISTORY.rst') as history_file: 10 | history = history_file.read() 11 | 12 | requirements = [ 13 | "funcparserlib", 14 | ] 15 | 16 | test_requirements = [ 17 | "funcparserlib", 18 | "pytest", 19 | "tox", 20 | "flake8", 21 | "wheel" 22 | ] 23 | 24 | setup( 25 | name='modparc', 26 | version='0.2.1', 27 | description="A Modelica parser based on parser generator", 28 | long_description=readme + '\n\n' + history, 29 | author="谢东平 Dongping XIE", 30 | author_email='dongping.xie.tud@gmail.com', 31 | url='https://github.com/xie-dongping/modparc', 32 | packages=[ 33 | 'modparc', 34 | 'modparc.syntax', 35 | ], 36 | package_dir={'modparc': 37 | 'modparc'}, 38 | include_package_data=True, 39 | install_requires=requirements, 40 | license="GNU General Public License v3", 41 | zip_safe=False, 42 | keywords='modparc', 43 | classifiers=[ 44 | 'Development Status :: 2 - Pre-Alpha', 45 | 'Intended Audience :: Developers', 46 | 'Intended Audience :: Science/Research', 47 | 'Topic :: Scientific/Engineering', 48 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 49 | 'Natural Language :: English', 50 | "Programming Language :: Python :: 2", 51 | 'Programming Language :: Python :: 2.7', 52 | 'Programming Language :: Python :: 3', 53 | 'Programming Language :: Python :: 3.3', 54 | 'Programming Language :: Python :: 3.4', 55 | 'Programming Language :: Python :: 3.5', 56 | ], 57 | test_suite='tests', 58 | tests_require=test_requirements 59 | ) 60 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/test_modparc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # pylint: disable=missing-docstring 4 | 5 | """ 6 | test_modparc 7 | ---------------------------------- 8 | 9 | Tests for `modparc` module. 10 | """ 11 | 12 | from funcparserlib.parser import skip, finished 13 | 14 | import modparc 15 | from modparc.syntax import tokenize 16 | 17 | 18 | def verify_parsed_result(source_code, parser, 19 | subelement_type, subelement_code): 20 | """ 21 | Verify the parsed result contain a predefined set of subelements 22 | 23 | :param source_code: code line to be parsed 24 | :param parser: parser to parse the code 25 | :param subelement_type: inspect all the subelement of this type 26 | :param subelement_code: reference result value for each subelement 27 | :return: returns nothing 28 | """ 29 | tokens = tokenize(source_code) 30 | parsed_element = (parser + skip(finished)).parse(tokens) 31 | subelements = parsed_element.search(subelement_type) 32 | assert len(subelements) == len(subelement_code) 33 | for (i, parsed_subelements) in enumerate(subelements): 34 | assert parsed_subelements.code() == subelement_code[i] 35 | 36 | 37 | def test_simple_expression(): 38 | source_code = "1:n" 39 | subelement_code = ['1', 'n'] 40 | subelement_type = 'LogicalExpression' 41 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 42 | subelement_type, subelement_code) 43 | 44 | 45 | def test_expression1(): 46 | source_code = r'x*(alpha-beta*y)' 47 | subelement_code = ['x*(alpha-beta*y)', 'alpha-beta*y'] 48 | subelement_type = 'Expression' 49 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 50 | subelement_type, subelement_code) 51 | 52 | 53 | def test_expression2(): 54 | source_code = r'k1*(phi2-phi1)+d1*der(phi2-phi1)' 55 | subelement_code = ['k1*(phi2-phi1)+d1*der(phi2-phi1)', 56 | 'phi2-phi1', 'phi2-phi1'] 57 | subelement_type = 'Expression' 58 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 59 | subelement_type, subelement_code) 60 | 61 | 62 | def test_unicode_expression(): 63 | source_code = u"x*('阿尔法'-beta*y)" 64 | subelement_code = [u"x*('阿尔法'-beta*y)", u"'阿尔法'-beta*y"] 65 | subelement_type = 'Expression' 66 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 67 | subelement_type, subelement_code) 68 | 69 | 70 | def test_expression_if1(): 71 | source_code = r'if done then 0 else -9.81' 72 | subelement_code = ['if done then 0 else -9.81', 'done', '0', '-9.81'] 73 | subelement_type = 'Expression' 74 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 75 | subelement_type, subelement_code) 76 | 77 | 78 | def test_expression_if2(): 79 | source_code = r'reinit(v, -e*(if h<-eps then 0 else pre(v)))' 80 | subelement_code = ['reinit(v, -e*(if h<-eps ' 81 | + 'then 0 else pre(v)))', 82 | 'v', '-e*(if h<-eps then 0 else pre(v))', 83 | 'if h<-eps then 0 else pre(v)', 'h<-eps', 84 | '0', 'pre(v)', 'v'] 85 | subelement_type = 'Expression' 86 | verify_parsed_result(source_code, modparc.syntax.expressions.expression, 87 | subelement_type, subelement_code) 88 | 89 | 90 | def test_function_arguments(): 91 | " Problem with the backtracking with named_arguments" 92 | source_code = """ 93 | Text( 94 | extent={{-100,-40},{100,-80}}, 95 | lineColor={0,0,0}, 96 | fillColor={255,255,255}, 97 | fillPattern=FillPattern.Solid, 98 | textString="%name") 99 | """ 100 | subelement_code = ['extent={{-100,-40},{100,-80}}', 101 | 'lineColor={0,0,0}', 102 | 'fillColor={255,255,255}', 103 | 'fillPattern=FillPattern.Solid', 104 | 'textString="%name"'] 105 | subelement_type = 'NamedArgument' 106 | verify_parsed_result(source_code, 107 | modparc.syntax.expressions.function_arguments, 108 | subelement_type, subelement_code) 109 | 110 | 111 | def test_simple_equation(): 112 | source_code = r'der(v) = if done then 0 else -9.81' 113 | subelement_code = ['v', 'if done then 0 else -9.81', 'done', 114 | '0', '-9.81', ] 115 | subelement_type = 'Expression' 116 | verify_parsed_result(source_code, modparc.syntax.equations.equation, 117 | subelement_type, subelement_code) 118 | 119 | 120 | def test_if_equation(): 121 | source_code = """ 122 | if init==InitializationOptions.FixedPopulation then 123 | population = initial_population; 124 | elseif init==InitializationOptions.SteadyState then 125 | der(population) = 0; 126 | else 127 | end if 128 | """ 129 | subelement_code = ['population = initial_population', 130 | 'der(population) = 0'] 131 | subelement_type = 'Equation' 132 | verify_parsed_result(source_code, modparc.syntax.equations.if_equation, 133 | subelement_type, subelement_code) 134 | 135 | 136 | def test_roundtripping(): 137 | source_code = """ 138 | if init==InitializationOptions.FixedPopulation then 139 | population = initial_population; 140 | elseif init==InitializationOptions.SteadyState then 141 | der(population) = 0; 142 | else 143 | end if""" 144 | parser = modparc.syntax.equations.if_equation 145 | syntax_element = parser.parse(tokenize(source_code)) 146 | 147 | assert syntax_element.original_code() == source_code 148 | 149 | 150 | def test_get_name(): 151 | source_code = """ 152 | within ModelicaByExample.BasicEquations.SimpleExample; 153 | model FirstOrder 154 | Real x; 155 | equation 156 | der(x) = 1-x; 157 | end FirstOrder; 158 | """ 159 | defintion = modparc.parse(source_code) 160 | assert defintion.name() == "FirstOrder" 161 | 162 | 163 | def test_get_type(): 164 | source_code = """ 165 | within ModelicaByExample.BasicEquations.SimpleExample; 166 | model FirstOrder 167 | Real x; 168 | equation 169 | der(x) = 1-x; 170 | end FirstOrder; 171 | """ 172 | defintion = modparc.parse(source_code) 173 | assert defintion.class_type() == "model" 174 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py34, py35, flake8 3 | 4 | [testenv:flake8] 5 | basepython=python 6 | deps=flake8 7 | commands=flake8 modparc 8 | 9 | [testenv] 10 | setenv = 11 | PYTHONPATH = {toxinidir}:{toxinidir}/modparc 12 | deps = 13 | -r{toxinidir}/requirements_dev.txt 14 | commands = 15 | pip install -U pip 16 | py.test --basetemp={envtmpdir} 17 | 18 | 19 | ; If you want to make tox run the tests with the same versions, create a 20 | ; requirements.txt with the pinned versions and uncomment the following lines: 21 | ; deps = 22 | ; -r{toxinidir}/requirements.txt 23 | -------------------------------------------------------------------------------- /travis_pypi_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Update encrypted deploy password in Travis config file 4 | """ 5 | 6 | 7 | from __future__ import print_function 8 | import base64 9 | import json 10 | import os 11 | from getpass import getpass 12 | import yaml 13 | from cryptography.hazmat.primitives.serialization import load_pem_public_key 14 | from cryptography.hazmat.backends import default_backend 15 | from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 16 | 17 | 18 | try: 19 | from urllib import urlopen 20 | except: 21 | from urllib.request import urlopen 22 | 23 | 24 | GITHUB_REPO = 'xie-dongping/modparc' 25 | TRAVIS_CONFIG_FILE = os.path.join( 26 | os.path.dirname(os.path.abspath(__file__)), '.travis.yml') 27 | 28 | 29 | def load_key(pubkey): 30 | """Load public RSA key, with work-around for keys using 31 | incorrect header/footer format. 32 | 33 | Read more about RSA encryption with cryptography: 34 | https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ 35 | """ 36 | try: 37 | return load_pem_public_key(pubkey.encode(), default_backend()) 38 | except ValueError: 39 | # workaround for https://github.com/travis-ci/travis-api/issues/196 40 | pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') 41 | return load_pem_public_key(pubkey.encode(), default_backend()) 42 | 43 | 44 | def encrypt(pubkey, password): 45 | """Encrypt password using given RSA public key and encode it with base64. 46 | 47 | The encrypted password can only be decrypted by someone with the 48 | private key (in this case, only Travis). 49 | """ 50 | key = load_key(pubkey) 51 | encrypted_password = key.encrypt(password, PKCS1v15()) 52 | return base64.b64encode(encrypted_password) 53 | 54 | 55 | def fetch_public_key(repo): 56 | """Download RSA public key Travis will use for this repo. 57 | 58 | Travis API docs: http://docs.travis-ci.com/api/#repository-keys 59 | """ 60 | keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) 61 | data = json.loads(urlopen(keyurl).read().decode()) 62 | if 'key' not in data: 63 | errmsg = "Could not find public key for repo: {}.\n".format(repo) 64 | errmsg += "Have you already added your GitHub repo to Travis?" 65 | raise ValueError(errmsg) 66 | return data['key'] 67 | 68 | 69 | def prepend_line(filepath, line): 70 | """Rewrite a file adding a line to its beginning. 71 | """ 72 | with open(filepath) as f: 73 | lines = f.readlines() 74 | 75 | lines.insert(0, line) 76 | 77 | with open(filepath, 'w') as f: 78 | f.writelines(lines) 79 | 80 | 81 | def load_yaml_config(filepath): 82 | with open(filepath) as f: 83 | return yaml.load(f) 84 | 85 | 86 | def save_yaml_config(filepath, config): 87 | with open(filepath, 'w') as f: 88 | yaml.dump(config, f, default_flow_style=False) 89 | 90 | 91 | def update_travis_deploy_password(encrypted_password): 92 | """Update the deploy section of the .travis.yml file 93 | to use the given encrypted password. 94 | """ 95 | config = load_yaml_config(TRAVIS_CONFIG_FILE) 96 | 97 | config['deploy']['password'] = dict(secure=encrypted_password) 98 | 99 | save_yaml_config(TRAVIS_CONFIG_FILE, config) 100 | 101 | line = ('# This file was autogenerated and will overwrite' 102 | ' each time you run travis_pypi_setup.py\n') 103 | prepend_line(TRAVIS_CONFIG_FILE, line) 104 | 105 | 106 | def main(args): 107 | public_key = fetch_public_key(args.repo) 108 | password = args.password or getpass('PyPI password: ') 109 | update_travis_deploy_password(encrypt(public_key, password.encode())) 110 | print("Wrote encrypted password to .travis.yml -- you're ready to deploy") 111 | 112 | 113 | if '__main__' == __name__: 114 | import argparse 115 | parser = argparse.ArgumentParser(description=__doc__) 116 | parser.add_argument('--repo', default=GITHUB_REPO, 117 | help='GitHub repo (default: %s)' % GITHUB_REPO) 118 | parser.add_argument('--password', 119 | help='PyPI password (will prompt if not provided)') 120 | 121 | args = parser.parse_args() 122 | main(args) 123 | --------------------------------------------------------------------------------