diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..527d57b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: +- package-ecosystem: pip + directory: "/" + schedule: + interval: daily + time: "07:00" + groups: + python-packages: + patterns: + - "*" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..0720cb2 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,74 @@ +name: Publish to PyPI + +on: + push: + tags: + - '[0-9]+.[0-9]+.[0-9]+' # Matches semantic versioning tags + - '[0-9]+.[0-9]+.[0-9]+-test.*' # Test releases + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.11', '3.12'] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies and run CI + run: | + python -m pip install --upgrade pip + pip install build pytest pytest-cov setuptools_scm + make ci + + publish: + needs: test + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.12' + + - name: Verify tag version matches package version + run: | + python -m pip install --upgrade pip + pip install build pytest pytest-cov setuptools_scm twine + PACKAGE_VERSION=$(python -m setuptools_scm) + TAG_VERSION=${GITHUB_REF#refs/tags/} # Remove 'refs/tags/' prefix + if [ "$PACKAGE_VERSION" != "$TAG_VERSION" ]; then + echo "Package version ($PACKAGE_VERSION) does not match tag version ($TAG_VERSION)" + exit 1 + fi + + - name: Publish to TestPyPI + if: contains(github.ref, 'test') + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.TEST_PYPI_API_TOKEN }} + run: make all && twine upload --repository testpypi dist/* + + - name: Publish to PyPI + if: "!contains(github.ref, 'test')" + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} + run: make dist + + - name: Create Release + uses: softprops/action-gh-release@v1 + with: + files: dist/* + generate_release_notes: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..378e52d --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,26 @@ +name: Tests + +on: + pull_request: + branches: [ main ] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.12'] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies and run CI + run: | + python -m pip install --upgrade pip + pip install pytest pytest-cov + make ci diff --git a/.github/workflows/windows-test.yml b/.github/workflows/windows-test.yml new file mode 100644 index 0000000..a0e269c --- /dev/null +++ b/.github/workflows/windows-test.yml @@ -0,0 +1,48 @@ +name: Windows Package Test +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + # Optional: manual trigger + workflow_dispatch: + +jobs: + test-windows: + runs-on: windows-latest + strategy: + matrix: + python-version: ['3.12'] + architecture: ['x64'] + + steps: + - uses: actions/checkout@v3 + - uses: actions/cache@v3 + with: + path: ~\AppData\Local\pip\Cache + key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} + + - name: Set up Python ${{ matrix.python-version }} ${{ matrix.architecture }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + architecture: ${{ matrix.architecture }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build pytest pytest-cov + + - name: Run tests + run: | + make ci + + # Optional: Upload artifacts if your package generates any + - name: Upload artifacts + if: failure() + uses: actions/upload-artifact@v3 + with: + name: test-artifacts + path: | + ./*.log + ./tests/results diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a8c941 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/src/version/_version.py +src/*.egg-info +__pycache__ +dist +build +out +.coverage +.*.history* +*.tags.cache* diff --git a/LICENSE b/LICENSE index e69de29..7a4a3ea 100644 --- a/LICENSE +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e6852c9 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +.PHONY: all dist d clean c version v install i test t build b + +ci: clean install test +all: ci build version + +dist d: all + scripts/check-version.sh + # Win MSYS2 support: force config file location + twine upload $$(test -e ~/.pypirc && echo '--config-file ~/.pypirc') dist/* + +clean c: + rm -rfv out dist build/bdist.* src/*.egg-info + +version v: + git describe --tags ||: + python -m setuptools_scm + +install i: + pip install --upgrade --force-reinstall -e . + +test t: + pytest --cov=src/cedarscript_ast_parser tests/ --cov-report term-missing + +build b: + # SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 + python -m build diff --git a/README.md b/README.md index d56e1a6..dc08aa8 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ [![PyPI version](https://badge.fury.io/py/cedarscript-ast-parser.svg)](https://pypi.org/project/cedarscript-ast-parser/) [![Python Versions](https://img.shields.io/pypi/pyversions/cedarscript-ast-parser.svg)](https://pypi.org/project/cedarscript-ast-parser/) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) `CEDARScript AST Parser` is a Python library for parsing and interpreting `CEDARScript`, a SQL-like language designed for concise code analysis, manipulation, and refactoring tasks. ## What is CEDARScript? -[CEDARScript](https://github.com/CEDARScript/cedarscript-grammar#readme) (_Concise Examination, Development, And Refactoring Script_) is a domain-specific language that +[CEDARScript](https://bit.ly/cedarscript) (_Concise Examination, Development, And Refactoring Script_) is a domain-specific language that aims to improve how AI coding assistants interact with codebases and communicate their code modification intentions. It provides a standardized way to express complex code modification and analysis operations, making it easier for AI-assisted development tools to understand and execute these tasks. @@ -17,7 +17,7 @@ AI-assisted development tools to understand and execute these tasks. ## Features - Parse `CEDARScript` Abstract Syntax Tree (`AST`) that was generated by Tree-Sitter into a list of commands -- Support for various code manipulation andn analysis commands (CREATE, UPDATE, RM, MV, SELECT) +- Support for various code manipulation and analysis commands (CREATE, UPDATE, RM, MV, SELECT) - Return results in `XML` format for easier parsing and processing by LLM systems ## Installation diff --git a/pyproject.toml b/pyproject.toml index a5777b1..a07ecfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,18 +1,22 @@ [build-system] -requires = ["setuptools>=61.0", "wheel"] +requires = ["setuptools>=61.0", "wheel", "setuptools_scm[toml]>=6.2"] build-backend = "setuptools.build_meta" +# To build both source and wheel distributions: +# python -m build --sdist --wheel +# This creates both .tar.gz (source) and .whl (wheel) files in the 'dist' directory + [project] name = "cedarscript-ast-parser" dynamic = ["version"] description = "A library for parsing and interpreting CEDARScript, a SQL-like language for code analysis and transformations" -readme = "README.md" authors = [{ name = "Elifarley", email = "cedarscript@orgecc.com" }] -license = { file = "LICENSE" } +readme = "README.md" +license = {text = "Apache-2.0"} classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: MIT License", + "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", @@ -22,7 +26,7 @@ classifiers = [ ] keywords = ["parser", "ast", "cedarscript", "code-editing", "refactoring", "code-analysis", "sql-like", "ai-assisted-development"] dependencies = [ - "cedarscript-grammar>=0.0.9", + "cedarscript-grammar>=0.7.0", ] requires-python = ">=3.8" @@ -40,15 +44,34 @@ dev = [ "flake8>=4.0", ] -[tool.setuptools.dynamic] -version = {attr = "cedarscript_ast_parser.__version__"} - [tool.setuptools] package-dir = {"" = "src"} -py-modules = ["cedarscript_ast_parser"] [tool.setuptools.packages.find] where = ["src"] -include = ["cedarscript_ast_parser*"] +include = ["version", "cedarscript_ast_parser*"] exclude = ["cedarscript_ast_parser.tests*"] namespaces = false + +[tool.setuptools_scm] +# To override version: +# >>> SETUPTOOLS_SCM_PRETEND_VERSION=0.0.2 python -m build +# To dry-run and see version: +# >>> python -m setuptools_scm +write_to = "src/version/_version.py" +# Append .post{number of commits} to your version if there are commits after the last tag. +version_scheme = "post-release" + +[tool.black] +line-length = 100 +target-version = ['py39'] + +[tool.isort] +profile = "black" +line_length = 100 + +[tool.mypy] +python_version = "3.8" +strict = true +warn_return_any = true +warn_unused_configs = true diff --git a/scripts/check-version.sh b/scripts/check-version.sh new file mode 100755 index 0000000..a6a4293 --- /dev/null +++ b/scripts/check-version.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env sh +version=$(python -m setuptools_scm) +# Check if the version is pure (i.e., it doesn't contain a '+') +echo "$version" | grep -q "+" && { + echo "Error: Version '$version' is not pure. Aborting dist." + exit 1 +} +exit 0 diff --git a/src/cedarscript_ast_parser/__init__.py b/src/cedarscript_ast_parser/__init__.py index 58d14bc..9bb62ec 100644 --- a/src/cedarscript_ast_parser/__init__.py +++ b/src/cedarscript_ast_parser/__init__.py @@ -1,19 +1,20 @@ -__version__ = "0.2.0" +from version import __version__ from .cedarscript_ast_parser import ( CEDARScriptASTParser, ParseError, Command, CreateCommand, RmFileCommand, MvFileCommand, UpdateCommand, - SelectCommand, IdentifierFromFile, SingleFileClause, Segment, Marker, BodyOrWhole, MarkerType, RelativeMarker, RelativePositionType, - MoveClause, DeleteClause, InsertClause, ReplaceClause, EditingAction, Region, BodyOrWhole, WhereClause, RegionClause + SelectCommand, IdentifierFromFile, SingleFileClause, Segment, Marker, BodyOrWhole, MarkerType, RelativeMarker, + RelativePositionType, MoveClause, DeleteClause, InsertClause, ReplaceClause, EditingAction, Region, + WhereClause, RegionClause, EdScript, CaseStatement, CaseWhen, CaseAction, LoopControl ) -__all__ = ( - CEDARScriptASTParser, ParseError, Command, - CreateCommand, RmFileCommand, MvFileCommand, UpdateCommand, - SelectCommand, IdentifierFromFile, SingleFileClause, Segment, Marker, BodyOrWhole, MarkerType, RelativeMarker, RelativePositionType, - MoveClause, DeleteClause, InsertClause, ReplaceClause, EditingAction, Region, BodyOrWhole, WhereClause, RegionClause -) - - - +__all__ = [ + "__version__", + "CEDARScriptASTParser", "ParseError", "Command", + "CreateCommand", "RmFileCommand", "MvFileCommand", "UpdateCommand", + "SelectCommand", "IdentifierFromFile", "SingleFileClause", "Segment", "Marker", "BodyOrWhole", "MarkerType", + "RelativeMarker", "RelativePositionType", "MoveClause", "DeleteClause", "InsertClause", "ReplaceClause", + "EditingAction", "Region", "WhereClause", "RegionClause", "EdScript", "CaseStatement", "CaseWhen", "CaseAction", + "LoopControl" +] diff --git a/src/cedarscript_ast_parser/cedarscript_ast_parser.py b/src/cedarscript_ast_parser/cedarscript_ast_parser.py index a78a3b5..599972a 100644 --- a/src/cedarscript_ast_parser/cedarscript_ast_parser.py +++ b/src/cedarscript_ast_parser/cedarscript_ast_parser.py @@ -1,23 +1,29 @@ -from enum import StrEnum, auto -from typing import TypeAlias, NamedTuple, Union from collections.abc import Sequence - -from tree_sitter import Parser -import cedarscript_grammar from dataclasses import dataclass +from enum import StrEnum, auto +from typing import TypeAlias, NamedTuple, Union, Optional +import re +import cedarscript_grammar +from tree_sitter import Parser + class ParseError(NamedTuple): - command_ordinal: int + ordinal: int message: str line: int column: int suggestion: str def __str__(self): + line_msg = f'; LINE #{self.line}' if self.line else '' + col_msg = f'; COLUMN #{self.column}' if self.column else '' + cmd_or_block = 'BLOCK' if self.line else 'COMMAND' + error_type = 'Source Parsing' if self.line else 'CST Parsing' + suggestion_msg = f'{self.suggestion} ' if self.suggestion else '' return ( - f"COMMAND #{self.command_ordinal}{f'; LINE #{self.line}' if self.line else ''}{f'; COLUMN #{self.column}' if self.column else ''}" - f"PARSING (no commands were applied at all){self.message}" - f"{f"{self.suggestion} " if self.suggestion else ""}" + f"{cmd_or_block} #{self.ordinal}{line_msg}{col_msg}" + f"{error_type} (no commands were applied at all){self.message}" + f"{suggestion_msg}" "(NEVER apologize; just take a deep breath, re-read grammar rules (enclosed by tags) " "and fix you CEDARScript syntax)" ) @@ -31,28 +37,62 @@ class BodyOrWhole(StrEnum): WHOLE = auto() -MarkerType = StrEnum('MarkerType', 'LINE VARIABLE FUNCTION CLASS') -RelativePositionType = StrEnum('RelativePositionType', 'AT BEFORE AFTER INSIDE_TOP INSIDE_BOTTOM') +MarkerType = StrEnum('MarkerType', 'LINE VARIABLE FUNCTION METHOD CLASS') +RelativePositionType = StrEnum('RelativePositionType', 'AT BEFORE AFTER INTO_TOP INTO_BOTTOM') class MarkerCompatible: def as_marker(self) -> 'Marker': pass + @dataclass class Marker(MarkerCompatible): + """ + A marker can be one of: + - LINE with string/number value + - LINE REGEX with regex pattern + - LINE PREFIX with prefix string + - LINE SUFFIX with suffix string + - VARIABLE with name + - FUNCTION with name + - CLASS with name + See also: Marker.to_search_range + """ type: MarkerType - value: str + value: str | int | None offset: int | None = None + # See `line_base` + marker_subtype: str | None = None + @property def as_marker(self) -> 'Marker': return self + def with_qualifier(self, qualifier: RelativePositionType): + return RelativeMarker( + qualifier=qualifier, + type=self.type, + value=self.value, + offset=self.offset, + marker_subtype = self.marker_subtype + ) if qualifier else self + def __str__(self): - result = f"{self.type.value} '{self.value}'" + result = self.type.value + match self.marker_subtype: + case 'string' | None: + pass + case 'empty': + result = 'empty line' + case _: + result += f' {self.marker_subtype}' + + if self.marker_subtype != 'empty': + result += f" '{str(self.value).strip()}'" if self.offset is not None: - result += f" at offset {self.offset}" + result += f" ^{self.offset}" return result @@ -69,7 +109,7 @@ def __str__(self): case RelativePositionType.AT: pass case _: - result = f'{result} ({self.qualifier.replace('_', ' ')})' + result = f'{result} ({str(self.qualifier).replace("_", " ")})' return result @@ -79,7 +119,7 @@ class Segment: end: RelativeMarker def __str__(self): - return f"segment from {self.start} to {self.end}" + return f"segment from [{self.start}] to [{self.end}]" MarkerOrSegment: TypeAlias = Marker | Segment @@ -102,20 +142,24 @@ class SingleFileClause: @dataclass class IdentifierFromFile(SingleFileClause, MarkerCompatible): - where_clause: WhereClause identifier_type: MarkerType # VARIABLE, FUNCTION, CLASS (but not LINE) + name: str + where_clause: WhereClause offset: int | None = None @property def as_marker(self) -> Marker: # TODO Handle different values for field and operator in where_clause - return Marker(self.identifier_type, self.where_clause.value, self.offset) + return Marker(self.identifier_type, self.name or self.where_clause.value, self.offset) def __str__(self): - result = f"{self.identifier_type.lower()} ({self.where_clause})" + wc = self.where_clause or '' + if wc: + wc = f' ({wc})' + result = f"{str(self.identifier_type).lower()} {self.name}{wc}" if self.offset is not None: result += f" at offset {self.offset}" - return f"{result} from file {self.file_path}" + return f"{result} [{str(self.file_path).split('/')[-1]}]" FileOrIdentifierWithin: TypeAlias = SingleFileClause | IdentifierFromFile @@ -161,7 +205,6 @@ class MoveClause(DeleteClause, InsertClause): # - # @dataclass @@ -188,6 +231,7 @@ def files_to_change(self) -> tuple[str, ...]: class CreateCommand(FileCommand): content: str + @dataclass class RmFileCommand(FileCommand): pass @@ -204,11 +248,55 @@ def files_to_change(self) -> tuple[str, ...]: # +@dataclass +class LoopControl(StrEnum): + BREAK = 'BREAK' + CONTINUE = 'CONTINUE' + + +@dataclass +class CaseWhen: + """Represents a WHEN condition in a CASE statement""" + empty: bool = False + indent_level: int | None = None + line_number: int | None = None + line_matcher: str | None = None + regex: str | None = None + prefix: str | None = None + suffix: str | None = None + + +@dataclass +class CaseAction: + """Represents a THEN action in a CASE statement""" + loop_control: LoopControl | None = None + remove: bool = False + sub_pattern: str | None = None # For SUB command pattern + sub_repl: str | None = None # For SUB command replacement + indent: int | None = None + content: Optional[str | tuple[Region, int | None]] = None + +class LineFilter: + pass + +@dataclass +class CaseStatement(LineFilter): + """Represents a CASE statement with when-then pairs and optional else""" + cases: list[tuple[CaseWhen, CaseAction]] + else_action: Optional[CaseAction] = None + + +@dataclass +class EdScript(LineFilter): + """Represents an ED script content""" + script: str + + @dataclass class UpdateCommand(Command): target: FileOrIdentifierWithin action: EditingAction - content: str | tuple[Region, int | None] | None = None + content: str | tuple[Region, int | None] | EdScript | CaseStatement | None = None @property def files_to_change(self) -> tuple[str, ...]: @@ -241,7 +329,7 @@ def _generate_suggestion(error_node, code_text) -> str: return "Please check the syntax near the error." parent_type = parent.type - if parent_type == 'content_clause': + if parent_type == 'content_literal': return "Ensure the content block is properly enclosed with matching quotes (''' or \"\")." if parent_type == 'update_command': return "An action clause ('REPLACE', 'INSERT', 'DELETE') is expected in the 'UPDATE' command." @@ -255,8 +343,18 @@ class _CEDARScriptASTParserBase: def __init__(self): """Load the CEDARScript language, and initialize the parser. """ - self.parser = Parser() - self.parser.set_language(cedarscript_grammar.language()) + from importlib.metadata import version + from packaging import version as v + + package_version = version('tree_sitter') + parsed_version = v.parse(package_version) + + match parsed_version: + case x if x <= v.parse('0.21.3'): + self.parser = Parser() + self.parser.set_language(cedarscript_grammar.language()) + case _: + self.parser = Parser(cedarscript_grammar.language()) class CEDARScriptASTParser(_CEDARScriptASTParserBase): @@ -268,9 +366,7 @@ def parse_script(self, code_text: str) -> tuple[Sequence[Command], Sequence[Pars """ command_ordinal = 1 try: - # Parse the code text - tree = self.parser.parse(bytes(code_text, 'utf8')) - root_node = tree.root_node + root_node = self.parser.parse(bytes(code_text, 'utf8')).root_node errors = self._collect_parse_errors(root_node, code_text, command_ordinal) if errors: @@ -282,7 +378,7 @@ def parse_script(self, code_text: str) -> tuple[Sequence[Command], Sequence[Pars for child in root_node.children: node_type = child.type.casefold() if node_type == 'comment': - print("(COMMENT) " + self.parse_string(child).removeprefix("--").strip()) + print("(COMMENT) " + self.parse_string(child).removeprefix("--").removeprefix("/*").strip()) if not node_type.endswith('_command'): continue commands.append(self.parse_command(child)) @@ -293,7 +389,7 @@ def parse_script(self, code_text: str) -> tuple[Sequence[Command], Sequence[Pars # Handle any unexpected exceptions during parsing error_message = str(e) error = ParseError( - command_ordinal=command_ordinal, + ordinal=command_ordinal, message=error_message, line=0, column=0, @@ -321,7 +417,7 @@ def _collect_parse_errors(self, node, code_text, command_ordinal: int) -> list[P suggestion = _generate_suggestion(node, code_text) error = ParseError( - command_ordinal=command_ordinal, + ordinal=command_ordinal, message=message, line=line, column=column, @@ -396,22 +492,28 @@ def parse_update_target(self, node): raise ValueError(f"[parse_update_target] Invalid target: {invalid}") def parse_identifier_from_file(self, node): - identifier_type = MarkerType(node.children[0].type.casefold()) + identifier_matcher = self.find_first_by_type(node.named_children, 'identifier_matcher') + identifier_type = MarkerType(identifier_matcher.children[0].type.casefold()) + name = self.parse_string(identifier_matcher.named_children[0]) + offset_clause = self.find_first_by_type(identifier_matcher.named_children, 'offset_clause') file_clause = self.find_first_by_type(node.named_children, 'singlefile_clause') where_clause = self.find_first_by_type(node.named_children, 'where_clause') - offset_clause = self.find_first_by_type(node.named_children, 'offset_clause') - if not file_clause or not where_clause: + if not file_clause or not name: raise ValueError("Invalid identifier_from_file clause") file_path = self.parse_singlefile_clause(file_clause).file_path + offset = self.find_primitive(offset_clause) if offset_clause else None where = self.parse_where_clause(where_clause) - offset = self.parse_offset_clause(offset_clause) if offset_clause else None - return IdentifierFromFile(identifier_type=identifier_type, file_path=file_path, - where_clause=where, offset=offset) + return IdentifierFromFile(file_path=file_path, + identifier_type=identifier_type, name=name, offset=offset, + where_clause=where + ) def parse_where_clause(self, node): + if not node: + return None condition = self.find_first_by_type(node.children, 'condition') if not condition: raise ValueError("No condition found in where clause") @@ -423,8 +525,10 @@ def parse_where_clause(self, node): return WhereClause(field=field, operator=operator, value=value) def parse_update_action(self, node): - child_types = ['update_delete_region_clause', 'update_delete_mos_clause', 'update_move_region_clause', 'update_move_mos_clause', - 'insert_clause', 'replace_mos_clause', 'replace_region_clause'] + child_types = [ + 'update_delete_region_clause', 'update_delete_mos_clause', 'update_move_region_clause', + 'update_move_mos_clause', 'insert_clause', 'replace_mos_clause', 'replace_region_clause' + ] action_node = self.find_first_by_type(node.named_children, child_types) if action_node is None: raise ValueError("No valid action found in update command") @@ -481,7 +585,8 @@ def parse_region(self, node) -> Region: node = node.named_children[0] main_type = node.child(0).type.casefold() match main_type: - case 'inside': + case 'into': + # INTO_TOP, INTO_BOTTOM main_type += '_' + node.child(2).type.casefold() qualifier = RelativePositionType(main_type) node = node.named_children[0] @@ -492,7 +597,7 @@ def parse_region(self, node) -> Region: node = node.named_children[0] match node.type.casefold(): - case 'marker' | 'linemarker' | 'identifiermarker': + case 'marker' | 'line_matcher' | 'identifier_matcher': result = self.parse_marker(node) case 'segment': result = self.parse_segment(node) @@ -500,18 +605,38 @@ def parse_region(self, node) -> Region: result = BodyOrWhole(bow.lower()) case _: raise ValueError(f"Unexpected node type: {node.type}") - if qualifier: - result = RelativeMarker(qualifier=qualifier, type=result.type, value=result.value, offset=result.offset) - return result + return result.with_qualifier(qualifier) if qualifier else result def parse_marker(self, node) -> Marker: - # TODO Fix: handle line marker as well + # Handle marker inside marker_or_segment if node.type.casefold() == 'marker': node = node.named_children[0] - marker_type = node.children[0].type # LINE, VARIABLE, FUNCTION, or CLASS - value = self.parse_string(self.find_first_by_type(node.named_children, 'string')) - offset = self.parse_offset_clause(self.find_first_by_type(node.named_children, 'offset_clause')) - return Marker(type=MarkerType(marker_type.casefold()), value=value, offset=offset) + + marker_type = node.named_children[0].type + # LINE, VARIABLE, FUNCTION, METHOD or CLASS + marker_subtype = None + value = None + + # Handle the different marker types + if marker_type == 'line_base': + marker_type = 'line' + # subtype: None, number, EMPTY, REGEX, PREFIX, SUFFIX, INDENT-LEVEL + line_base_node = node.named_children[0] # line_base + marker_subtype = [n.type.casefold() for n in line_base_node.children if n.type.casefold() != 'line'][0] + value = self.find_primitive(line_base_node) + + else: # identifier_matcher + marker_type = node.children[0].type.casefold() + value = self.find_primitive(node) + + offset = self.find_first_by_type(node.named_children, 'offset_clause') + offset = self.find_primitive(offset) + return Marker( + type=MarkerType(marker_type.casefold()), + marker_subtype=marker_subtype, + value=value, + offset=offset + ) def parse_segment(self, node) -> Segment: relpos_start = self.find_first_by_type(node.named_children, 'relpos_segment_start').children[1] @@ -520,29 +645,120 @@ def parse_segment(self, node) -> Segment: end: RelativeMarker = self.parse_region(relpos_end) return Segment(start=start, end=end) - def parse_offset_clause(self, node): - if node is None: - return None - return int(self.find_first_by_type(node.children, 'number').text) - - def parse_relative_indentation(self, node) -> int: + def parse_relative_indentation(self, node) -> int | None: node = self.find_first_by_type(node.named_children, 'relative_indentation') - if node is None: - return None - return int(self.find_first_by_type(node.named_children, 'number').text) + return self.find_primitive(node) - def parse_content(self, node) -> str | tuple[Region, int | None]: - content = self.find_first_by_type(node.named_children, ['content_clause', 'content_from_segment']) + def parse_content(self, node) -> str | tuple[Region, int | None] | None: + content = self.find_first_by_type(node.named_children, [ + 'content_literal', 'content_from_segment', 'line_filter' + ]) if not content: return None match content.type: - case 'content_clause': - return self.parse_content_clause(content) # str + case 'content_literal': + return self.parse_content_literal(content) # str case 'content_from_segment': - return self.parse_content_from_segment_clause(content) # tuple[Region, int] + return self.parse_content_from_segment_clause(content) # tuple[Region, int] + case 'line_filter': + return self.parse_line_filter(content) case _: raise ValueError(f"Invalid content type: {content.type}") + def parse_line_filter(self, node) -> LineFilter: + node = node.named_children[0] + match node.type: + case 'ed_stmt': + return self.parse_ed_stmt(node) # EdScript + case 'case_stmt': + return self.parse_case_stmt(node) # CaseStatement + + + def parse_ed_stmt(self, node) -> EdScript: + """Parse an ED script statement""" + ed_script = self.find_first_by_type(node.children, 'string') + if ed_script is None: + raise ValueError("No ED script found in ed_stmt") + return EdScript(script=self.parse_string(ed_script)) + + def parse_case_stmt(self, node) -> CaseStatement: + """Parse a CASE statement""" + cases = [] + + # Parse all WHEN-THEN pairs + current_when = None + for child in node.children: + match child.type: + case 'line_base': + current_when = self.parse_case_when(child) + case 'case_action' if current_when is not None: + action = self.parse_case_action(child) + cases.append((current_when, action)) + current_when = None + + # Parse optional ELSE clause + else_action = None + else_node = self.find_first_by_field_name(node, 'else') + if else_node: + else_action = self.parse_case_action(else_node) + + return CaseStatement(cases=cases, else_action=else_action) + + def parse_case_when(self, node) -> CaseWhen: + """Parse a WHEN clause in a CASE statement""" + when = CaseWhen() + + if self.find_first_by_field_name(node, 'empty'): + when.empty = True + + elif indent := self.find_first_by_field_name(node, 'indent_level'): + when.indent_level = int(indent.text.decode('utf8')) + + elif line_num := self.find_first_by_field_name(node, 'line_number'): + when.line_number = int(line_num.text.decode('utf8')) + + elif line_str := self.find_first_by_field_name(node, 'line_matcher'): + when.line_matcher = self.parse_string(line_str) + + elif regex := self.find_first_by_field_name(node, 'regex'): + when.regex = re.compile(self.parse_string(regex)) + + elif prefix := self.find_first_by_field_name(node, 'prefix'): + when.prefix = self.parse_string(prefix) + + elif suffix := self.find_first_by_field_name(node, 'suffix'): + when.suffix = self.parse_string(suffix) + + return when + + def parse_case_action(self, node) -> CaseAction: + """Parse a THEN clause in a CASE statement""" + action = CaseAction() + + # Parse loop control if present + loop_control = self.find_first_by_type(node.children, 'loop_control') + if loop_control: + if self.find_first_by_type(loop_control.children, 'loop_break'): + action.loop_control = LoopControl.BREAK + elif self.find_first_by_type(loop_control.children, 'loop_continue'): + action.loop_control = LoopControl.CONTINUE + + # Parse other action types + if self.find_first_by_field_name(node, 'remove'): + action.remove = True + elif pattern := self.find_first_by_field_name(node, 'pattern'): + action.sub_pattern = re.compile(self.parse_string(pattern)) + if repl := self.find_first_by_field_name(node, 'repl'): + action.sub_repl = self.parse_string(repl) + elif indent := self.find_first_by_field_name(node, 'indent'): + action.indent = int(indent.text) + else: + # Check for content replacement + content = self.find_first_by_type(node.children, ['content_literal', 'content_from_segment']) + if content: + action.content = self.parse_content(content) + + return action def parse_singlefile_clause(self, node): if node is None or node.type != 'singlefile_clause': @@ -552,11 +768,11 @@ def parse_singlefile_clause(self, node): raise ValueError("No file_path found in singlefile_clause") return SingleFileClause(file_path=self.parse_string(path_node)) - def parse_content_clause(self, node) -> str: + def parse_content_literal(self, node) -> str: child_type = ['string', 'relative_indent_block', 'multiline_string'] content_node = self.find_first_by_type(node.children, child_type) if content_node is None: - raise ValueError("No content found in content_clause") + raise ValueError("No content found in content_literal") if content_node.type == 'string': return self.parse_string(content_node) elif content_node.type == 'relative_indent_block': @@ -581,22 +797,45 @@ def parse_to_value_clause(self, node): raise ValueError("No value found in to_value_clause") return self.parse_string(value_node) - def parse_string(self, node): + def find_primitive(self, node): + if node is None: + return None + node = self.find_first_by_type(node.named_children, ['string', 'number']) + if node is None: + return None + match node.type.casefold(): + case 'string': + return self.parse_string(node) + case 'number': + return int(node.text) + case _: + raise ValueError(f"[find_primitive] Invalid primitive: {node.type} ({node.text})") + + @staticmethod + def parse_string(node): match node.type.casefold(): case 'string': node = node.named_children[0] text = node.text.decode('utf8') match node.type.casefold(): case 'raw_string': - text = text.strip('"\'') + match text: + case x if x.startswith("r'''") or x.startswith('r"""'): + text = text[4:-3] + case x if x.startswith("r'") or x.startswith('r"'): + text = text[2:-1] + case _: + raise ValueError(f"Invalid raw string: `{text}`") case 'single_quoted_string': - text = text.replace("\\'", "'").replace('\\"', '"').strip('"\'') + text = text[1:-1] # Remove surrounding quotes + text = text.replace(r"\'", "'").replace(r'\"', '"').replace(r"\t", '\t').replace("\\\\", "\\") case 'multi_line_string': - text = text.removeprefix("'''").removeprefix('"""').removesuffix("'''").removesuffix('"""') + text = text[3:-3] return text - def parse_multiline_string(self, node): + @staticmethod + def parse_multiline_string(node): return node.text.decode('utf8').strip("'''").strip('"""') def parse_relative_indent_block(self, node) -> str: @@ -610,7 +849,8 @@ def parse_relative_indent_block(self, node) -> str: lines.append(f"{' ' * (4 * indent)}{content.text}") return '\n'.join(lines) - def find_first_by_type(self, nodes: Sequence[any], child_type): + @staticmethod + def find_first_by_type(nodes: Sequence[any], child_type): if isinstance(child_type, list): for child in nodes: if child.type in child_type: @@ -621,7 +861,8 @@ def find_first_by_type(self, nodes: Sequence[any], child_type): return child return None - def find_first_by_field_name(self, node: any, field_names): + @staticmethod + def find_first_by_field_name(node: any, field_names): if not isinstance(field_names, list): return node.child_by_field_name(field_names) diff --git a/src/version/__init__.py b/src/version/__init__.py new file mode 100644 index 0000000..32495d2 --- /dev/null +++ b/src/version/__init__.py @@ -0,0 +1,3 @@ +from ._version import version + +__version__ = version diff --git a/tests/test_parser.py b/tests/test_parser.py new file mode 100644 index 0000000..7eed9b0 --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,6 @@ +from cedarscript_ast_parser import CEDARScriptASTParser + + +def test_can_instantiate_parser(): + """Test that we can create a CEDARScriptASTParser instance""" + CEDARScriptASTParser() pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy