Generate the JS code for the XJS module.

@param  {object} code - Helper for Javascript code writing.
@param {string} moduleName - Javascript module name.

@return {string} Resulting JS code.
431817
function outputAll( code, moduleName ) {
    try {
        let out = outputComments( code );
        out += "  module.exports = function() {\n";
        out += outputNeededConstants( code );
        out += `    //-------------------
    // Class definition.
    const ViewClass = function( args ) {
      try {
        if( typeof args === 'undefined' ) args = {};
        this.$elements = {};
        ${outputClassBody(code)}
      }
      catch( ex ) {
        console.error('${moduleName}', ex);
        throw Error('Instantiation error in XJS of ${JSON.stringify(moduleName)}:\\n' + ex)
      }
    };\n`;
        out += generate( code.section.statics, "Static members.", "    " );
        out += "    return ViewClass;\n";
        out += "  }();\n";
        return out;
    } catch ( ex ) {
        bubble( ex, "outputAll()" );
        return null;
    }
}
202761
private static int scriptNameToCode(String name) {
        try{
            int[] codes = UScript.getCode(name);
            return codes != null ? codes[0] : UScript.INVALID_CODE;
        }catch( MissingResourceException e){
            ///CLOVER:OFF
            return UScript.INVALID_CODE;
            ///CLOVER:ON
        }
    }
151590
function generateCode(filepath) {
    var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd';


    // support 4 types of output as follows:
    // amd/commonjs/global/umd
    var choice = {
        amd: {
            prefix: 'define([\'module\', \'exports\'], function (module, exports) {',
            suffix: '});'
        },
        commonjs: {
            prefix: '',
            suffix: ''
        },
        global: {
            prefix: '(function (module, exports) {',
            suffix: '})(this, this.exports = this.exports || {});'
        },
        umd: {
            prefix: '\n                (function (global, factory) {\n                    typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n                    typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n                    (factory(global, global.exports = global.exports || {}));\n                }(this, (function (module, exports) {\n            ',
            suffix: '})));'

        }
    };

    var _ref = choice[mode] || choice.amd,
        prefix = _ref.prefix,
        suffix = _ref.suffix;
    //const content = readFileSync(filepath, 'utf8');
    //const result = parseComponent(content);


    var result = getBlocks(filepath);
    var templateCode = result.template.code;
    var styleCode = result.styles.map(function (style) {
        return (0, _style2.default)(style.code);
    }).join('\n');
    var scriptCode = result.script.code;

    var code = '\n        ' + prefix + '\n            /* append style */\n            ' + styleCode + '\n\n            /* get render function */\n            var _module1 = {\n                exports: {}\n            };\n            (function (module, exports) {\n                ' + (0, _template2.default)(templateCode) + '\n            })(_module1, _module1.exports);\n\n            /* get script output data */\n            var _module2 = {\n                exports: {}\n            };\n            (function (module, exports) {\n                ' + (0, _script2.default)(scriptCode) + '\n            })(_module2, _module2.exports);\n\n            var obj = _module2.exports.default || _module2.exports;\n            obj.render = _module1.exports.render;\n            obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n            module.exports = obj;\n        ' + suffix + '\n    ';

    return (0, _jsBeautify.js_beautify)(code);
}
1053852
function outputClassBody( code ) {
    try {
        let out = '';
        if ( code.that ) out += "        const that = this;\n";
        if ( code.pm ) out += "        const pm = PM(this);\n";
        out += generate( code.section.attribs.define, "Create attributes", "        " );
        out += generate( code.section.elements.define, "Create elements", "        " );
        out += generate( code.section.events, "Events", "        " );
        out += arrayToCodeWithNewLine( code.generateLinks(), "        " );
        out += generate( code.section.ons, "On attribute changed", "        " );
        out += generate( code.section.elements.init, "Initialize elements", "        " );
        out += generate( code.section.attribs.init, "Initialize attributes", "        " );
        if ( code.section.init ) {
            out += "        // Initialization.\n";
            out += `        CODE_BEHIND.${code.section.init}.call( this );\n`;
        }
        out += "        $.addClass(this, 'view', 'custom');\n";
        return out;
    } catch ( ex ) {
        bubble( ex, "outputClassBody" );
        return null;
    }
}
403090
function render(code, data) {
  var js = '```js' + code + '```'
  return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script>
(function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)}))
})()</script></div></div>`
}
426749
function (moduleName) {
                var found, args, mod,
                    shim = config.shim[moduleName] || {},
                    shExports = shim.exports;

                takeGlobalQueue();

                while (defQueue.length) {
                    args = defQueue.shift();
                    if (args[0] === null) {
                        args[0] = moduleName;
                        //If already found an anonymous module and bound it
                        //to this name, then this is some other anon module
                        //waiting for its completeLoad to fire.
                        if (found) {
                            break;
                        }
                        found = true;
                    } else if (args[0] === moduleName) {
                        //Found matching define call for this script!
                        found = true;
                    }

                    callGetModule(args);
                }

                //Do this after the cycle of callGetModule in case the result
                //of those calls/init calls changes the registry.
                mod = registry[moduleName];

                if (!found && !defined[moduleName] && mod && !mod.inited) {
                    if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
                        if (hasPathFallback(moduleName)) {
                            return;
                        } else {
                            return onError(makeError('nodefine',
                                             'No define call for ' + moduleName,
                                             null,
                                             [moduleName]));
                        }
                    } else {
                        //A script that does not call define(), so just simulate
                        //the call for it.
                        callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
                    }
                }

                checkLoaded();
            }
1227890
def generate(module_name, code):
    
    try:
        ast_tree = ast.parse(code)
    except Exception:
        raise RuntimeError('Bad Python code')

    visitor = SearchSpaceGenerator(module_name)
    try:
        visitor.visit(ast_tree)
    except AssertionError as exc:
        raise RuntimeError('%d: %s' % (visitor.last_line, exc.args[0]))
    return visitor.search_space, astor.to_source(ast_tree)
341524
function compile(code, filename, options) {
  options = defaults(options || {}, {
    embedSourceMaps: true,
    bareModule: false,
    color: false
  });
  if (arguments.length !== compile.length) {
    throw new Error("incorrect argument count to compile");
  }
  var result = parse(ensureNewline(code));
  if (!result.status) {
    var expectations = uniq(result.expected);
    var data = "expected one of " + expectations.join(", ");
    var index = Math.min(result.index, code.length - 1);
    var oopsyInput = {index: index, data: data};
    var oopsies =
      OopsyData.fromIndices(code, [oopsyInput], {color: options.color});
    return {
      parsed: false,
      result: {
        expectations: expectations,
        oopsy: oopsies[0]
      }
    };
  }
  var squiggleAst = result.value;
  squiggleAst.bareModule = options.bareModule;
  var warnings = lint(squiggleAst);
  var contextualWarnings =
    OopsyData.fromLocations(code, warnings, {color: options.color});
  var esAst = transformAst(squiggleAst);
  var mangledAst = SHOULD_MANGLE ?
    esmangle.optimize(esAst) :
    esAst;
  var optimizedAst = SHOULD_OPTIMIZE ?
    optimize(mangledAst) :
    mangledAst;
  var stuff = generateCodeAndSourceMap(
    optimizedAst, filename, code);
  var js = ensureNewline(stuff.code);
  var sourceMap = stuff.map.toString();
  if (options.embedSourceMaps) {
    js = addSourceMapUrl(js, sourceMap);
  }
  return {
    parsed: true,
    warnings: contextualWarnings,
    sourceMap: sourceMap,
    code: js
  };
}
380330
function CodeMap() {
    /**
     * Dynamic code entries. Used for JIT compiled code.
     */
    this.dynamics_ = new tr.e.importer.v8.SplayTree();

    /**
     * Name generator for entries having duplicate names.
     */
    this.dynamicsNameGen_ = new tr.e.importer.v8.CodeMap.NameGenerator();

    /**
     * Static code entries. Used for statically compiled code.
     */
    this.statics_ = new tr.e.importer.v8.SplayTree();

    /**
     * Libraries entries. Used for the whole static code libraries.
     */
    this.libraries_ = new tr.e.importer.v8.SplayTree();

    /**
     * Map of memory pages occupied with static code.
     */
    this.pages_ = [];
  }
859548
function convertCode2Script(code) {
    // clean source code comment
    return code
        .replace(/\/\/\/ <reference path="[\s\S]*?>/gm, '')
        .replace(/\r\n/gm, '\n')
        .replace(convert.mapFileCommentRegex, '')
        .trim('\n') + '\n';
}
1252043
function generateApplicationCode(swagger, codegenOptions) {
  debug('Generating application code.');

  // Build up the execution parameters for the templates.
  const templateFunc = codegenOptions.templateSet;
  const outputDirectory = codegenOptions.temporaryDirectory;
  const codegenSettings = defaults(
    templateFunc(codegenOptions.templateSettings),
    {
      output: (name, content) => {
        const fullName = path.join(outputDirectory, name);
        const parsed = path.parse(fullName);
        mkdirp.sync(parsed.dir);
        fs.writeFileSync(fullName, content);
      },
      swagger: JSON.parse(JSON.stringify(swagger)), // Clone to avoid issues
    });

  // Perform the actual code generation
  codegen(codegenSettings);
}
663363
function ModuleGraph(moduleData) {
  var self = this;
  var modules = {};
  var moduleNameList = [];
  moduleData.forEach(function(info) {
    var m = new Module(info);
    modules[info.name] = m;
    moduleNameList.push(info.name);
  });

  /**
   * Get a list of all module names.
   * @return {Array.<string>} List of module names.
   */
  this.getAllModules = function() {
    return moduleNameList;
  };

  /**
   * Get transitive dependencies for a given module
   * @param {string} name Name of the module.
   * @return {Array.<string>} List of module names.
   */
  this.getTransitiveDependencies = function(name) {
    var m = getModule(name);
    return m.transitiveDeps || [];
  };

  function getModule(name) {
    var m = modules[name];
    if (!m) {
      throw new self.NotFoundException(name);
    }
    return m;
  }

  /**
   * Error object used when a requested module cannot be found.
   * @constructor
   */
  this.NotFoundException = function(name) {
    var msg = 'Unknown module: ' + name;
    this.name = name;
    this.message = msg;
    Error.call(this, msg);
  };
  this.NotFoundException.prototype = new Error();
  this.NotFoundException.prototype.statusCode = 404;

  /**
   * Gets the requested module names and their transitive deps minus the
   * transitive deps (and the) of the optional excluded names.
   * @param {Array.<string>} moduleNames List of module names.
   * @apram {Array.<string>} opt_excludeNames List of module names to exclude.
   * @return {Array.<string>} List of module names.
   */
  this.getModules = function(moduleNames, opt_excludeNames) {
    var list = [];
    var seen = {};
    var exclude = {};

    if (opt_excludeNames) {
      opt_excludeNames.forEach(function(name) {
        exclude[name] = true;
        var m = getModule(name);
        m.transitiveDeps.forEach(function(name) {
          exclude[name] = true;
        });
      });
    }

    function addModule(name) {
      if (!seen[name] && !exclude[name]) {
        seen[name] = true;
        list.push(name)
      }
    }
    moduleNames.forEach(function(name) {
      var m = getModule(name);
      m.transitiveDeps.forEach(addModule);
      addModule(m.name);
    });
    return list;
  };
}
1248254
public String[] generateCodes(final String code, final String objectName) {
        return generateCodes(code, objectName, null, null);
    }
674581
function generateDoc (name, code) {
  // get block comment from code
  const match = /\/\*\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//.exec(code)

  if (!match) {
    return null
  }

  // get text content inside block comment
  const comment = match[0].replace('/**', '')
    .replace('*/', '')
    .replace(/\n\s*\* ?/g, '\n')
    .replace(/\r/g, '')

  const lines = comment.split('\n')
  let line = ''

  // get next line
  function next () {
    line = lines.shift()
  }

  // returns true if current line is empty
  function empty () {
    return !line || !line.trim()
  }

  // returns true if there still is a current line
  function exists () {
    return line !== undefined
  }

  // returns true if current line is a header like 'Syntax:'
  function isHeader () {
    return /^(Name|Syntax|Description|Examples|See also)/i.test(line)
  }

  // returns true if the current line starts with an annotation like @param
  function isAnnotation () {
    return /^@/.test(line)
  }

  function skipEmptyLines () {
    while (exists() && empty()) next()
  }

  function stripLeadingSpaces (lines) {
    let spaces = null
    lines.forEach(function (line) {
      const match = /^ +/.exec(line)
      const s = match && match[0] && match[0].length
      if (s > 0 && (spaces === null || s < spaces)) {
        spaces = s
      }
    })

    if (spaces) {
      lines.forEach(function (line, index) {
        lines[index] = line.substring(spaces)
      })
    }
  }

  function parseDescription () {
    let description = ''

    while (exists() && !isHeader() && !isAnnotation()) {
      description += line + '\n'

      next()
    }

    // remove trailing returns
    while (description.charAt(description.length - 1) === '\n') {
      description = description.substring(0, description.length - 1)
    }

    doc.description = description
  }

  function parseSyntax () {
    if (/^syntax/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        doc.syntax.push(line)
        next()
      }
      stripLeadingSpaces(doc.syntax)

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseWhere () {
    if (/^where/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        doc.where.push(line)
        next()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseExamples () {
    if (/^example/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && (empty() || line.charAt(0) === ' ')) {
        doc.examples.push(line)
        next()
      }
      stripLeadingSpaces(doc.examples)

      if (doc.examples.length > 0 && doc.examples[doc.examples.length - 1].trim() === '') {
        doc.examples.pop()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseSeeAlso () {
    if (/^see also/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        const names = line.split(',')
        doc.seeAlso = doc.seeAlso.concat(names.map(function (name) {
          return name.trim()
        }))
        next()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function trim (text) {
    return text.trim()
  }

  // replace characters like '<' with HTML entities like '&lt;'
  function escapeTags (text) {
    return text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
  }

  function parseParameters () {
    let count = 0
    let match
    do {
      match = /\s*@param\s*\{(.*)}\s*\[?(\w*)]?\s*(.*)?$/.exec(line)
      if (match) {
        next()

        count++
        const annotation = {
          name: match[2] || '',
          description: (match[3] || '').trim(),
          types: match[1].split('|').map(trim).map(escapeTags)
        }
        doc.parameters.push(annotation)

        // TODO: this is an ugly hack to extract the default value
        const index = annotation.description.indexOf(']')
        let defaultValue = null
        if (index !== -1) {
          defaultValue = annotation.description.substring(1, index).trim()
          annotation.description = annotation.description.substring(index + 1).trim()
        }

        // multi line description (must be non-empty and not start with @param or @return)
        while (exists() && !empty() && !/^\s*@/.test(line)) {
          const lineTrim = line.trim()
          const separator = (lineTrim[0] === '-' ? '</br>' : ' ')
          annotation.description += separator + lineTrim
          next()
        }

        if (defaultValue !== null) {
          annotation.description += ' Default value: ' + defaultValue + '.'
        }
      }
    } while (match)

    return count > 0
  }

  function parseReturns () {
    const match = /\s*@returns?\s*\{(.*)}\s*(.*)?$/.exec(line)
    if (match) {
      next()

      doc.returns = {
        description: match[2] || '',
        types: match[1].split('|').map(trim).map(escapeTags)
      }

      // multi line description
      while (exists() && !empty() && !/^\s*@/.test(line)) {
        doc.returns.description += ' ' + line.trim()
        next()
      }

      return true
    }
    return false
  }

  // initialize doc
  let doc = {
    name: name,
    description: '',
    syntax: [],
    where: [],
    examples: [],
    seeAlso: [],
    parameters: [],
    returns: null
  }

  next()
  skipEmptyLines()
  parseDescription()

  do {
    skipEmptyLines()

    const handled = parseSyntax() ||
        parseWhere() ||
        parseExamples() ||
        parseSeeAlso() ||
        parseParameters() ||
        parseReturns()

    if (!handled) {
      // skip this line, no one knows what to do with it
      next()
    }
  } while (exists())

  return doc
}
471555
function generateLayers () {
			grunt.log.write("Generating layers...");

			var config = lang.extend({}, requireConfig, {
				isPrepareStage: true,
				optimize: "none",
				optimizeCss: "none",
				appDir: buildDir,
				dir: tempDir,
				baseUrl: "./",
				logLevel: 2, // WARN
				removeCombined: false,
				skipDirOptimize: true,
				keepBuildDir: false,
				skipSemiColonInsertion: true,
				pragmas: {
					prepare: true,
					build: true
				},
				// Pragmas for rjs plugins:
				pragmasOnSave: {
					prepareSave: true
				},
				// main (root) modules:
				modules: modules.map(function (module) { return { name: module }; }),
				onBuildWrite: function (moduleName, modulePath, contents) {
					// put moduleName into some layer basing on its path
					layers.some(function (layer) {
						var relPath = path.relative(path.resolve(config.dir), modulePath);
						var layerDir = layer.dir;
						if (!Array.isArray(layerDir)) {
							layerDir = [layerDir];
						}
						layerDir.forEach(function(dir) {
							if (relPath.indexOf(dir) === 0) {
								if (options.ignoreModules) {
									if (options.ignoreModules.some(function (m) {
										return m === moduleName;
									})) {
										return;
									}
								}
								layer.modules[moduleName] = true;
							}
						});
					});
					if (moduleName.indexOf('xhtmpl!') === 0) {
						modulesToDelete.push(path.join(outputDir, modulePath.slice('xhtmpl!'.length)));

						// Manually save pre-compiled template back into buildDir as
						// we're currently saving into tempDir (that's why we can't rely on returning content)

						// NOTE: manually remove leading semicolon
						// TODO: the code should be removed after migrating on 2.1.9 (with skipSemiColonInsertion support)
						if (contents.charAt(contents.length-1) === ";") {
							contents = contents.slice(0, contents.length-1);
						}
						file.saveFile(path.join(buildDir, modulePath.slice('xhtmpl!'.length)), contents);
					}
					//return contents;
					return "// this is a stub for finding layer's dependencies: moduleName=" + moduleName;
				}
			});

			requirejs.optimize(
				config,
				lang.safeCallback(function () {
					// create layer modules using 'layers' structure created in onBuildWrite:
					// every 'layer module' is an empty RJS module with imports (via define([..])) of all modules inside this layer
					layers.forEach(function (layer) {
						var modules = Object.keys(layer.modules).sort(),
							content = "define([\n\t\"" + modules.join("\",\n\t\"") + "\"\n], function () {});";
						file.saveFile(path.join(buildDir, layer.name) + ".js", content);
					});

					grunt.log.writeln('OK'.green);

					// Go to next step
					optimizeModules();
				}),
				lang.errorCallback
			);
		}
779903
function(element) {
			var moduleName = getModuleName(element),
				moduleData = modules[moduleName],
				instanceData,
				context,
				module;

			if (!moduleData) {
				error(new Error('Module type "' + moduleName + '" is not defined.'));
				return;
			}

			if (!this.isStarted(element)) {
				// Auto-assign module id to element
				if (!element.id) {
					element.id = 'mod-' + moduleName + '-' + moduleData.counter;
				}

				moduleData.counter++;

				context = new Box.Context(this, element);

				module = moduleData.creator(context);

				// Prevent errors from showing the browser, fire event instead
				if (!globalConfig.debug) {
					captureObjectErrors(module, moduleName);
				}

				instanceData = {
					moduleName: moduleName,
					instance: module,
					context: context,
					element: element,
					eventHandlers: {}
				};

				bindEventListeners(instanceData);

				instances[element.id] = instanceData;

				callModuleMethod(instanceData.instance, 'init');

				var moduleBehaviors = getBehaviors(instanceData),
					behaviorInstance;

				for (var i = 0, len = moduleBehaviors.length; i < len; i++) {
					behaviorInstance = moduleBehaviors[i];
					callModuleMethod(behaviorInstance, 'init');
				}

			}
		}
609412
function generateCodeEntryJs (config) {

	// Read the entry point script
	var entry_js = null;
	try {
		// Read from current script
		entry_js = fs.readFileSync(ENTRY_POINT_FILENAME).toString();
	} catch (e) {
		// Read from template script
		entry_js = fs.readFileSync(__dirname + '/../templates/' + ENTRY_POINT_FILENAME + '.tmpl').toString() + '\n';
	}

	return entry_js;

}