-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
WIP #541 Refactored nn-parser for better reusability
- Loading branch information
Showing
2 changed files
with
82 additions
and
56 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
(function(root, factory){ | ||
if(typeof define === "function" && define.amd) { | ||
define(['./lua'], function(luajs){ | ||
return (root.LayerParser = factory(luajs)); | ||
}); | ||
} else if(typeof module === "object" && module.exports) { | ||
var luajs = require('./lua'); | ||
module.exports = (root.LayerParser = factory(luajs)); | ||
} | ||
}(this, function(luajs) { | ||
var LayerParser = {}; | ||
|
||
var findInitParams = function(ast){ | ||
// Find '__init' function | ||
var params; | ||
ast.block.stats.forEach(function(block){ | ||
if(block.key && block.key.val == '__init' && block.func){ | ||
params = block.func.args; | ||
if(params.length === 0 && block.func.varargs){ | ||
params[0] = 'params'; | ||
} | ||
} | ||
}); | ||
return params; | ||
}; | ||
|
||
var findTorchClass = function(ast){ | ||
var torchClassArgs, // args for `torch.class(...)` | ||
name = '', | ||
baseType, | ||
params = []; | ||
|
||
if(ast.type == 'function'){ | ||
ast.block.stats.forEach(function(func){ | ||
if(func.type == 'stat.local' && func.right && func.right[0] && | ||
func.right[0].func && func.right[0].func.self && | ||
func.right[0].func.self.val == 'torch' && | ||
func.right[0].func.key.val == 'class'){ | ||
|
||
torchClassArgs = func.right[0].args.map(arg => arg.val); | ||
name = torchClassArgs[0]; | ||
if(name !== ''){ | ||
name = name.replace('nn.', ''); | ||
params = findInitParams(ast); | ||
if (torchClassArgs.length > 1) { | ||
baseType = torchClassArgs[1].replace('nn.', ''); | ||
} | ||
} | ||
} | ||
}); | ||
// If there is a name, check for methods owned by the given name | ||
// which modify a 'self' value and return 'self' | ||
// TODO | ||
} | ||
return { | ||
name, | ||
baseType, | ||
params | ||
}; | ||
}; | ||
|
||
LayerParser.parse = function(text) { | ||
var ast = luajs.parser.parse(text); | ||
return findTorchClass(ast); | ||
}; | ||
|
||
return LayerParser; | ||
})); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters