Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CompilerDefines fields #1010

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions Sources/kha/internal/CompilerDefinesBuilder.hx
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,49 @@ class CompilerDefinesBuilder {
*
* @return Array of class fields.
*/
public static macro function build() : Array<Field> {
var fields = Context.getBuildFields();

var defines = Context.getDefines();
public static macro function build(): Array<Field> {
final fields = Context.getBuildFields();
final defines = Context.getDefines();
final added:Map<String, Bool> = [];

for (k in defines.keys()) {
var key = $v{k};
final key = prepareFieldName($v{k});
if (added[key]) continue;
added[key] = true;
addField(fields, key, $v{Std.string(defines.get(key))});
}

return fields;
}

/**
* Fix wrong field names like keywords.
*
* @param name Field name.
* @return New field name.
*/
static function prepareFieldName(name: String): String {
if (isKeyword(name)) return '_$name';
name = ~/[^A-z0-9_]/.replace(name, "_");
if (~/^[0-9]/.match(name)) return '_$name';
return name;
}

static final keywords = [
"function", "class", "static", "var", "if", "else", "while", "do", "for",
"break", "return", "continue", "extends", "implements", "import",
"switch", "case", "default", "public", "private", "try", "untyped",
"catch", "new", "this", "throw", "extern", "enum", "in", "interface",
"cast", "override", "dynamic", "typedef", "package",
"inline", "using", "null", "true", "false", "abstract", "macro", "final",
"operator", "overload"
];

/** Checks for keywords (see `is_valid_identifier` from Haxe) */
static function isKeyword(name: String): Bool {
return keywords.indexOf(name) != -1;
}

/**
* Constructs the structure for defining a class field with public
* static visibility, and pushes it to the class fields array.
Expand All @@ -36,7 +66,7 @@ class CompilerDefinesBuilder {
* @param name Field name.
* @param value Field value.
*/
static function addField(fields : Array<Field>, name : String, value : String) : Void {
static function addField(fields: Array<Field>, name: String, value: String): Void {
fields.push({
name: name,
access: [ APublic, AStatic ],
Expand Down