From 61c11ee1b4222f01eebd600a2699f27c24d4c958 Mon Sep 17 00:00:00 2001 From: David Majda Date: Thu, 14 Jul 2016 14:56:24 +0200 Subject: [PATCH] peg.generate: Implement { format: "amd" } --- README.md | 8 ++++---- lib/compiler/passes/generate-js.js | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c41a223..08e80fd 100644 --- a/README.md +++ b/README.md @@ -140,13 +140,13 @@ object to `peg.generate`. The following options are supported: `false`) * `dependencies` — parser dependencies, the value is an object which maps variables used to access the dependencies in the parser to module IDs used - to load them; valid only when `format` is set to `"node"` or `"umd"` - (default: `{}`) + to load them; valid only when `format` is set to `"amd"`, `"node"`, or + `"umd"` (default: `{}`) * `exportVar` — name of a global variable into which the parser object is assigned to when no module loader is detected; valid only when `format` is set to `"umd"` (default: `null`) - * `format` — format of the genreated parser (`"bare"`, `"node"`, or `"umd"`); - valid only when `output` is set to `"source"` (default: `"bare"`) + * `format` — format of the genreated parser (`"amd"`, `"bare"`, `"node"`, or + `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) * `optimize`— selects between optimizing the generated parser for parsing speed (`"speed"`) or code size (`"size"`) (default: `"speed"`) * `output` — if set to `"parser"`, the method will return generated parser diff --git a/lib/compiler/passes/generate-js.js b/lib/compiler/passes/generate-js.js index efea66c..de35a34 100644 --- a/lib/compiler/passes/generate-js.js +++ b/lib/compiler/passes/generate-js.js @@ -1302,6 +1302,30 @@ function generateJS(ast, options) { return parts.join('\n'); }, + amd: function() { + var dependencyIds = objects.values(options.dependencies), + dependencyVars = objects.keys(options.dependencies), + dependencies = '[' + + arrays.map( + dependencyIds, + function(id) { return '"' + js.stringEscape(id) + '"'; } + ).join(', ') + + ']', + params = dependencyVars.join(', '); + + return [ + generateGeneratedByComment(), + 'define(' + dependencies + ', function(' + params + ') {', + ' "use strict";', + '', + indent2(toplevelCode), + '', + indent2('return ' + generateParserObject() + ';'), + '});', + '' + ].join('\n'); + }, + umd: function() { var parts = [], dependencyIds = objects.values(options.dependencies),