Code Monkey home page Code Monkey logo

Comments (5)

mingodad avatar mingodad commented on May 28, 2024

After writing the above I noticed that the types array does come in file/line order except for the global vars/functions that comes at the end in one entry suffixed with _Fields_, would be nice if the var/function global declarations came individually in their file/line order like the other types and maybe move this helper array could be a field like fields.

from code-cookbook.

mingodad avatar mingodad commented on May 28, 2024

Here is an update version of MyOnGenerate.hx that shows how wild it becomes to be able to generate code in declaration order with the actual api:

#if macro
import haxe.macro.Type;
import haxe.macro.Context;

using haxe.macro.PositionTools;
using StringTools;

/**
 * Callback on generating code from context
 */
private function mygenerate(types:Array<Type>, filterFileName: String):Void {
	var buf = new StringBuf();
	var prev_file: String = null;
	var declarations = [];
	var global_declarations: Array<ClassField> = [];
	var last_global_decl_idx = 0;
	var last_global_decl_min = 0;

	function genDocComment(doc: String) {
		if(doc != null) {
			buf.add('\n/**${doc}*/');
		}
	}

	function genCode(this_types:Array<Type>) {
		for (ttype in this_types) {
			var aref = ttype.getParameters()[0].get();
			var apos = Context.getPosInfos(aref.pos);

			/*
				Check if there is any global declaration that preceed this declaration
				and if so gen code for then.
			*/
			if(last_global_decl_min < apos.min) {
				for(i in last_global_decl_idx...global_declarations.length) {
					var vg = global_declarations[i];
					var vg_pos = Context.getPosInfos(vg.pos);
					if(vg_pos.min < apos.min) {
						last_global_decl_idx = i+1;
						//trace(vg);
						genDocComment(vg.doc);
						buf.add('\nglobal ${vg.name};');
					}
					else break;
				}
				last_global_decl_min = apos.min;
			}
			switch (ttype) {
				case TMono(t):
					trace(t + "::" + aref.pos);
				case TEnum(t, params):
					var t_ref = t.get();
					trace(t.toString() + "::" + aref.pos + "::" + params.toString());
					buf.add('\nenum ${t_ref.name} {\n');
					var enumFields = [];
					for (efield in t_ref.constructs) {
						//trace(efield);
						var ebuf = new StringBuf();
						ebuf.add('\t${efield.name}');
						switch(efield.type) {
							case TEnum(_, _): ebuf.add(";\n");
							case TFun(args, _):
								ebuf.add("(");
								for (i in 0...args.length) {
									var arg = args[i];
									if (i > 0)
										ebuf.add(", ");
									var type_name = switch(arg.t) {
										case TAbstract(t, params): t.get().name;
										default:
											throw 'Unsupported paramter ${arg.t}';
											null;
									};
									ebuf.add('${arg.name}: ${type_name}');
								}
								ebuf.add(");\n");
	
							default:
								throw 'Unsupported paramter ${efield.type}';
						}
						enumFields.insert(efield.index, ebuf.toString());
					}
					for(elm in enumFields) buf.add(elm);
					buf.add("}\n");
					//trace(buf.toString());
				case TInst(t, params):
					var t_ref = t.get();
					trace(aref.name + "::" + aref.pos /*.getInfos().min*/ + "::" + params.toString());
					var classFields = t_ref.fields.get();
					buf.add('\nclass ${t_ref.name} {\n');
					//trace(classFields);
					if(t_ref.constructor != null) trace(t_ref.constructor.get());
					for (ifield in classFields) {
						trace(ifield);
						buf.add('\t${ifield.name};\n');
					}
					trace(t_ref.statics.get());
					buf.add("}\n");
					//trace(buf.toString());
				case TType(t, params):
					trace(aref.name + "::" + aref.pos /*.getInfos().min*/ + "::" + params.toString());
				case TFun(args, ret):
					trace(args + "::" + aref.pos + "::" + ret);
				case TAnonymous(a):
					trace(a + "::" + aref.pos);
				case TDynamic(t):
					trace(t + "::" + aref.pos);
				case TLazy(f):
					trace(f + "::" + aref.pos);
				case TAbstract(t, params):
					trace(aref.name + "::" + aref.pos /*.getInfos().min*/ + "::" + params.toString());
			}
		}
	}

	for (atype in types) {
		// trace(atype);
		var aref = atype.getParameters()[0].get();
		var apos = Context.getPosInfos(aref.pos);
		if(filterFileName != null && apos.file != filterFileName) continue;
		//trace(aref.name);
		if(StringTools.endsWith(aref.name, "_Fields_")) {
			switch(atype) {
				case TInst(t, params):
					var t_ref = t.get();
					global_declarations = t_ref.statics.get();
				default:
					throw 'Unsupported paramter ${atype}';
			}
		}
		else declarations.push(atype);

		/*
			After the first pass above to discover if we have global declarations
			we then now do the code generation
		*/
		if(prev_file != null && prev_file != apos.file) {
			genCode(declarations);
			declarations.resize(0); //clear
		}
		//trace(apos);
	}
	/*
		The last file is not managed inside the above loop
		so we do it now if any.
	*/
	if(declarations.length > 0) genCode(declarations);
	trace(buf.toString());
}

function set_on_generate(?ffname: String) {
	haxe.macro.Context.onGenerate(function(types:Array<Type>){mygenerate(types, ffname);});
}
#end

Output:

haxe "TestOnGenerate.hxml"
MyOnGenerate.hx:53: Color::#pos(TestOnGenerate.hx:9: lines 9-14)::[]
MyOnGenerate.hx:88: Test::#pos(TestOnGenerate.hx:16: lines 16-30)::[]
MyOnGenerate.hx:92: {name: new, isFinal: false, namePos: #pos(TestOnGenerate.hx:22: characters 19-22), isPublic: true, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:22: lines 22-26), kind: FMethod(MethNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TFun([{name: name, t: TInst(<...>,[]), opt: false},{name: x, t: TAbstract(<...>,[]), opt: false},{name: y, t: TAbstract(<...>,[]), opt: false}],TAbstract(Void,[])), expr: #fun}
MyOnGenerate.hx:94: {name: name, isFinal: false, namePos: #pos(TestOnGenerate.hx:18: characters 14-18), isPublic: true, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:18: characters 3-26), kind: FVar(AccNormal,AccNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TInst(String,[]), expr: #fun}
MyOnGenerate.hx:94: {name: x, isFinal: false, namePos: #pos(TestOnGenerate.hx:19: characters 14-15), isPublic: true, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:19: characters 3-22), kind: FVar(AccNormal,AccNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TAbstract(Float,[]), expr: #fun}
MyOnGenerate.hx:94: {name: y, isFinal: false, namePos: #pos(TestOnGenerate.hx:20: characters 14-15), isPublic: true, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:20: characters 3-22), kind: FVar(AccNormal,AccNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TAbstract(Float,[]), expr: #fun}
MyOnGenerate.hx:94: {name: toString, isFinal: false, namePos: #pos(TestOnGenerate.hx:27: characters 19-27), isPublic: true, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:27: lines 27-29), kind: FMethod(MethNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TFun([],TInst(String,[])), expr: #fun}
MyOnGenerate.hx:97: [{name: _count, isFinal: false, namePos: #pos(TestOnGenerate.hx:17: characters 14-20), isPublic: false, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:17: characters 3-30), kind: FVar(AccNormal,AccNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TAbstract(Int,[]), expr: #fun}]
MyOnGenerate.hx:88: TestOnGenerate::#pos(TestOnGenerate.hx:32: lines 32-37)::[]
MyOnGenerate.hx:97: [{name: main, isFinal: false, namePos: #pos(TestOnGenerate.hx:33: characters 21-25), isPublic: false, isAbstract: false, doc: null, params: [], pos: #pos(TestOnGenerate.hx:33: lines 33-36), kind: FMethod(MethNormal), meta: {get: #fun, remove: #fun, has: #fun, extract: #fun, add: #fun}, overloads: overloads, isExtern: false, type: TFun([],TAbstract(Void,[])), expr: #fun}]
MyOnGenerate.hx:148: 
global _version;
/** Get version string. */
global getVersion;
enum Color {
	Red;
	Green;
	Blue;
	RGB(r: Int, g: Int, b: Int);
}

class Test {
	name;
	x;
	y;
	toString;
}

class TestOnGenerate {
}

from code-cookbook.

mingodad avatar mingodad commented on May 28, 2024

And looking at the last output I can see that for class static fields and constructor we'll also will need two pass to properly generate code in declaration order.

If somehow we also manage to add the comments to the ast we could write several tools for Haxe code manipulation in Haxe itself, like code formatting, refactoring, documentation extraction, ...

In my opinion ideally we should be able to regenerate the original Haxe code through this api, onGenerate (not always the exact code because of possible optimizations) and with an afterParsing callback definitely we should be able to regenerate the identical source.

from code-cookbook.

mingodad avatar mingodad commented on May 28, 2024

So now I have a clear view of what this api should allow to do:

  • Regenerate identically the original source code.

And the Code Cookbook should show a sample that does that.

The sample should also be a test to detect any possible regression.

from code-cookbook.

markknol avatar markknol commented on May 28, 2024

Hey there! Thanks for figuring this out, it can be a nice to have an example generator in the cookbook as starting point for other people. It would be great if you create a pull request for the article. These are basically markdown pages. More about contributing articles can be found here https://github.com/HaxeFoundation/code-cookbook#creating-articles

Other than that, to me it is not very clear if you have technical questions or just thinking out loud here? (which for me is fine too 😜 )

from code-cookbook.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.