Custom plugin to simulate macro expressions.
489016
function getTransformMacroExpressions(babelTemplate) {
  return {
    visitor: {
        StringLiteral(path) {
            const node = path.node;
            if (!node.macro) {
                // This has nothing to do with macros but it's necessary to prevent
                // Babel from escaping Unicode strings. See #784
                if (typeof node.value === "string") {
                    node.extra = {
                        raw: JSON.stringify(node.value),
                        rawValue: node.value,
                    };
                }
                return;
            }

            const DOLLAR_REGEX = /\$\d+/g;
            const buildArgs = {};
            const originalMacro = node.value;
            let macro = originalMacro;

            try {
                // Check if there are more placeholders than args, this may happen
                // if null optional arguments have been removed.
                let m = null;
                const placeholders = [];
                const args = node.args || [];

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    placeholders.push(parseInt(m[0].substr(1), 10));
                }

                if (placeholders.length > 0) {
                    const max = placeholders.reduce((x, y) => Math.max(x, y));
                    // If there're actually more args than placeholders (e.g `$0($1...)`), use the args length
                    const argsLength = Math.max(max + 1, args.length);
                    for (let i = 0; i < argsLength; i++) {
                        buildArgs["$" + String(i)] =
                            args[i] == null
                                ? { type: "NullLiteral" }
                                : args[i];
                    }
                }

                macro = macro
                    // Macro transformations, see http://fable.io/docs/interacting.html#emit-attribute
                    .replace(/\$(\d+)\.\.\./, (_, i) => {
                        const rep = [];
                        for (let j = parseInt(i, 10); j < args.length; j++) {
                            rep.push("$" + j);
                        }
                        return rep.join(",");
                    })
                    .replace(/\{\{\s*\$(\d+)\s*\?(.*?)\:(.*?)\}\}/g, (_, g1, g2, g3) => {
                        const i = parseInt(g1, 10);
                        return typeof args[i] === "object" && args[i].value ? g2 : g3;
                    })
                    .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, (_, g1, g2) => {
                        const i = parseInt(g2, 10);
                        return typeof args[i] === "object" && args[i].type !== "NullLiteral" ? g1 : "";
                    })
                    .replace(/\$(\d+)!/, (_, i) => {
                        const arg = args[parseInt(i, 10)]
                        return typeof arg === "object" && arg.type === "StringLiteral" ? arg.value : "";
                    });

                // Babel 7 throws error if there're unused arguments, remove them
                const actualArgs = [];
                const buildArgKeys = Object.keys(buildArgs);

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    actualArgs.push(m[0]);
                }
                for (const key of buildArgKeys) {
                    if (actualArgs.indexOf(key) < 0) {
                        delete buildArgs[key];
                    }
                }

                // console.log("MACRO 1", originalMacro);
                // console.log("MACRO 2", macro);
                // console.log("MACRO ARGS", buildArgs);

                const builtMacro = babelTemplate(macro, {
                    placeholderPattern: /^\$\d+$/,
                })(buildArgs);

                if (builtMacro != null) {
                    path.replaceWithMultiple(builtMacro);
                } else {
                    // Apparently if the macro is just a string, babel-template will fail
                    path.replaceWith({
                        type: "StringLiteral",
                        value: JSON.parse(macro),
                    });
                }
            } catch (err) {
                throw new Error(
                    "BABEL ERROR: Failed to parse macro: " + originalMacro + " -> " + macro + "\n" +
                    "MACRO ARGUMENTS: " + Object.keys(buildArgs).join() + "\n" +
                    err.message);
            }
        },
    },
  };
}
396154
def stringToExpression(s, types, context):
    
    old_ctx = expressions._context.get_current_context()
    try:
        expressions._context.set_new_context(context)
        # first compile to a code object to determine the names
        if context.get('truediv', False):
            flags = __future__.division.compiler_flag
        else:
            flags = 0
        c = compile(s, '<expr>', 'eval', flags)
        # make VariableNode's for the names
        names = {}
        for name in c.co_names:
            if name == "None":
                names[name] = None
            elif name == "True":
                names[name] = True
            elif name == "False":
                names[name] = False
            else:
                t = types.get(name, default_type)
                names[name] = expressions.VariableNode(name, type_to_kind[t])
        names.update(expressions.functions)
        # now build the expression
        ex = eval(c, names)
        if expressions.isConstant(ex):
            ex = expressions.ConstantNode(ex, expressions.getKind(ex))
        elif not isinstance(ex, expressions.ExpressionNode):
            raise TypeError("unsupported expression type: %s" % type(ex))
    finally:
        expressions._context.set_new_context(old_ctx)
    return ex
144075
function () {
    instance = this;

    parser = new FormulaParser(instance);

    instance.formulas = Formula;
    instance.matrix = new Matrix();

    instance.custom = {};

    if (rootElement) {
      instance.matrix.scan();
    }
  }
73356
void insertMacros(TokenList tokens ) {
        TokenList.Token t = tokens.getFirst();
        while( t != null ) {
            if( t.getType() == Type.WORD ) {
                Macro v = lookupMacro(t.word);
                if (v != null) {
                    TokenList.Token before = t.previous;
                    List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();
                    t = parseMacroInput(inputs,t.next);

                    TokenList sniplet = v.execute(inputs);
                    tokens.extractSubList(before.next,t);
                    tokens.insertAfter(before,sniplet);
                    t = sniplet.last;
                }
            }
            t = t.next;
        }
    }
401508
function() {    
    var self = this, vars, j;
    
    // If this editor needs to be rendered by a macro template
    if(this.template) {
      vars = this.getWatchedFieldValues();
      this.setValue(this.template(vars),false,true);
    }
    
    this._super();
  }
772660
function (macroName) {
            var res = this.macros[macroName];
            if (res == null) {
                res = {};
                this.macros[macroName] = res;
            }
            return res;
        }
1335326
def _construct_regex(cls, fmt):
        """"""
        return re.compile(fmt.format(**vars(cls)), flags=re.U)
723760
function compiler(dom, directive, data, ans){
    var fns = [];
    // autoRendering nodes parsing -> auto-nodes
    ans = ans || data && getAutoNodes(dom, data);
    if(data){
      var j, jj, cspec, n, target, nodes, itersel, node, inner;
      // for each auto-nodes
      while(ans.length > 0){
        cspec = ans[0].cspec;
        n = ans[0].n;
        ans.splice(0, 1);
        if(cspec.t === 'str'){
          // if the target is a value
          target = gettarget(n, cspec, false);
          setsig(target, fns.length);
          fns[fns.length] = wrapquote(target.quotefn, dataselectfn(cspec.prop));
        }else{
          // if the target is a loop
          itersel = dataselectfn(cspec.sel);
          target = gettarget(n, cspec, true);
          nodes = target.nodes;
          for(j = 0, jj = nodes.length; j < jj; j++){
            node = nodes[j];
            inner = compiler(node, false, data, ans);
            fns[fns.length] = wrapquote(target.quotefn, loopfn(cspec.sel, itersel, inner));
            target.nodes = [node];
            setsig(target, fns.length - 1);
          }
        }
      }
    }
    // read directives
    var target, dsel;
    for(var sel in directive){
      if(directive.hasOwnProperty(sel)){
        dsel = directive[sel];
        if(typeof(dsel) === 'function' || typeof(dsel) === 'string'){
          // set the value for the node/attr
          target = gettarget(dom, sel, false);
          setsig(target, fns.length);
          fns[fns.length] = wrapquote(target.quotefn, dataselectfn(dsel));
        }else{
          // loop on node
          loopgen(dom, sel, dsel, fns);
        }
      }
    }
        // convert node to a string
        var h = outerHTML(dom), pfns = [];
    // IE adds an unremovable "selected, value" attribute
    // hard replace while waiting for a better solution
        h = h.replace(/<([^>]+)\s(value\=""|selected)\s?([^>]*)>/ig, "<$1 $3>");

        // remove attribute prefix
        h = h.split(attPfx).join('');

    // slice the html string at "Sig"
    var parts = h.split( Sig ), p;
    // for each slice add the return string of
    for(var i = 1; i < parts.length; i++){
      p = parts[i];
      // part is of the form "fn-number:..." as placed there by setsig.
      pfns[i] = fns[ parseInt(p, 10) ];
      parts[i] = p.substring( p.indexOf(':') + 1 );
    }
    return concatenator(parts, pfns);
  }
949008
def parse_macro_params(token):
    
    try:
        bits = token.split_contents()
        tag_name, macro_name, values = bits[0], bits[1], bits[2:]
    except IndexError:
        raise template.TemplateSyntaxError(
            "{0} tag requires at least one argument (macro name)".format(
                token.contents.split()[0]))

    args = []
    kwargs = {}

    # leaving most validation up to the template.Variable
    # class, but use regex here so that validation could
    # be added in future if necessary.
    kwarg_regex = (
        r'^([A-Za-z_][\w_]*)=(".*"|{0}.*{0}|[A-Za-z_][\w_]*)$'.format(
            "'"))
    arg_regex = r'^([A-Za-z_][\w_]*|".*"|{0}.*{0}|(\d+))$'.format(
        "'")
    for value in values:
        # must check against the kwarg regex first
        # because the arg regex matches everything!
        kwarg_match = regex_match(
            kwarg_regex, value)
        if kwarg_match:
            kwargs[kwarg_match.groups()[0]] = template.Variable(
                # convert to a template variable here
                kwarg_match.groups()[1])
        else:
            arg_match = regex_match(
                arg_regex, value)
            if arg_match:
                args.append(template.Variable(arg_match.groups()[0]))
            else:
                raise template.TemplateSyntaxError(
                    "Malformed arguments to the {0} tag.".format(
                        tag_name))

    return tag_name, macro_name, args, kwargs
431205
private void translatePreconditionMacros(WyilFile.Decl.FunctionOrMethod declaration) {
		Tuple<WyilFile.Expr> invariants = declaration.getRequires();
		//
		for (int i = 0; i != invariants.size(); ++i) {
			// Construct fresh environment for this macro. This is necessary to
			// avoid name clashes with subsequent macros.
			GlobalEnvironment globalEnvironment = new GlobalEnvironment(declaration);
			LocalEnvironment localEnvironment = new LocalEnvironment(globalEnvironment);
			WyalFile.VariableDeclaration[] type = generatePreconditionParameters(declaration, localEnvironment);
			// Translate expression itself
			WyalFile.Stmt.Block clause = translateAsBlock(invariants.get(i), localEnvironment);
			// Capture any free variables. This is necessary to deal with any
			// variable aliases introduced by type test operators.
			clause = captureFreeVariables(declaration, globalEnvironment, clause);
			//
			Name ident = convert(declaration.getQualifiedName(), "_requires_" + i, declaration.getName());
			WyalFile.Declaration md = new WyalFile.Declaration.Named.Macro(ident, type, clause);
			allocate(md, invariants.get(i).getParent(WyilFile.Attribute.Span.class));
		}
	}
969887
function compile(name, edbml, options, macros, directives) {
	var result = compiler.compile(edbml, options, macros, directives);
	return assistant.declare(name, result);
}
1002416
function parser (inputs, output, plugins, cb) {
  var data = {
    charset: 'UTF-8',
    headers: DEFAULT_HEADERS,
    translations: {
      context: {}
    }
  }

  var defaultContext = data.translations.context

  var headers = data.headers
  headers['plural-forms'] = headers['plural-forms'] || DEFAULT_HEADERS['plural-forms']
  headers['content-type'] = headers['content-type'] || DEFAULT_HEADERS['content-type']

  var nplurals = /nplurals ?= ?(\d)/.exec(headers['plural-forms'])[1]

  inputs
    .forEach(function (file) {
      var resolvedFilePath = path.join(process.cwd(), file)
      var src = fs.readFileSync(resolvedFilePath, 'utf8')

      try {
        var ast = babelParser.parse(src, {
          sourceType: 'module',
          plugins: ['jsx'].concat(plugins)
        })
      } catch (e) {
        console.error(`SyntaxError in ${file} (line: ${e.loc.line}, column: ${e.loc.column})`)
        process.exit(1)
      }

      walk.simple(ast.program, {
        CallExpression: function (node) {
          if (functionNames.hasOwnProperty(node.callee.name) ||
            node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {
            var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name]
            var translate = {}

            var args = node.arguments
            for (var i = 0, l = args.length; i < l; i++) {
              var name = functionName[i]

              if (name && name !== 'count' && name !== 'domain') {
                var arg = args[i]
                var value = arg.value

                if (value) {
                  var line = node.loc.start.line
                  translate[name] = value
                  translate['comments'] = {
                    reference: file + ':' + line
                  }
                }

                if (name === 'msgid_plural') {
                  translate.msgstr = []
                  for (var p = 0; p < nplurals; p++) {
                    translate.msgstr[p] = ''
                  }
                }
              }
            }

            var context = defaultContext
            var msgctxt = translate.msgctxt

            if (msgctxt) {
              data.translations[msgctxt] = data.translations[msgctxt] || {}
              context = data.translations[msgctxt]
            }

            context[translate.msgid] = translate
          }
        }
      })
    })

  fs.writeFile(output, gettextParser.po.compile(data), function (err) {
    if (err) {
      cb(err)
    }
    cb(null)
  })
}
996259
def main():
    """"""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, insert_secnos,
                                process_tables, delete_secnos,
                                detach_attrs_table], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()
523134
protected function getMacroFunction($macro_func)
    {
        if (is_array($macro_func) && is_callable($macro_func)) {
            return new \ReflectionMethod($macro_func[0], $macro_func[1]);
        }

        if (is_object($macro_func) && is_callable($macro_func) && !$macro_func instanceof Closure) {
            return new \ReflectionMethod($macro_func, '__invoke');
        }

        return new \ReflectionFunction($macro_func);
    }
568910
def generate_highlight_subparser(subparsers):
    """"""
    parser = subparsers.add_parser(
        'highlight', description=constants.HIGHLIGHT_DESCRIPTION,
        epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter,
        help=constants.HIGHLIGHT_HELP)
    parser.set_defaults(func=highlight_text)
    utils.add_common_arguments(parser)
    parser.add_argument('-m', '--minus-ngrams', metavar='NGRAMS',
                        help=constants.HIGHLIGHT_MINUS_NGRAMS_HELP)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-n', '--ngrams', action='append', metavar='NGRAMS',
                       help=constants.HIGHLIGHT_NGRAMS_HELP)
    group.add_argument('-r', '--results', metavar='RESULTS',
                       help=constants.HIGHLIGHT_RESULTS_HELP)
    parser.add_argument('-l', '--label', action='append', metavar='LABEL',
                        help=constants.HIGHLIGHT_LABEL_HELP)
    utils.add_corpus_arguments(parser)
    parser.add_argument('base_name', help=constants.HIGHLIGHT_BASE_NAME_HELP,
                        metavar='BASE_NAME')
    parser.add_argument('output', metavar='OUTPUT',
                        help=constants.REPORT_OUTPUT_HELP)
132294
def synthesize(self, modules, use_string, x64, native):
        """"""
        # code_opts = CodeOpts(
        #     str.lower, None if use_string else hash_func,
        #     'reloc_delta', '->',
        #     True)
        # gen_opts = GenOpts('defs', transformed)
        print(hash_func)
        groups = group_by(modules, ends_with_punctuation)
        sources = self.make_source(groups, self.database)
        if sources:
            return stylify_files(
                {'defs.h': sources[0], 'init.c': sources[1]}
            )
        else:
            return ''
817364
def do_usemacro(parser, token):
    
    tag_name, macro_name, args, kwargs = parse_macro_params(token)
    try:
        macro = parser._macros[macro_name]
    except (AttributeError, KeyError):
        raise template.TemplateSyntaxError(
            "Macro '{0}' is not defined previously to the {1} tag".format(
                macro_name, tag_name))
    macro.parser = parser
    return UseMacroNode(macro, args, kwargs)