Żmija is a simple universal code generation tool.

Overview

Zmija


GitHub code size in bytes GitHub issues GitHub last commit GitHub commit activity GitHub


Żmija

Żmija is a simple universal code generation tool. It is intended to be used as a means to generate code that is both efficient and easily maintainable.

It is intended to be used in embedded systems with limited resources, however it can be used anywhere else as well.


Usage

Żmija lets you define sections in your code where code is generated automatically in accordance to a provided Python script. Such a section typically looks like this:

/* ~ZMIJA.GENERATOR:
def declare(variables):
	pass
	
def init(variables):
	pass
	
def generate(variables):
	return ""
*/// ~ZMIJA.GENERATED_CODE:

// ~ZMIJA.END

The section is defined inside a multi-line comment as to not affect the compilation of the code it is located in. Żmija supports any languge, including those that have non C-style comment styles (hence it is universal).

This is what the same section might look like inside a Lua script, for example:

--[[ ~ZMIJA.GENERATOR:
def declare(variables):
	pass
	
def init(variables):
	pass
	
def generate(variables):
	return ""
]]-- ~ZMIJA.GENERATED_CODE:

-- ~ZMIJA.END

Each section consists of a declare-function, an init-function and a generate-function. Each function is provided with the variables argument, which is a dictionary that is intended to be used for the storage of variables.

The declare-function is executed first. It is meant for variable declaration and should only reference its own variables.

The init-function is meant to initialize variables, including those of other sections. It is executed only after the declare-function has been executed for all sections in the project.

The generate-function returns the generated code for the section it is located in. It is executed only after the declare and init-functions of all sections have been executed.

Note: Empty functions can safely be removed.


Run python3 ./src/zmija.py /path/to/your/project/directory/ to perform the code generation. The generated code will be placed between the ~ZMIJA.GENERATED_CODE: and the ~ZMIJA.END lines.


Help output

Zmija. Simple universal code generation.

Usage:
	zmija.py path
	zmija.py path -d | --delete
	zmija.py path -c | --check-only
	zmija.py path --config-path="path/to/config"
	zmija.py -h | --help
	
Options:
	-h --help         Show this screen.
	-d --delete       Delete all generated code.
	-c --check-only   Check Python code for syntax and runtime errors without writing the
	                  changes to file.
	-u --unsafe       Skip the test pass. May cause data loss if the Python code raises
	                  exceptions, but offers better performance. Use with caution.
	--config-path     Provides a path to a configuration file.
	
Config:
	file_filter(file_path)     A function intended to filter file paths. Any file path
	                           for which this function returns False is ignored.

Config

You can define a file path filter function inside a config file, such that certain files are ignored by Żmija.

Here's what an example config file may look like:

def file_filter(file_path):
	return file_path.endswith('.cpp') or file_path.endswith('.h')

The file path of the config file needs to be supplied using the --config-file argument, like so:

python3 ./src/zmija.py /path/to/your/project/directory/ --config-file="/path/to/your/config/file"


Example

Say you have two modules, a ButtonController and a LedController. You would like to implement the observer pattern to allow the ButtonController to communicate with the LedController without depending on it.

The following C++ code implements this. It is a simple example where pressing the button toggles the LED.

register_callback([this]() { toggle_led(); }); } int main() { button_controller = new ButtonController(); led_controller = new LedController(); button_controller->on_button_pressed(); return 0; } ">
#include <stdio.h>
#include <vector>
#include <functional>

// This would typically go into .h files:
struct ButtonController {
private:
    // Callbacks are functions that will be called
    // when the button is pressed. Notice how the
    // vector is constructed at runtime and held in
    // RAM.
    std::vector
   <
   void()>> callbacks;


   public:
    
   void 
   on_button_pressed();
    
   void 
   register_callback(std::function<
   void()> cb);
};


   struct 
   LedController {

   public:
    
   void 
   toggle_led();

    
   LedController();
};




   // This would typically go into .cpp files:
ButtonController *button_controller;
LedController *led_controller;


   // This function is meant to be automatically

   // called whenever a button is pressed.

   void 
   ButtonController::on_button_pressed() {
    
   // call all registered callbacks
    
   for (
   auto &cb : callbacks) 
   cb();
}


   // This function is meant to be called by other

   // modules that would like to react to button

   // presses.

   void 
   ButtonController::register_callback(std::function<
   void()> cb) {
    callbacks.
   push_back(cb);
}



   void 
   LedController::toggle_led() {
    
   printf(
   "LED toggled.\n");
}


   LedController::LedController() {
    
   // Registering a new callback consumes precious RAM.
    button_controller->
   register_callback([
   this]() {
        
   toggle_led();
    });
}


   int 
   main() {
    button_controller = 
   new 
   ButtonController();
    led_controller = 
   new 
   LedController();

    button_controller->
   on_button_pressed();

    
   return 
   0;
}
  

Calling the main() function will print LED toggled. to the console, as intended.

However, the ButtonController's callbacks vector is built during runtime and held in RAM. This causes an unnecessary overhead regarding both memory usage and execution speed.

Since the registered callbacks do not change after they have been registered, it may be beneficial to register them during compile time instead.


The following C++ code attempts to achieve this by using Żmija to generate the callbacks during compile time:

toggle_led();") def generate(variables): # Nothing to do. This function can safely be removed. return '' */// ~ZMIJA.GENERATED_CODE: // ~ZMIJA.END } int main() { button_controller = new ButtonController(); led_controller = new LedController(); button_controller->on_button_pressed(); return 0; } ">
#include <stdio.h>

// This would typically go into .h files:
struct ButtonController {
public:
	void on_button_pressed();
};

struct LedController {
public:
	void toggle_led();

	LedController();
};



// This would typically go into .cpp files:
ButtonController *button_controller;
LedController *led_controller;

// This function is meant to be automatically
// called whenever a button is pressed.
void ButtonController::on_button_pressed() {
	/* ~ZMIJA.GENERATOR:
	def declare(variables):
		# Declare a new list called "on_button_pressed".
		# This list will contain calls to callback functions
		# in string form.
		variables["on_button_pressed"] = []
		
	def init(variables):
		# Nothing to do. This function can safely be removed.
		pass
		
	def generate(variables):
		# Return a string containing all callback calls,
		# separated by a newline character.
		return "\n".join(variables["on_button_pressed"])
	*/// ~ZMIJA.GENERATED_CODE:
	
	// ~ZMIJA.END
}


void LedController::toggle_led() {
	printf("LED toggled.\n");
}

LedController::LedController() {
	/* ~ZMIJA.GENERATOR:
	def declare(variables):
		# Nothing to do. This function can safely be removed.
		pass
	
	def init(variables):
		# Add a callback call in string form.
		# This string will be added to the ButtonController's 
		# generated code.
		variables["on_button_pressed"].append("led_controller->toggle_led();")
		
	def generate(variables):
		# Nothing to do. This function can safely be removed.
		return ''
	*/// ~ZMIJA.GENERATED_CODE:
	
	// ~ZMIJA.END
}

int main() {
	button_controller = new ButtonController();
	led_controller = new LedController();

	button_controller->on_button_pressed();

	return 0;
}

Let's run Żmija:

python3 ./src/zmija.py /path/to/your/project/directory/

This is what our newly generated .cpp file looks like now:

toggle_led(); // ~ZMIJA.END } void LedController::toggle_led() { printf("LED toggled.\n"); } LedController::LedController() { /* ~ZMIJA.GENERATOR: def declare(variables): # Nothing to do. This function can safely be removed. pass def init(variables): # Add a callback call in string form. # This string will be added to the ButtonController's # generated code. variables["on_button_pressed"].append("led_controller->toggle_led();") def generate(variables): # Nothing to do. This function can safely be removed. return '' */// ~ZMIJA.GENERATED_CODE: // ~ZMIJA.END } int main() { button_controller = new ButtonController(); led_controller = new LedController(); button_controller->on_button_pressed(); return 0; } ">
#include <stdio.h>

// This would typically go into .h files:
struct ButtonController {
public:
	void on_button_pressed();
};

struct LedController {
public:
	void toggle_led();

	LedController();
};



// This would typically go into .cpp files:
ButtonController *button_controller;
LedController *led_controller;

// This function is meant to be automatically
// called whenever a button is pressed.
void ButtonController::on_button_pressed() {
	/* ~ZMIJA.GENERATOR:
	def declare(variables):
		# Declare a new list called "on_button_pressed".
		# This list will contain calls to callback functions
		# in string form.
		variables["on_button_pressed"] = []
		
	def init(variables):
		# Nothing to do. This function can safely be removed.
		pass
		
	def generate(variables):
		# Return a string containing all callback calls,
		# separated by a newline character.
		return "\n".join(variables["on_button_pressed"])
	*/// ~ZMIJA.GENERATED_CODE:
	led_controller->toggle_led();
	// ~ZMIJA.END
}


void LedController::toggle_led() {
	printf("LED toggled.\n");
}

LedController::LedController() {
	/* ~ZMIJA.GENERATOR:
	def declare(variables):
		# Nothing to do. This function can safely be removed.
		pass
	
	def init(variables):
		# Add a callback call in string form.
		# This string will be added to the ButtonController's 
		# generated code.
		variables["on_button_pressed"].append("led_controller->toggle_led();")
		
	def generate(variables):
		# Nothing to do. This function can safely be removed.
		return ''
	*/// ~ZMIJA.GENERATED_CODE:
	
	// ~ZMIJA.END
}

int main() {
	button_controller = new ButtonController();
	led_controller = new LedController();

	button_controller->on_button_pressed();

	return 0;
}

As you can see, Żmija has generated the led_controller->toggle_led();-line, just as intended.

Owner
Adrian Samoticha
Adrian Samoticha
Get link preview of a website.

Preview Link You may have seen a preview of a link with a title, image, domain, and description when you share a link on social media. This preview ha

SREEHARI K.V 8 Jan 08, 2023
🍭 epub generator for lightnovel.us 轻之国度 epub 生成器

lightnovel_epub 本工具用于基于轻之国度网页生成epub小说。 注意:本工具仅作学习交流使用,作者不对内容和使用情况付任何责任! 原理 直接抓取 HTML,然后将其中的图片下载至本地,随后打包成 EPUB。

gyro永不抽风 188 Dec 30, 2022
A hack to run custom shell commands when building documentation on Read the Docs.

readthedocs-custom-steps A hack to run custom steps when building documentation on Read the Docs. Important: This module should not be installed outsi

Niklas Rosenstein 5 Feb 22, 2022
ACPOA plugin creation helper

ACPOA Plugin What is ACPOA ACPOA is the acronym for "Application Core for Plugin Oriented Applications". It's a tool to create flexible and extendable

Leikt Sol'Reihin 1 Oct 20, 2021
Material for the ros2 crash course

Material for the ros2 crash course

Emmanuel Dean 1 Jan 22, 2022
Some of the best ways and practices of doing code in Python!

Pythonicness ❤ This repository contains some of the best ways and practices of doing code in Python! Features Properly formatted codes (PEP 8) for bet

Samyak Jain 2 Jan 15, 2022
EasyMultiClipboard - Python script written to handle more than 1 string in clipboard

EasyMultiClipboard - Python script written to handle more than 1 string in clipboard

WVlab 1 Jun 18, 2022
A clean customizable documentation theme for Sphinx

A clean customizable documentation theme for Sphinx

Pradyun Gedam 1.5k Jan 06, 2023
A `:github:` role for Sphinx

sphinx-github-role A github role for Sphinx. Usage Basic usage MyST: :caption: index.md See {github}`astrojuanlu/sphinx-github-role#1`. reStructuredT

Juan Luis Cano Rodríguez 4 Nov 22, 2022
30 Days of google cloud leaderboard website

30 Days of Cloud Leaderboard This is a leaderboard for the students of Thapar, Patiala who are participating in the 2021 30 days of Google Cloud Platf

Developer Student Clubs TIET 13 Aug 25, 2022
A next-generation curated knowledge sharing platform for data scientists and other technical professions.

Knowledge Repo The Knowledge Repo project is focused on facilitating the sharing of knowledge between data scientists and other technical roles using

Airbnb 5.2k Dec 27, 2022
Assignments from Launch X's python introduction course

Launch X - On Boarding Assignments from Launch X's Python Introduction Course Explore the docs » Report Bug · Request Feature Table of Contents About

Javier Méndez 0 Mar 15, 2022
OpenTelemetry Python API and SDK

Getting Started • API Documentation • Getting In Touch (GitHub Discussions) Contributing • Examples OpenTelemetry Python This page describes the Pytho

OpenTelemetry - CNCF 1.1k Jan 08, 2023
The project that powers MDN.

Kuma Kuma is the platform that powers MDN (developer.mozilla.org) Development Code: https://github.com/mdn/kuma Issues: P1 Bugs (to be fixed ASAP) P2

MDN Web Docs 1.9k Dec 26, 2022
Convert excel xlsx file's table to csv file, A GUI application on top of python/pyqt and other opensource softwares.

Convert excel xlsx file's table to csv file, A GUI application on top of python/pyqt and other opensource softwares.

David A 0 Jan 20, 2022
Exercism exercises in Python.

Exercism exercises in Python.

Exercism 1.3k Jan 04, 2023
Fast syllable estimation library based on pattern matching.

Syllables: A fast syllable estimator for Python Syllables is a fast, simple syllable estimator for Python. It's intended for use in places where speed

ProseGrinder 26 Dec 14, 2022
JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates.

JTEX JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates. This package uses Jinja2 as the template engine with

Curvenote 15 Dec 21, 2022
charcade is a string manipulation library that can animate, color, and bruteforce strings

charcade charcade is a string manipulation library that can animate, color, and bruteforce strings. Features Animating text for CLI applications with

Aaron 8 May 23, 2022
An awesome Data Science repository to learn and apply for real world problems.

AWESOME DATA SCIENCE An open source Data Science repository to learn and apply towards solving real world problems. This is a shortcut path to start s

Academic.io 20.3k Jan 09, 2023