Skip to content
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
9 changes: 9 additions & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ reStructuredPython Changelog
Major release 0
---------------

.. raw:: html

<details>
<summary>0.8.0</summary>
<ul>
<li>Addded multiline comments similar to JavaScript using /* and */</li>
</ul>
</details>

.. raw:: html

<details>
Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
copyright = '2025, Rihaan Meher'
author = 'Rihaan Meher'

release = '0.7.0'
release = '0.8.0'
html_favicon = "_static/icon.png"

# -- General configuration ---------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ Features
* **JavaScript-like Syntax:** Enjoy a syntax reminiscent of JavaScript, making it familiar and intuitive for developers with a JavaScript background.
* **Header Files** In reStructuredPython, enjoy having the ability to create header files, similar to C++ for easier, and more organized development. View the `syntax <https://restructuredpython.readthedocs.io/en/latest/reference/Syntax_Guide.html>`_ guide for more details.
* **Seamless Compilation:** reStructuredPython code compiles directly into Python, ensuring compatibility with existing Python libraries and frameworks.
* **Enhanced Readability:** The syntax enhancements aim to improve code readability and reduce verbosity.
* **Enhanced Readability:** The syntax enhancements which include multiline comments aim to improve code readability and reduce verbosity.

Documentation
-------------

* **Syntax Guide:** Learn about the specific syntax changes and how to write reStructuredPython code effectively.
* **Installation Guide:** Step-by-step instructions on setting up reStructuredPython in your development environment.
* **API Reference:** Comprehensive details on the available functions, classes, and modules within reStructuredPython.
* **Syntax Reference:** Comprehensive details on the available functions, classes, and modules within reStructuredPython.
* **Examples:** Explore practical examples demonstrating the use of reStructuredPython in various scenarios.

Community and Support
Expand Down
4 changes: 0 additions & 4 deletions docs/source/reference/Built_in_Functions.rst

This file was deleted.

30 changes: 27 additions & 3 deletions docs/source/reference/Syntax_Guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Syntax Guide

reStructuredPython introduces a syntax that combines Python's functionality with JavaScript-like conventions. Below are some key syntax elements:

1. **Control Loop Syntax**
1. **Control Loop Syntax** Latest in 0.6.0

Control loops and class/function definitions use curly brackets instead of ":" like in regular Python

Expand Down Expand Up @@ -31,7 +31,7 @@ reStructuredPython introduces a syntax that combines Python's functionality with
return param
}

2. **Header Files**
2. **Header Files** Latest in 0.5.0

reStructuredPython offers a new and exciting feature not present in regular python. The addition of header files, written in a ``.cdata`` file extension are regular ``.repy`` files written in reStructuredPython that are compiled and automatically included in the final compilation of a ``.repy`` file.

Expand Down Expand Up @@ -60,7 +60,7 @@ reStructuredPython introduces a syntax that combines Python's functionality with

afunctiondefinedintheheaderfile()

3. **Function Chaining**
3. **Function Chaining** Latest in 0.7.0

In reStructuredPython 0.7.0, a new feature called function chaning was created. In 0.7.0, you can chain functions using the ``|>`` operartor to increase readablility and efficency

Expand Down Expand Up @@ -95,6 +95,30 @@ reStructuredPython introduces a syntax that combines Python's functionality with

This is best used in conjunction with header files.

4. **Multiline Comments** Latest in 0.8.0

In reStructuredPython 0.8.0, we added multiline comments with an near identical syntax to JavaScript to make large comments in programs easier to write, a feature that python doesn't have.

Example:

.. code-block:: repy

/* This is a multiline comment
that spans multiple lines */
if True:
print("Hello World")
This compiles into:

.. code-block:: repy

# This is a multiline comment
# that spans multiple lines
if True:
print("Hello World")

This should be pretty easy to grasp for a developer who knows the syntax of the C and JavaScript familes to use.
This feature is also useful for including documentation in files when a docstring is too long or not an option.




Expand Down
1 change: 0 additions & 1 deletion docs/source/reference/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,4 @@ The reference section provides detailed information about the built-in functions
.. toctree::
:maxdepth: 1

Built_in_Functions
Syntax_Guide
4 changes: 4 additions & 0 deletions docs/source/tutorials/compiled_programs/comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This is a multiline comment
# that spans multiple lines
if True:
print("Hello World")
4 changes: 4 additions & 0 deletions docs/source/tutorials/programs/comments.repy
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* This is a multiline comment
that spans multiple lines */
if True:
print("Hello World")
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "restructuredpython"
version = "0.7.0"
version = "0.8.0"
description = "A superset of Python with js-like syntax"
authors = [{name = "Rihaan Meher", email = "meherrihaan@gmail.com"}]
license = {text = "MIT"}
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# reStructuredPython 0.7.0
# reStructuredPython 0.8.0

The all in one, new python.
reStructuredPython aka 'rePython' is a superset of python with many new features, such as header files, similar to C and C++, Optional Javascript-like syntax with curly brackets {} around control loops, function chanining and more. All the features can be found in the syntax/feature guide of out documentation https://restructuredpython.readthedocs.io/en/latest/reference/Syntax_Guide.html
Expand Down
2 changes: 1 addition & 1 deletion restructuredpython.egg-info/PKG-INFO
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Metadata-Version: 2.2
Name: restructuredpython
Version: 0.7.0
Version: 0.8.0
Summary: A superset of Python with js-like syntax
Author-email: Rihaan Meher <meherrihaan@gmail.com>
License: MIT
Expand Down
121 changes: 63 additions & 58 deletions restructuredpython/restructuredpython.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import warnings
from pathlib import Path

# Define token specifications
token_specification = [
('COMMENT', r'/\*.*?\*/'), # Multiline comment pattern
('IF', r'if'),
('FOR', r'for'),
('WHILE', r'while'),
Expand All @@ -32,27 +32,35 @@
]

token_regex = '|'.join(
f'(?P<{
pair[0]}>{
pair[1]})' for pair in token_specification)
f'(?P<{pair[0]}>{pair[1]})' for pair in token_specification)


def tokenize(code):
"""Tokenizes the rePython source code."""
"""Tokenizes the rePython source code and handles multiline comments."""
inside_multiline_comment = False
for mo in re.finditer(token_regex, code):
kind = mo.lastgroup
value = mo.group()

if kind == 'SKIP':
continue
continue # Skip over whitespace and newlines

elif kind == 'COMMENT':
# Handle multiline comments, converting them to Python-style comments
if value.startswith('/*') and value.endswith('*/'):
# This is a single multiline comment
comment_lines = value[2:-2].splitlines() # Remove /* and */
for line in comment_lines:
yield 'COMMENT', f"# {line.strip()}"
continue # Skip the rest of the processing for this comment

elif kind == 'MISMATCH':
warnings.warn(
f'Unexpected character {
value!r}. Continuing with compilation')
warnings.warn(f'Unexpected character {value!r}. Continuing with compilation')
yield kind, value

else:
yield kind, value


def check_syntax(input_lines):
for i in range(len(input_lines)):
line = input_lines[i].strip()
Expand Down Expand Up @@ -81,7 +89,6 @@ def check_syntax(input_lines):

def parse_repython(code):
"""Parses the rePython code and converts it to valid Python code."""

def chain_pipeline(code):
parts = [part.strip() for part in code.split('|>')]
if len(parts) > 1:
Expand Down Expand Up @@ -113,46 +120,58 @@ def nest(parts):

check_syntax(lines)

inside_comment_block = False

for line in lines:
processed_line = chain_pipeline(line)
# Handle statements that begin with a keyword and have an opening brace
if re.match(
r'^\s*(if|for|while|def|try|elif|else|except|class|match|with|case)\s.*\{',
processed_line):
# Replace the { with a colon (:) and track the opening brace
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True
# Handle the case where we encounter a closing brace
elif re.match(r'^\s*\}', processed_line) and inside_block:
brace_stack.pop() # Pop the opening brace from the stack
# Check if we still have open blocks
inside_block = len(brace_stack) > 0
elif re.match(r'^\s*match\(', processed_line):
# Specifically handle the match statement to remove { and add :
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True
elif re.match(r'^\s*case', processed_line):
# Handle case blocks to remove { and add :
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True

# Handling multiline comments properly
if inside_comment_block:
if processed_line.endswith("*/"):
# End of multiline comment block
modified_code.append(f"# {processed_line[:-2].strip()}") # Remove the ending '*/'
inside_comment_block = False
else:
# Continuation of the multiline comment
modified_code.append(f"# {processed_line.strip()}")
elif processed_line.startswith("/*") and processed_line.endswith("*/"):
# Single-line comment
modified_code.append(f"# {processed_line[2:-2].strip()}") # Remove the '/*' and '*/'
elif processed_line.startswith("/*"):
# Beginning of a multiline comment
modified_code.append(f"# {processed_line[2:].strip()}") # Remove the starting '/*'
inside_comment_block = True
elif processed_line.endswith("*/"):
# Ending of a multiline comment
modified_code.append(f"# {processed_line[:-2].strip()}") # Remove the ending '*/'
else:
modified_code.append(processed_line)
# Regular code lines (not in a comment)
if re.match(
r'^\s*(if|for|while|def|try|elif|else|except|class|match|with|case)\s.*\{',
processed_line):
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True
# Handle the case where we encounter a closing brace
elif re.match(r'^\s*\}', processed_line) and inside_block:
brace_stack.pop()
inside_block = len(brace_stack) > 0
elif re.match(r'^\s*match\(', processed_line):
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True
elif re.match(r'^\s*case', processed_line):
modified_code.append(processed_line.split('{')[0] + ':')
brace_stack.append('{')
inside_block = True
else:
modified_code.append(processed_line)

return '\n'.join(modified_code)


def compile_header_file(header_filename):
"""Compiles a .cdata file and returns the corresponding Python code."""

# Make sure the file exists
header_filename = Path(header_filename).resolve()
header_filename = header_filename.as_posix()
header_filename = Path(header_filename).resolve()
print(f"Resolved header file path: {header_filename}")

if not header_filename.exists():
raise FileNotFoundError(f"Header file {header_filename} not found.")
try:
Expand All @@ -170,25 +189,14 @@ def compile_header_file(header_filename):
def process_includes(code, input_file):
"""Processes #include directives and compiles included .d.repy files."""
include_pattern = r'\s*include\s+[\'"]([^\'"]+)[\'"]'

includes = re.findall(include_pattern, code)
if includes:
print(f"All include files: {includes}")
else:
print("No include found.")

header_code = ""
for include in includes:
print(f"Processing include: {include}")

if not os.path.isabs(include):
include = os.path.join(
os.path.dirname(
os.path.abspath(input_file)),
include)
include = os.path.join(os.path.dirname(os.path.abspath(input_file)), include)

if os.path.exists(include):
print(f"Compiling included file: {include}")
header_code += compile_header_file(include) + "\n"
else:
print(f"Error: Included file '{include}' not found.")
Expand All @@ -198,8 +206,6 @@ def process_includes(code, input_file):

return header_code, code_without_includes

# Example use case


def main():
parser = argparse.ArgumentParser(description="Compile REPY files.")
Expand All @@ -215,8 +221,7 @@ def main():
with open(input_file, 'r') as f:
source_code = f.read()

header_code, code_without_includes = process_includes(
source_code, input_file)
header_code, code_without_includes = process_includes(source_code, input_file)

python_code = parse_repython(code_without_includes)

Expand Down
4 changes: 4 additions & 0 deletions tests/.py/comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This is a multiline comment
# that spans multiple lines
if True:
print("Hello World")
4 changes: 4 additions & 0 deletions tests/.repy/comments.repy
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* This is a multiline comment
that spans multiple lines */
if True:
print("Hello World")