converts comma-separated name/value pairs into expression/variable bindings
335932
public static Map<String, String> toBindMap(String expression) {
    if (Strings.empty(expression))
      return Collections.emptyMap();

    Deque<Character> escapes = new ArrayDeque<Character>();
    List<String> pairs = new ArrayList<String>();
    int index = 0;
    for (int i = 0; i < expression.length(); i++) {
      char c = expression.charAt(i);

      if (('"' == c && (escapes.isEmpty() || escapes.peek().charValue() != c))
          || '[' == c || '{' == c || '(' == c) {
        escapes.push(c);
      } else if (('"' == c && escapes.peek().charValue() == c) || ']' == c || '}' == c || ')' == c) {
        escapes.pop();
      }

      if (escapes.isEmpty() && ',' == c) {
        if (index < i)
          pairs.add(expression.substring(index, i));

        //skip comma & whitespace if any
        for (; i < expression.length() && (',' == expression.charAt(i) || ' ' == expression.charAt(i));)
          i++;

        //reset new start index
        index = i;
      }

    }

    //add last pair if needed
    if (index < expression.length()) {

      //chew up leading comma & whitespace if any
      //noinspection StatementWithEmptyBody
      for (; ',' == expression.charAt(index) || ' ' == expression.charAt(index); index++) ;

      final String pair = expression.substring(index, expression.length()).trim();

      //only consider this a pair if it has something in it!
      if (pair.length() > 1)
        pairs.add(pair);
    }

    //nice to preserve insertion order
    final Map<String, String> map = new LinkedHashMap<String, String>();
    for (String pair : pairs) {
      final String[] nameAndValue = pair.split("=", 2);

      //do some validation
      if (nameAndValue.length != 2)
        throw new IllegalArgumentException("Invalid parameter binding format: " + pair);

      Strings.nonEmpty(nameAndValue[0], "Cannot have an empty left hand side target parameter: " + pair);
      Strings.nonEmpty(nameAndValue[1], "Must provide a non-empty right hand side expression: " + pair);

      map.put(nameAndValue[0].trim(), nameAndValue[1].trim());
    }

    return Collections.unmodifiableMap(map);
  }
582008
private Map<String, String> convertToMap(Object expression) {
        if (expression instanceof Map) {
            return (Map<String, String>) expression;
        }

        return Stream.of(Optional.ofNullable(expression)
                .map(Object::toString)
                .orElse("")
                .split(","))
                .map(keyValue -> Optional.ofNullable(StringUtils.split(keyValue, "=")).orElse(new String[] {keyValue, ""}))
                .collect(Collectors.toMap(keyValue -> keyValue[0], keyValue -> keyValue[1]));
    }
520350
def _transform(self, var):
        '''  '''
        self.collection.variables.pop(var.name)
        return var.values
922850
function templateLiteralToStringConcat(node, sourceCode) {
    const ss = []
    node.quasis.forEach((q, i) => {
        const value = q.value.cooked
        if (value) {
            ss.push(JSON.stringify(value))
        }

        if (i < node.expressions.length) {
            const e = node.expressions[i]
            const text = sourceCode.getText(e)
            ss.push(text)
        }
    })
    if (!ss.length || !isStringLiteralCode(ss[0])) {
        ss.unshift(`""`)
    }
    return ss.join("+")
}
786299
function getLexicalBindingNames(tree) {
  let names = new StringSet();
  if (tree !== null && tree.type === VARIABLE_DECLARATION_LIST &&
      tree.declarationType !== VAR) {
    let visitor = new FindNames(names);
    for (let i = 0; i < tree.declarations.length; i++) {
      visitor.visitAny(tree.declarations[i].lvalue);
    }
  }
  return names;
}
325855
public static String toVariableName(Object o) throws PageException {
	String str = toString(o);
	if (!Decision.isVariableName(str)) throw new ExpressionException("can't cast [" + str + "] to variable name value");
	return str;
    }
612677
function getFormattedValues (formatString, rawValues) {
      var formattedValueString = formatString;
      var rawValuesLength = rawValues.length;

      for (var i = 0; i < rawValuesLength; i++) {
        formattedValueString = formattedValueString.replace(
          VALUE_PLACEHOLDER, +rawValues[i].toFixed(4));
      }

      return formattedValueString;
    }
1134197
function(string, variables, shouldWrap) {
			var instance = this;

			return string.replace(INTERPOLATION_MATCHER, function(variable, variableName) {
				var value;

				// Either return the variable value or the original expression if it doesn't exist
				if (variables[variableName] !== undefined) {
					value = variables[variableName];
				} else if (process.env[variableName] !== undefined) {
					value = process.env[variableName];
				}

				if (value !== undefined) {
					if (shouldWrap) {
						// Escape all double quotes and wrap the value in double quotes
						return instance._wrap(variables[variableName]);
					}

					return value;
				}

				return variable;
			});
		}
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
319603
def _parse_variable(s: str, curr_row: int, curr_col: int) -> Tuple:
        '''
        
        '''

        def parse_expression(ss, curr_row, curr_col):
            ss = ss.replace('$row', str(curr_row))
            ss = ss.replace('$col', str(curr_col))
            ss = ExcelExtractor._re_row_identifier.sub(
                lambda x: str(ExcelExtractor._row_name_to_num(x.group()[1:])) if len(x.group()) > 0 else '', ss)
            ss = ExcelExtractor._re_col_identifier.sub(
                lambda x: str(ExcelExtractor._col_name_to_num(x.group()[1:])) if len(x.group()) > 0 else '', ss)
            return eval(ss)

        ss = s.split(',')
        if len(ss) == 1:
            return parse_expression(ss[0], curr_row, curr_col),
        elif len(ss) == 2:
            rr, cc = (ss[1], ss[0])
            return parse_expression(rr, curr_row, curr_col), parse_expression(cc, curr_row, curr_col)
        else:
            raise ValueError('Invalid variable')
1184048
public String encode(String... values) {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    int i = 0;
    for (String value : values) {
      builder.put("$" + i++, value);
    }
    // We will get an error if there are named bindings which are not reached by values.
    return instantiate(builder.build());
  }
235868
public Object eval(Bindings bindings, String expression) throws ScriptException {
    CompiledScript compiledExpression = requireNonNull(expressions.get(expression));
    Object returnValue = compiledExpression.eval(bindings);
    return convertNashornValue(returnValue);
  }
821714
private static String formatParameterValueAsUnescapedVariableTemplate(final Object parameterValue) {
        // Get the value
        if (parameterValue == null) { // If null (= NO_VALUE), empty String
            return "";
        }
        // If it is not multivalued (e.g. non-List) simply escape and return
        if (!(parameterValue instanceof List<?>)) {
            return parameterValue.toString();
        }
        // It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)
        final List<?> values = (List<?>)parameterValue;
        final int valuesLen = values.size();
        final StringBuilder strBuilder = new StringBuilder(valuesLen * 16);
        for (int i = 0; i < valuesLen; i++) {
            final Object valueItem = values.get(i);
            if (strBuilder.length() > 0) {
                strBuilder.append(',');
            }
            strBuilder.append(valueItem == null? "" : valueItem.toString());
        }
        return strBuilder.toString();
    }
660881
def _vars_match(self):
        """"""
        return re.compile(
            r'#([A-Za-z]+)'  # match literal (#App) at beginning of String
            r':([\d]+)'  # app id (:7979)
            r':([A-Za-z0-9_\.\-\[\]]+)'  # variable name (:variable_name)
            r'!(StringArray|BinaryArray|KeyValueArray'  # variable type (array)
            r'|TCEntityArray|TCEnhancedEntityArray'  # variable type (array)
            r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity'  # variable type
            r'|(?:(?!String)(?!Binary)(?!KeyValue)'  # non matching for custom
            r'(?!TCEntity)(?!TCEnhancedEntity)'  # non matching for custom
            r'[A-Za-z0-9_-]+))'  # variable type (custom)
        )
1120802
function parseUnnamedCondition( $funcName, &$args, $tpl, &$text, &$text_len, &$cur_pos,
                                    $relatedTemplateName, $startLine, $startColumn, $rootNamespace )
    {
        $cond = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $text, $cur_pos, $cur_pos, $text_len, $rootNamespace );
        if ( !count( $cond ) )
        {
            $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                          $funcName, 'Not enough arguments' );
            return;

        }
        $args['condition'] = $cond;
    }
425840
def _var_strings(self, v_name, v_values, v_idx=None, v_start=None):
        """"""
        if self.uppercase:
            v_name = v_name.upper()

        var_strs = []

        # Parse a multidimensional array
        if is_nullable_list(v_values, list):
            if not v_idx:
                v_idx = []

            i_s = v_start[::-1][len(v_idx)] if v_start else None

            # FIXME: We incorrectly assume 1-based indexing if it is
            # unspecified.  This is necessary because our output method always
            # separates the outer axes to one per line.  But we cannot do this
            # if we don't know the first index (which we are no longer assuming
            # to be 1-based elsewhere).  Unfortunately, the solution needs a
            # rethink of multidimensional output.

            # NOTE: Fixing this would also clean up the output of todict(),
            # which is now incorrectly documenting unspecified indices as 1.

            # For now, we will assume 1-based indexing here, just to keep
            # things working smoothly.
            if i_s is None:
                i_s = 1

            for idx, val in enumerate(v_values, start=i_s):
                v_idx_new = v_idx + [idx]
                v_strs = self._var_strings(v_name, val, v_idx=v_idx_new,
                                           v_start=v_start)
                var_strs.extend(v_strs)

        # Parse derived type contents
        elif isinstance(v_values, Namelist):
            for f_name, f_vals in v_values.items():
                v_title = '%'.join([v_name, f_name])

                v_start_new = v_values.start_index.get(f_name, None)

                v_strs = self._var_strings(v_title, f_vals,
                                           v_start=v_start_new)
                var_strs.extend(v_strs)

        # Parse an array of derived types
        elif is_nullable_list(v_values, Namelist):
            if not v_idx:
                v_idx = []

            i_s = v_start[::-1][len(v_idx)] if v_start else 1

            for idx, val in enumerate(v_values, start=i_s):

                # Skip any empty elements in a list of derived types
                if val is None:
                    continue

                v_title = v_name + '({0})'.format(idx)

                v_strs = self._var_strings(v_title, val)
                var_strs.extend(v_strs)

        else:
            use_default_start_index = False
            if not isinstance(v_values, list):
                v_values = [v_values]
                use_default_start_index = False
            else:
                use_default_start_index = self.default_start_index is not None

            # Print the index range

            # TODO: Include a check for len(v_values) to determine if vector
            if v_idx or v_start or use_default_start_index:
                v_idx_repr = '('

                if v_start or use_default_start_index:
                    if v_start:
                        i_s = v_start[0]
                    else:
                        i_s = self.default_start_index

                    if i_s is None:
                        v_idx_repr += ':'

                    else:
                        i_e = i_s + len(v_values) - 1

                        if i_s == i_e:
                            v_idx_repr += '{0}'.format(i_s)
                        else:
                            v_idx_repr += '{0}:{1}'.format(i_s, i_e)
                else:
                    v_idx_repr += ':'

                if v_idx:
                    idx_delim = ', ' if self._index_spacing else ','
                    v_idx_repr += idx_delim
                    v_idx_repr += idx_delim.join(str(i) for i in v_idx[::-1])

                v_idx_repr += ')'

            else:
                v_idx_repr = ''

            # Split output across multiple lines (if necessary)

            val_strs = []

            val_line = ''
            for v_val in v_values:

                v_header = v_name + v_idx_repr + ' = '
                # Increase column width if the header exceeds this value
                if len(self.indent + v_header) >= self.column_width:
                    column_width = len(self.indent + v_header) + 1
                else:
                    column_width = self.column_width

                v_width = column_width - len(self.indent + v_header)

                if len(val_line) < v_width:
                    val_line += self._f90repr(v_val) + ', '

                if len(val_line) >= v_width:
                    val_strs.append(val_line.rstrip())
                    val_line = ''

            # Append any remaining values
            if val_line:
                val_strs.append(val_line.rstrip())

            if val_strs:
                if self.end_comma or v_values[-1] is None:
                    pass
                else:
                    val_strs[-1] = val_strs[-1][:-1]

            # Complete the set of values
            if val_strs:
                var_strs.append('{0}{1} = {2}'
                                ''.format(v_name, v_idx_repr,
                                          val_strs[0]).strip())

                for v_str in val_strs[1:]:
                    var_strs.append(' ' * len(v_header) + v_str)

        return var_strs
901207
function parseVariableDeclarations(string, syntax, options) {
  string = ignoreBlock.removeIgnoredBlocks(string);
  var parser = getParserForSyntax(syntax, options);
  if (parser) {
    return parser.parseVariableDeclarations(string);
  }
  return [];
}