for (let line of lines) {
let trimmedLine = line.trim();
code
// Skip empty lines
if (trimmedLine.length === 0) {
outputLines.push('');
continue;
}
// Handle closing brace
if (trimmedLine.startsWith('}')) {
currentIndentLevel = Math.max(currentIndentLevel - 1, 0);
trimmedLine = trimmedLine.substring(1).trim();
// If there's code after }, process it
if (trimmedLine.length > 0) {
// Fall through to process the remaining code
} else {
// No more code on this line
outputLines.push('');
continue;
}
}
// Handle opening brace
let hasOpeningBrace = false;
if (trimmedLine.endsWith('{')) {
hasOpeningBrace = true;
trimmedLine = trimmedLine.substring(0, trimmedLine.length - 1).trim() + ':';
}
// Apply indentation
const indent = indentUnit.repeat(currentIndentLevel);
outputLines.push(indent + trimmedLine);
// If there was an opening brace, increase the indent
if (hasOpeningBrace) {
currentIndentLevel += 1;
}
Assistant
}
return outputLines.join('\n');
}
/**
Ensures that the directory exists. If not, creates it recursively.
@param dirPath The directory path to ensure.
*/
async function ensureDirectory(dirPath: string) {
try {
await access(dirPath, fs.constants.F_OK);
// Directory exists
} catch {
// Directory does not exist, create it
await mkdir(dirPath, { recursive: true });
console.log(Created directory: ${dirPath});
}
}
/**
Processes a single .pi file and writes the translated .py file.
Processes files based on the provided configuration.
@param config The configuration object from piconfig.json.
*/
async function processConfig(config: PiConfig) {
// Iterate over each key in the config
for (const [sourceDir, targetDir] of Object.entries(config)) {
console.log(\nProcessing mapping: ${sourceDir} → ${targetDir});
code
// Ensure the target directory exists
await ensureDirectory(targetDir);
// Define the glob pattern to find all .pi files recursively in sourceDir
const pattern = `${sourceDir}/**/*.pi`;
console.log(`Using glob pattern: ${pattern}`);
const files = glob.sync(pattern, { nodir: true });
console.log(`Found ${files.length} .pi file(s) in ${sourceDir}`);
if (files.length === 0) {
console.warn(`No .pi files found in ${sourceDir} using pattern ${pattern}`);
}
for (const file of files) {
// Compute the relative path from the source directory
const relativePath = path.relative(sourceDir, file);
// Define the output file path in the target directory with .py extension
const outputFilePath = path.join(targetDir, relativePath).replace(/\.pi$/i, '.py');
await processFile(file, outputFilePath);
}
}
}
/**
Entry point of the script.
*/
async function main() {
console.log("Starting PI to PY compilation...");
// Check if configuration is empty
if (Object.keys(config).length === 0) {
console.warn('piconfig.json is empty. No mappings to process.');
return;
}
// Process files based on the configuration
await processConfig(config);
console.log("\nPI to PY compilation completed.");
}
main();
There's a case we need to handle for the dictionaries:
pi:
dic = {
"name": "John"
}
print(dic)
being compiled to:
dic =:
"name": "John"
print(dic)
Dictionaries, in general, shouldn't be touched, whether they're:
dic = { "name": "John" }
or:
dic = {
"name": "John"
}
or:
my_function({
"name": "John"
})
or:
my_function({ "Name": "John" })
To handle the scenario where you want to preserve dictionary literals and avoid altering them during the translation from .pi to .py, you'll need to refine the translatePiToPy function. The current implementation indiscriminately replaces curly braces {} with colons :, which mistakenly transforms dictionary syntax into invalid Python code.
Problem Overview
Consider the following .pi code:
pi
dic = {
"name": "John"
}
print(dic)
With the existing translatePiToPy function, this would incorrectly translate to:
python
dic =:
"name": "John"
print(dic)
This is invalid Python because the dictionary braces {} have been improperly replaced with a colon :.
Solution
To preserve dictionary literals while still translating code blocks correctly, we can differentiate between braces used for code blocks and those used for dictionaries or other expressions.
Here's how you can achieve this:
Identify Code Blocks: Typically, code blocks in languages that use curly braces (like C, Java, etc.) start with keywords such as if, for, while, def, class, etc. We'll use these keywords to determine whether a { is starting a new code block.
Preserve Dictionaries and Expressions: If a { does not follow one of the code block keywords, we'll assume it's part of an expression (like a dictionary) and leave it untouched.
Modified translatePiToPy Function
Below is the updated translatePiToPy function with comments explaining the changes:
typescript
/**
* Translates .pi content to Python syntax by replacing curly brackets with colons
* and managing indentation. Preserves dictionary literals by not altering braces
* that are part of expressions.
* @param content The content of the .pi file.
* @returns The translated Python code.
*/
function translatePiToPy(content: string): string {
const lines = content.split(/\r?\n/);
const outputLines: string[] = [];
const indentUnit = ' '; // 4 spaces
let currentIndentLevel = 0;
// List of keywords that typically start a code block
const codeBlockKeywords = [
'if', 'else', 'elif', 'for', 'while',
'def', 'class', 'try', 'except', 'finally',
'with', 'switch', 'case'
];
for (let line of lines) {
let trimmedLine = line.trim();
// Skip empty lines
if (trimmedLine.length === 0) {
outputLines.push('');
continue;
}
// Handle closing brace
if (trimmedLine.startsWith('}')) {
currentIndentLevel = Math.max(currentIndentLevel - 1, 0);
trimmedLine = trimmedLine.substring(1).trim();
// If there's code after }, process it
if (trimmedLine.length > 0) {
// Fall through to process the remaining code
} else {
// No more code on this line
outputLines.push('');
continue;
}
}
// Check if the line ends with '{'
let hasOpeningBrace = false;
if (trimmedLine.endsWith('{')) {
// Determine if this brace starts a code block
// Extract the part before the '{'
const beforeBrace = trimmedLine.slice(0, -1).trim();
// Check if the line starts with any of the code block keywords
const startsWithCodeBlock = codeBlockKeywords.some(keyword => {
// Use a regex to match the keyword at the start followed by space or '('
const regex = new RegExp(`^${keyword}(\\s|\\()`);
return regex.test(beforeBrace);
});
if (startsWithCodeBlock) {
hasOpeningBrace = true;
// Replace '{' with ':' to conform to Python syntax
trimmedLine = beforeBrace + ':';
} else {
// The brace is part of an expression (e.g., dictionary), leave it as is
// Do not alter the line; proceed without replacing '{'
}
}
// Apply indentation
const indent = indentUnit.repeat(currentIndentLevel);
outputLines.push(indent + trimmedLine);
// If there was an opening brace for a code block, increase the indent
if (hasOpeningBrace) {
currentIndentLevel += 1;
}
}
return outputLines.join('\n');
}
Explanation of Changes
Identifying Code Block Starters:
Introduced a codeBlockKeywords array containing common keywords that initiate code blocks.
When a line ends with {, we extract the part before { and check if it starts with any of the code block keywords using a regular expression.
Conditionally Replacing {:
If the line starts with a code block keyword, we replace { with : and increase the indentation level.
Else, we assume the { is part of an expression (like a dictionary) and leave the line unchanged.
Preserving Indentation and Structure:
Only lines determined to start a code block affect the currentIndentLevel. Expressions with { do not.
Examples
Let's see how the modified function handles different cases:
Code Block:
.pi Code:
pi
if condition {
do_something()
}
Translated .py Code:
python
if condition:
do_something()
Dictionary Assignment:
.pi Code:
pi
dic = {
"name": "John"
}
print(dic)
Translated .py Code:
python
dic = {
"name": "John"
}
print(dic)
Function with Dictionary Argument:
.pi Code:
pi
my_function({ "Name": "John" })
Translated .py Code:
python
my_function({ "Name": "John" })
Additional Considerations
Nested Code Blocks and Dictionaries:
The updated function correctly handles nested structures where dictionaries are inside code blocks or vice versa.
Multi-Line Expressions:
For multi-line dictionaries or other expressions, the function leaves the braces intact as long as they aren't part of a code block.
Edge Cases:
Ensure that edge cases, such as lines with multiple braces or unconventional formatting, are tested. You might need to further refine the regex patterns based on your specific use cases.
Complete Updated Script
For completeness, here's how the entire script with the updated translatePiToPy function would look:
typescript
Testing the Updated Function
Let's test the updated translatePiToPy function with different .pi code snippets to ensure it works as expected.
Code Block Example:
Input .pi Code:
pi
if x > 0 {
print("Positive")
} else {
print("Non-positive")
}
Translated .py Code:
python
if x > 0:
print("Positive")
else:
print("Non-positive")
Dictionary Assignment Example:
Input .pi Code:
pi
data = {
"id": 123,
"name": "Alice"
}
process(data)
Translated .py Code:
python
data = {
"id": 123,
"name": "Alice"
}
process(data)
class User {
def __init__(self, name, age) {
self.name = name
self.age = age
}
def to_dict(self) {
return {
"name": self.name,
"age": self.age
}
}
}
Translated .py Code:
python
Conclusion
By refining the translatePiToPy function to distinguish between code blocks and expressions, you ensure that:
Code Blocks (e.g., if, for, def) are correctly translated with proper indentation and syntax.
Dictionary Literals and other expressions using {} remain intact, preserving valid Python syntax.
This approach leverages simple heuristics based on common syntax patterns, providing a balance between functionality and complexity. For more advanced parsing needs, consider integrating a proper parser or leveraging existing parsing libraries.
Feel free to further customize the codeBlockKeywords array to include any additional keywords specific to your .pi language that initiate code blocks.
Not yet included in a published release.
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import * as glob from 'glob';
// Promisified versions of fs functions for easier async/await usage.
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const mkdir = util.promisify(fs.mkdir);
const access = util.promisify(fs.access);
/**
* Interface for piconfig.json
*/
interface PiConfig {
[sourceDir: string]: string;
}
/**
* Reads and parses the piconfig.json file.
* @returns The parsed configuration object.
*/
async function readConfig(): Promise<PiConfig> {
const configPath = path.resolve('piconfig.json');
try {
const data = await readFile(configPath, 'utf8');
const config: PiConfig = JSON.parse(data);
console.log(`Loaded configuration from ${configPath}:`, config);
return config;
} catch (err) {
console.error(`Error reading or parsing piconfig.json:`, err);
process.exit(1);
}
}
/**
* Translates .pi content to Python syntax by replacing curly brackets with colons
* and managing indentation. Preserves dictionary literals by not altering braces
* that are part of expressions.
* @param content The content of the .pi file.
* @returns The translated Python code.
*/
function translatePiToPy(content: string): string {
const lines = content.split(/\r?\n/);
const outputLines: string[] = [];
const indentUnit = ' '; // 4 spaces
let currentIndentLevel = 0;
// List of keywords that typically start a code block
const codeBlockKeywords = [
'if', 'else', 'elif', 'for', 'while',
'def', 'class', 'try', 'except', 'finally',
'with', 'switch', 'case'
];
for (let line of lines) {
let trimmedLine = line.trim();
// Skip empty lines
if (trimmedLine.length === 0) {
outputLines.push('');
continue;
}
// Handle closing brace
if (trimmedLine.startsWith('}')) {
currentIndentLevel = Math.max(currentIndentLevel - 1, 0);
trimmedLine = trimmedLine.substring(1).trim();
// If there's code after }, process it
if (trimmedLine.length > 0) {
// Fall through to process the remaining code
} else {
// No more code on this line
outputLines.push('');
continue;
}
}
// Check if the line ends with '{'
let hasOpeningBrace = false;
if (trimmedLine.endsWith('{')) {
// Determine if this brace starts a code block
// Extract the part before the '{'
const beforeBrace = trimmedLine.slice(0, -1).trim();
// Check if the line starts with any of the code block keywords
const startsWithCodeBlock = codeBlockKeywords.some(keyword => {
// Use a regex to match the keyword at the start followed by space or '('
const regex = new RegExp(`^${keyword}(\\s|\\()`);
return regex.test(beforeBrace);
});
if (startsWithCodeBlock) {
hasOpeningBrace = true;
// Replace '{' with ':' to conform to Python syntax
trimmedLine = beforeBrace + ':';
} else {
// The brace is part of an expression (e.g., dictionary), leave it as is
// Do not alter the line; proceed without replacing '{'
}
}
// Apply indentation
const indent = indentUnit.repeat(currentIndentLevel);
outputLines.push(indent + trimmedLine);
// If there was an opening brace for a code block, increase the indent
if (hasOpeningBrace) {
currentIndentLevel += 1;
}
}
return outputLines.join('\n');
}
/**
* Ensures that the directory exists. If not, creates it recursively.
* @param dirPath The directory path to ensure.
*/
async function ensureDirectory(dirPath: string) {
try {
await access(dirPath, fs.constants.F_OK);
// Directory exists
} catch {
// Directory does not exist, create it
await mkdir(dirPath, { recursive: true });
console.log(`Created directory: ${dirPath}`);
}
}
/**
* Processes a single .pi file and writes the translated .py file.
* @param inputPath The path to the .pi file.
* @param outputPath The path to the output .py file.
*/
async function processFile(inputPath: string, outputPath: string) {
try {
console.log(`\nProcessing file: ${inputPath}`);
const data = await readFile(inputPath, 'utf8');
const translated = translatePiToPy(data);
const outputDir = path.dirname(outputPath);
await ensureDirectory(outputDir);
await writeFile(outputPath, translated, 'utf8');
console.log(`Successfully compiled ${inputPath} → ${outputPath}`);
} catch (err) {
console.error(`Error processing file ${inputPath}:`, err);
}
}
/**
* Processes files based on the provided configuration.
* @param config The configuration object from piconfig.json.
*/
async function processConfig(config: PiConfig) {
// Iterate over each key in the config
for (const [sourceDir, targetDir] of Object.entries(config)) {
console.log(`\nProcessing mapping: ${sourceDir} → ${targetDir}`);
// Ensure the target directory exists
await ensureDirectory(targetDir);
// Define the glob pattern to find all .pi files recursively in sourceDir
const pattern = `${sourceDir}/**/*.pi`;
console.log(`Using glob pattern: ${pattern}`);
const files = glob.sync(pattern, { nodir: true });
console.log(`Found ${files.length} .pi file(s) in ${sourceDir}`);
if (files.length === 0) {
console.warn(`No .pi files found in ${sourceDir} using pattern ${pattern}`);
}
for (const file of files) {
// Compute the relative path from the source directory
const relativePath = path.relative(sourceDir, file);
// Define the output file path in the target directory with .py extension
const outputFilePath = path.join(targetDir, relativePath).replace(/\.pi$/i, '.py');
await processFile(file, outputFilePath);
}
}
}
/**
* Entry point of the script.
*/
async function main() {
console.log("Starting PI to PY compilation...");
// Read configuration
const config = await readConfig();
// Check if configuration is empty
if (Object.keys(config).length === 0) {
console.warn('piconfig.json is empty. No mappings to process.');
return;
}
// Process files based on the configuration
await processConfig(config);
console.log("\nPI to PY compilation completed.");
}
main();
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def to_dict(self):
return {
"name": self.name,
"age": self.age
}