Skip to content

Macro: even more friendly trace() #187

@farteryhr

Description

@farteryhr

that aims to provide better learning experience for the real beginners.

also something i dreamed of when typing down the first print what ever in basic.

i remember i've mentioned this somewhere sometime ago in the community... uhm but this time better place and better done?

to be discussed here is, is it good enough (in the sense of portability or anything else)?

import haxe.macro.Expr;
import haxe.macro.Context;
using haxe.macro.ExprTools;
class Hello {
  macro static function show(args: Array<Expr>){
    var exprs=[for(el in args) macro $v{el.toString()+": "}+$el];
    return {
      pos:Context.currentPos(),
      expr:ECall(
        {
          pos:Context.currentPos(),
          expr:EConst(CIdent("trace"))
        },
        exprs.length==1?exprs:[macro $a{exprs}.join(", ")]
      )
    };
  }
  static function main() {
    var a="Haxe",b="great";
    show('$a is $b!');
    show(''.length);
    var arr=[1,2,3];
    for(i=>v in arr){
      show(i,v);
    }
    show({a:1,b:2});
  }
}

currently generates (fairly good i think):

Hello.main = function() {
	var a = "Haxe";
	var b = "great";
	console.log("Hello.hx:20:","'$a is $b!': " + ("" + a + " is " + b + "!"));
	console.log("Hello.hx:21:","'人'.length: " + "人".length);
	var arr = [1,2,3];
	var _g_current = 0;
	var _g_array = arr;
	while(_g_current < _g_array.length) {
		var _g_value = _g_array[_g_current];
		var _g_key = _g_current++;
		var i = _g_key;
		var v = _g_value;
		console.log("Hello.hx:24:",["i: " + i,"v: " + v].join(", "));
	}
	console.log("Hello.hx:26:","{ a : 1, b : 2 }: " + Std.string({ a : 1, b : 2}));
};

also, trace(a) and trace(a,b) generates very different js code, the latter seems to bloats the code everywhere, haxe_Log.trace(a,{ fileName : "Hello.hx", lineNumber : 27, className : "Hello", methodName : "main", customParams : [b]}); there might be some room of improvement (but compatibility considerations?) for haxe_Log.trace.

so for now it's like another reason to use this to ensure this doesn't happen by joining the arguments manually. but afaik console.log treats all arguments equal, like conceptually what trace(a,b) do.
would directly utilizing the built-in console.log pretty-printing be considered? the best outcome i think might be like console.log("Hello.hx:24: i:",i,"v:",v);.

would it be possible to make this built-in behavior of trace, or traceExpr or some better (shorter) name, tracex?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions