python2igcse
Version:
Convert Python code to IGCSE Pseudocode format
347 lines (343 loc) • 13.7 kB
JavaScript
;
// Python to IGCSE Pseudocode Converter - Main Entry Point
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.examples = exports.utils = exports.defaultConverter = exports.IGCSE_SPEC_VERSION = exports.SUPPORTED_PYTHON_VERSION = exports.VERSION = exports.EmitterUtils = exports.createEmitter = exports.MarkdownEmitter = exports.TextEmitter = exports.BaseEmitter = exports.createParser = exports.PythonASTVisitor = exports.PythonParser = exports.BaseParser = exports.PythonToIGCSEConverter = exports.CLI = exports.convertFilesToIGCSE = exports.convertFileToIGCSE = exports.convertPythonToIGCSE = exports.Converter = void 0;
exports.convertPython = convertPython;
// Core exports
var converter_1 = require("./converter");
Object.defineProperty(exports, "Converter", { enumerable: true, get: function () { return converter_1.Converter; } });
Object.defineProperty(exports, "convertPythonToIGCSE", { enumerable: true, get: function () { return converter_1.convertPythonToIGCSE; } });
Object.defineProperty(exports, "convertFileToIGCSE", { enumerable: true, get: function () { return converter_1.convertFileToIGCSE; } });
Object.defineProperty(exports, "convertFilesToIGCSE", { enumerable: true, get: function () { return converter_1.convertFilesToIGCSE; } });
var cli_1 = require("./cli");
Object.defineProperty(exports, "CLI", { enumerable: true, get: function () { return cli_1.CLI; } });
// Legacy export for compatibility
var converter_2 = require("./converter");
Object.defineProperty(exports, "PythonToIGCSEConverter", { enumerable: true, get: function () { return converter_2.Converter; } });
// Import for internal use
const converter_3 = require("./converter");
// Parser exports
var parser_1 = require("./parser");
Object.defineProperty(exports, "BaseParser", { enumerable: true, get: function () { return parser_1.BaseParser; } });
Object.defineProperty(exports, "PythonParser", { enumerable: true, get: function () { return parser_1.PythonParser; } });
Object.defineProperty(exports, "PythonASTVisitor", { enumerable: true, get: function () { return parser_1.PythonASTVisitor; } });
Object.defineProperty(exports, "createParser", { enumerable: true, get: function () { return parser_1.createParser; } });
// Emitter exports
var emitter_1 = require("./emitter");
Object.defineProperty(exports, "BaseEmitter", { enumerable: true, get: function () { return emitter_1.BaseEmitter; } });
Object.defineProperty(exports, "TextEmitter", { enumerable: true, get: function () { return emitter_1.TextEmitter; } });
Object.defineProperty(exports, "MarkdownEmitter", { enumerable: true, get: function () { return emitter_1.MarkdownEmitter; } });
Object.defineProperty(exports, "createEmitter", { enumerable: true, get: function () { return emitter_1.createEmitter; } });
Object.defineProperty(exports, "EmitterUtils", { enumerable: true, get: function () { return emitter_1.EmitterUtils; } });
// Type exports
__exportStar(require("./types"), exports);
// Version and constants
var types_1 = require("./types");
Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return types_1.VERSION; } });
Object.defineProperty(exports, "SUPPORTED_PYTHON_VERSION", { enumerable: true, get: function () { return types_1.SUPPORTED_PYTHON_VERSION; } });
Object.defineProperty(exports, "IGCSE_SPEC_VERSION", { enumerable: true, get: function () { return types_1.IGCSE_SPEC_VERSION; } });
/**
* Quick conversion function for simple use cases
*/
async function convertPython(pythonCode) {
const converter = new converter_3.Converter();
const result = await converter.convert(pythonCode);
return result.code;
}
/**
* Default converter instance for quick usage
*/
exports.defaultConverter = new (class DefaultConverter {
constructor() {
this.converter = new converter_3.Converter();
}
/**
* Quick conversion with default options
*/
async convert(pythonCode) {
return this.converter.convert(pythonCode);
}
/**
* Convert to markdown format
*/
async convertToMarkdown(pythonCode) {
const converter = new converter_3.Converter({ outputFormat: 'markdown' });
return converter.convert(pythonCode);
}
/**
* Convert with custom options
*/
async convertWithOptions(pythonCode, options) {
const converter = new converter_3.Converter(options);
return converter.convert(pythonCode);
}
})();
/**
* Utility functions for common use cases
*/
exports.utils = {
/**
* Create a converter with preset configurations
*/
createConverter: {
/**
* Converter optimized for educational use
*/
educational: () => new converter_3.Converter({
outputFormat: 'plain',
beautify: true,
includeComments: true,
uppercaseKeywords: true,
spaceAroundOperators: true,
maxLineLength: 80
}),
/**
* Converter optimized for markdown documentation
*/
documentation: () => new converter_3.Converter({
outputFormat: 'markdown',
beautify: true,
includeComments: true,
includeLineNumbers: false
}),
/**
* Converter with compact output
*/
compact: () => new converter_3.Converter({
outputFormat: 'plain',
beautify: false,
includeComments: false,
indentSize: 2,
maxLineLength: 120
}),
/**
* Converter with strict validation
*/
strict: () => new converter_3.Converter({
strictMode: true,
maxErrors: 5,
timeout: 10000
})
},
/**
* Validation utilities
*/
validate: {
/**
* Check if Python code is suitable for IGCSE conversion
*/
async isPythonCodeSuitable(pythonCode) {
try {
const converter = new converter_3.Converter();
const result = await converter.convert(pythonCode);
const issues = [];
const suggestions = [];
// Check for errors
if (result.parseResult.errors.length > 0) {
issues.push(...result.parseResult.errors.map((e) => e.message));
}
// Check for warnings
if (result.parseResult.warnings.length > 0) {
suggestions.push(...result.parseResult.warnings.map((w) => w.message));
}
// Additional checks
if (pythonCode.includes('import ')) {
suggestions.push('Consider removing or simplifying import statements for IGCSE compatibility');
}
if (pythonCode.includes('class ')) {
suggestions.push('Object-oriented features may need simplification for IGCSE level');
}
return {
suitable: issues.length === 0,
issues,
suggestions
};
}
catch (error) {
return {
suitable: false,
issues: [error instanceof Error ? error.message : 'Unknown error'],
suggestions: []
};
}
},
/**
* Get complexity analysis of Python code
*/
async analyzeComplexity(pythonCode) {
try {
const converter = new converter_3.Converter();
const result = await converter.convert(pythonCode);
// Analyze IR for complexity
const lines = pythonCode.split('\n').length;
let functions = 0;
let loops = 0;
let conditionals = 0;
let maxDepth = 0;
const analyzeNode = (node, depth = 0) => {
maxDepth = Math.max(maxDepth, depth);
switch (node.kind) {
case 'function':
case 'procedure':
functions++;
break;
case 'for':
case 'while':
case 'repeat':
loops++;
break;
case 'if':
conditionals++;
break;
}
for (const child of node.children) {
analyzeNode(child, depth + 1);
}
};
if (Array.isArray(result.parseResult.ir)) {
result.parseResult.ir.forEach(node => analyzeNode(node));
}
else {
analyzeNode(result.parseResult.ir);
}
// Determine complexity level
let complexity = 'low';
const recommendations = [];
if (lines > 100 || functions > 5 || maxDepth > 4) {
complexity = 'high';
recommendations.push('Consider breaking down into smaller, simpler functions');
}
else if (lines > 50 || functions > 3 || maxDepth > 3) {
complexity = 'medium';
recommendations.push('Code complexity is moderate - good for intermediate IGCSE level');
}
else {
recommendations.push('Code complexity is appropriate for IGCSE level');
}
if (loops > 3) {
recommendations.push('Multiple loops detected - ensure each serves a clear purpose');
}
if (conditionals > 5) {
recommendations.push('Many conditional statements - consider simplifying logic');
}
return {
complexity,
metrics: {
lines,
functions,
loops,
conditionals,
nestingDepth: maxDepth
},
recommendations
};
}
catch (error) {
return {
complexity: 'high',
metrics: {
lines: pythonCode.split('\n').length,
functions: 0,
loops: 0,
conditionals: 0,
nestingDepth: 0
},
recommendations: ['Error analyzing code complexity']
};
}
}
},
/**
* Format utilities
*/
format: {
/**
* Format code for different educational contexts
*/
forExam: (code) => {
// Format code specifically for exam presentation
return code
.split('\n')
.map((line, index) => `${(index + 1).toString().padStart(2, '0')}. ${line}`)
.join('\n');
},
/**
* Format code for textbook inclusion
*/
forTextbook: (code) => {
// Add proper spacing and formatting for textbook
return code
.split('\n')
.map(line => line.trim() ? ` ${line}` : '')
.join('\n');
},
/**
* Format code for presentation slides
*/
forSlides: (code) => {
// Optimize for presentation visibility
return code
.replace(/\t/g, ' ') // Convert tabs to 2 spaces
.split('\n')
.filter(line => line.trim()) // Remove empty lines
.join('\n');
}
}
};
/**
* Quick start examples
*/
exports.examples = {
/**
* Basic variable assignment
*/
basicAssignment: `x = 5
y = 10
result = x + y
print(result)`,
/**
* Simple function
*/
simpleFunction: `def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 3)
print(f"Area: {result}")`,
/**
* Loop example
*/
simpleLoop: `for i in range(5):
print(f"Number: {i}")
total = 0
for num in [1, 2, 3, 4, 5]:
total += num
print(f"Total: {total}")`,
/**
* Conditional example
*/
simpleConditional: `age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
if age >= 65:
print("Senior citizen discount available")`
};
// Re-export Converter class as default export
var converter_4 = require("./converter");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return converter_4.Converter; } });
//# sourceMappingURL=index.js.map