HaxeFoundation / haxe

Haxe - The Cross-Platform Toolkit
https://haxe.org
6.14k stars 656 forks source link

Misalignment in Json stringify result with pretty when the object has a parent class with no variables #11560

Closed MadEwink closed 8 months ago

MadEwink commented 8 months ago

Haxe version : Tested on 4.3.2

Issue : When using haxe.Json.stringify on a class which inherits a class with at least one method and no variables, pretty formatting will be broken with a missing line return and wrong indentation. This is a minor issue that can safely be ignored.

Example :

class JsonPrettyClass {
    public static function main() {
        var p = new ParentClass();
        var c = new ChildClass();

        // If parent class had variables they would be last, thus causing no issue
        // trace("-- Parent class fields --");
        // for (f in Type.getInstanceFields(ParentClass)) {
        //     trace(f);
        // }

        // Child class field variables are before parent class methods
        // trace("-- Child class fields --");
        // for (f in Type.getInstanceFields(ChildClass)) {
        //     trace(f);
        // }

        var json = haxe.Json.stringify(c, "\t");
        trace(json);
    }
}

class ParentClass {
    // no field variable, the issue does not reproduce when there is one

    function anyFunc() {}

    public function new() {}
}

class ChildClass extends ParentClass {
    var anyVar : Int;
}

My understanding : This is caused by the changes in this commit. In the specific case when the object which is passed to write happens to be an instance of a class which inherits a class with only methods and no variables, the if (i == last) condition in fieldsString is skipped.

Fix proposal : fix-proposal.patch

Simn commented 8 months ago

Thanks! That's a nice edge case which apparently went unnoticed for 10 years. I've applied the fix as you've suggested, and added your example as a test. We will also add this to 4.3.