Skip to content

String Reading and Path Typing #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ jobs:
- name: Cargo Tests
if: success() || failure()
run: cargo test
- run: pip install dist/*.whl
- run: pip install mypy dist/*.whl
- name: Python Tests
run: python3 simple.py
working-directory: tests
run: python3 tests/simple.py
- name: Typying Check
run: mypy tests/simple.py

get_dynamic_version:
runs-on: ubuntu-latest
Expand Down
158 changes: 158 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,162 @@
**/.DS_Store
BUGS
**/.env
**/.direnv
# These are backup files generated by rustfmt
**/*.rs.bk

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
7 changes: 4 additions & 3 deletions src/python_wrapper/cvldoc_parser.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from enum import Enum
from pathlib import Path
from typing import Any, List, Dict, Optional
from os import PathLike
from typing import Any, Dict, List, Optional, Union

class DocumentationTag:
kind: str
Expand Down Expand Up @@ -51,4 +51,5 @@ class CvlElement:
def element_returns(self) -> Optional[str]: ...
def element_params(self) -> Optional[List[tuple[str, str]]]: ...

def parse(path: Path) -> List[CvlElement]: ...
def parse(path: Union[str, PathLike]) -> List[CvlElement]: ...
def parse_string(src: str) -> List[CvlElement]: ...
28 changes: 18 additions & 10 deletions src/python_wrapper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,35 @@ fn handle_io_error(path: &Path, e: std::io::Error) -> PyErr {
}
}

/// takes a path to a file a(s a string). returns a list of parsed cvldocs,
/// takes a source code as a string. returns a list of parsed cvldocs,
/// or an appropriate error in the case of a failure.
///
/// throws:
/// - `OSError` if file reading failed.
/// - `RuntimeError` if source code parsing failed.
#[pyfunction]
fn parse(py: Python, path: PathBuf) -> PyResult<Vec<CvlElementPy>> {
let src = file_contents(path.as_path())?;

let elements = Builder::new(&src).build().map_err(|_| {
let display = path.display();
let desc = format!("failed to parse source file: {display}");
PyRuntimeError::new_err(desc)
})?;
fn parse_string(py: Python, src: String) -> PyResult<Vec<CvlElementPy>> {
let elements = Builder::new(&src)
.build()
.map_err(|_| PyRuntimeError::new_err("Failed to parse source code"))?;

elements
.into_iter()
.map(|cvl_element| CvlElementPy::new(py, cvl_element))
.collect()
}

/// takes a path to a file a(s a string). returns a list of parsed cvldocs,
/// or an appropriate error in the case of a failure.
///
/// throws:
/// - `OSError` if file reading failed.
/// - `RuntimeError` if source code parsing failed.
#[pyfunction]
fn parse(py: Python, path: PathBuf) -> PyResult<Vec<CvlElementPy>> {
let src = file_contents(path.as_path())?;
parse_string(py, src)
}

#[pymodule]
fn cvldoc_parser(_py: Python, module: &PyModule) -> PyResult<()> {
module.add_class::<CvlElementPy>()?;
Expand All @@ -59,6 +66,7 @@ fn cvldoc_parser(_py: Python, module: &PyModule) -> PyResult<()> {
module.add_class::<DocumentationTagPy>()?;

wrap_pyfunction!(parse, module).and_then(|function| module.add_function(function))?;
wrap_pyfunction!(parse_string, module).and_then(|function| module.add_function(function))?;

Ok(())
}
32 changes: 30 additions & 2 deletions tests/simple.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,32 @@
from pathlib import Path

import cvldoc_parser

parsed = cvldoc_parser.parse("definition_test.spec")
assert len(parsed) == 3, "should parse to 3 elements"

def as_list(
elements: list[cvldoc_parser.CvlElement],
) -> list[tuple[str, str | None, str | None, list[tuple[str, str]] | None]]:
return [
(
x.raw(),
x.element_name(),
x.element_returns(),
x.element_params(),
)
for x in elements
]


spec_file = Path(__file__).parent / "definition_test.spec"

p_file = cvldoc_parser.parse(spec_file)

assert len(p_file) == 3, "should parse to 3 elements"

p_file_as_string = cvldoc_parser.parse(spec_file.as_posix())
p_from_string = cvldoc_parser.parse_string(spec_file.read_text())

p = map(as_list, [p_file, p_file_as_string, p_from_string])
assert all(
x == y for x in p for y in p
), "all three parsers should parse the same elements"
Comment on lines +29 to +32
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯