Skip to content

Code generation #34

Open
Open
@patgrasso

Description

@patgrasso

Some solutions have been proposed to reduce the string concatenation (#11, #12). I'd like to pitch another alternative: code generation from a dynamically generated AST using escodegen.

You could have something like this:

const Sum = (exprs) => exprs.reduce((prev, curr) => BinOp(prev, '+', curr));

const strideTimesX = (i) => BinOp(
    Member(parse('this.stride'), Literal(i), true),
    '*',
    'x' + i
);

const getFactory = (d, type) => FunctionDecl(
    className(d, type) + '_get', args,
    Return(
      Member(
        parse('this.data'),
        Sum( range(d).map(strideTimesX).concat(thisOffset) ),
        true))));

esprima or acorn can also be used to generate the AST for the static portions of the code:

// from view.pick
let vars = acorn.parse('var a = [], b = [], c = this.offset;').body[0].expression;

FunctionDecl('pick', range(n).map((i) => 'x' + i),
  [ vars,
  //...
    Return(BinOp('a', '+', 'b')) ] // <-- not accurate, just an example

This would allow for runtime generation of the classes and retention of efficiency, but in a more controlled and maintainable way. It also reads somewhat intuitively (I've been playing around with escodegen, the above are working examples).

Let me know what you think. You can see updates in my fork patgrasso/ndarray (check out the escodegen branch).

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