/ This adapts XreadExpressions output to the format originally produced by readColumnNames
506669
private OrderedHashSet getSimpleColumnNames(java.util.List<Expression> indexExprs) {
        OrderedHashSet set = new OrderedHashSet();

        for (Expression expression : indexExprs) {
            if (expression instanceof ExpressionColumn) {
                String colName = ((ExpressionColumn)expression).columnName;
                if (!set.add(colName)) {
                    throw Error.error(ErrorCode.X_42577, colName);
                }
            } else {
                return null;
            }
        }

        return set;
    }
174691
private void XreadWithList(WithList withList) {
        // <with list element> ::= <query name>
        //                         [ <left paren> <with column list> <right paren> ]
        //                         AS <left paren> <query expression> <right paren>
        //                         [ <search or cycle clause> ]
        //
        boolean recursive = withList.isRecursive();
        for (boolean done = false; ! done; done = ! readIfThis(Tokens.COMMA)) {
            HsqlName queryName = readNewSchemaObjectName(SchemaObject.TABLE);
            queryName.setSchemaIfNull(session.getCurrentSchemaHsqlName());
            List<HsqlName> columnNames = parseColumnNames();
            readThis(Tokens.AS);
            readThis(Tokens.OPENBRACKET);
            // Read a query.  If it's recursive it has to be of the form:
            //    Q1 union all Q2.
            // In Q1 we can't use an order by or limit.  It's ok
            // to use group by, aggregates and having, though.  The
            // query name will be visible in Q2 but not in Q1.
            //
            // If this with statement is not recursive then anything goes,
            // but the query name will not be visible in the query.
            QueryExpression baseQueryExpression = null;
            QueryExpression recursionQueryExpression = null;
            // This is not really standard behavior.  This should
            // really be just reading a query expression.  However,
            // This short circuits a great deal of complexity, and
            // will serve for prototype purposes.
            if (recursive) {
                baseQueryExpression = XreadQueryPrimary();
            } else {
                baseQueryExpression = XreadQueryExpressionBodyAndSortAndSlice();
            }
            // We have to resolve this here because we need
            // to fetch the types and perhaps the column aliases.
            // But we can't define the table now, because it is
            // not visible in the base query expression.
            baseQueryExpression.resolve(session);
            //
            // Calculate the schema of the common table.
            //
            HsqlName[] colNames = null;
            if (columnNames != null) {
                colNames = columnNames.toArray(new HsqlName[columnNames.size()]);
            } else {
                String[] queryNames = baseQueryExpression.getColumnNames();
                colNames = new HsqlName[queryNames.length];
                for (int idx = 0; idx < queryNames.length; idx += 1) {
                    String queryColumnName = queryNames[idx];
                    colNames[idx] = database.nameManager.newHsqlName(queryColumnName,
                                                                     false,
                                                                     SchemaObject.COLUMN);
                }
            }
            Type[] colTypes = baseQueryExpression.getColumnTypes();
            String cmp = null;
            if (colNames.length > colTypes.length) {
                cmp = "many";
            }
            else if (colNames.length < colTypes.length) {
                cmp = "few";
            }
            if (cmp != null) {
                throw Error.error("Too " + cmp + " column names in common table expression " + queryName.name);
            }
            // Now, define it.
            Table newTable = session.defineLocalTable(queryName, colNames, colTypes);
            if (recursive) {
                readThis(Tokens.UNION);
                readThis(Tokens.ALL);
                recursionQueryExpression = XreadQueryExpressionBody();
            }
            readThis(Tokens.CLOSEBRACKET);
            WithExpression withExpression = new WithExpression();
            withExpression.setQueryName(queryName);
            withExpression.setBaseQuery(baseQueryExpression);
            withExpression.setRecursiveQuery(recursionQueryExpression);
            withExpression.setTable(newTable);
            withList.add(withExpression);
        }
    }
205570
protected String elementAsString(XMLStreamReader reader, String key, Map<String, String> expressions)
      throws XMLStreamException
   {
      String elementtext = rawElementText(reader);

      if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1)
         expressions.put(key, elementtext);
      
      return getSubstitutionValue(elementtext);
   }
1348694
Expression XreadUnsignedValueSpecificationOrNull() {

        Expression e;

        switch (token.tokenType) {

            case Tokens.TRUE :
                read();

                return Expression.EXPR_TRUE;

            case Tokens.FALSE :
                read();

                return Expression.EXPR_FALSE;

            case Tokens.DEFAULT :
                if (compileContext.contextuallyTypedExpression) {
                    read();

                    e = new ExpressionColumn(OpTypes.DEFAULT);

                    return e;
                }
                break;

            case Tokens.NULL :
                e = new ExpressionValue(null, null);

                read();

                return e;

            case Tokens.X_VALUE :
                e = new ExpressionValue(token.tokenValue, token.dataType);

                read();

                return e;

            case Tokens.X_DELIMITED_IDENTIFIER :
            case Tokens.X_IDENTIFIER :
                if (!token.isHostParameter) {
                    return null;
                }

            // $FALL-THROUGH$
            case Tokens.QUESTION :
                e = new ExpressionColumn(OpTypes.DYNAMIC_PARAM);

                compileContext.parameters.add(e);
                read();

                return e;

            case Tokens.COLLATION :
                return XreadCurrentCollationSpec();

            case Tokens.VALUE :
            case Tokens.CURRENT_CATALOG :
            case Tokens.CURRENT_DEFAULT_TRANSFORM_GROUP :
            case Tokens.CURRENT_PATH :
            case Tokens.CURRENT_ROLE :
            case Tokens.CURRENT_SCHEMA :
            case Tokens.CURRENT_TRANSFORM_GROUP_FOR_TYPE :
            case Tokens.CURRENT_USER :
            case Tokens.SESSION_USER :
            case Tokens.SYSTEM_USER :
            case Tokens.USER :
                FunctionSQL function =
                    FunctionSQL.newSQLFunction(token.tokenString,
                                               compileContext);

                if (function == null) {
                    return null;
                }

                return readSQLFunction(function);

            // read SQL parameter reference
        }

        return null;
    }
563605
private static String indexExpressionsToString(List<IndexExpression> indexExpressions) throws IOException
    {
        assert indexExpressions != null;
        // oh, you thought cfdefToString was awful?
        IndexClause indexClause = new IndexClause();
        indexClause.setExpressions(indexExpressions);
        indexClause.setStart_key("".getBytes());
        TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
        try
        {
            return Hex.bytesToHex(serializer.serialize(indexClause));
        }
        catch (TException e)
        {
            throw new IOException(e);
        }
    }
877722
private PExp readApplicatorExpression() throws ParserException,
			LexException
	{
		PExp exp = readBasicExpression();
		boolean more = true;

		while (more)
		{
			LexToken token = lastToken();

			switch (token.type)
			{
				case BRA:
					// Either sequence(from, ..., to) or func(args) or map(key)
					// or mk_*(), is_*(), mu(), pre_*(), post_*(),
					// init_*() or inv_*()

					if (nextToken().is(VDMToken.KET))
					{
						if (exp instanceof AVariableExp)
						{
							AVariableExp ve = (AVariableExp) exp;
							String name = ve.getName().getName();

							if (name.startsWith("mk_"))
							{
								// a mk_TYPE() with no field values
								exp = readMkExpression(ve);
								break;
							}
						}

						exp = AstFactory.newAApplyExp(exp);
						nextToken();
					} else
					{
						if (exp instanceof AVariableExp)
						{
							AVariableExp ve = (AVariableExp) exp;
							String name = ve.getName().getName();

							if (name.equals("mu"))
							{
								exp = readMuExpression(ve);
								break;
							} else if (name.startsWith("mk_"))
							{
								exp = readMkExpression(ve);
								break;
							} else if (name.startsWith("is_"))
							{
								exp = readIsExpression(ve);
								break;
							} else if (name.equals("pre_"))
							{
								exp = readPreExpression(ve);
								break;
							} else if (name.equals("narrow_"))
							{
								if (Settings.release == Release.CLASSIC)
								{
									throwMessage(2303, "Narrow not available in VDM classic", ve.getName());
								} else
								{
									exp = readNarrowExpression(ve);
								}
								break;
							}
						}

						// So we're a function/operation call, a list subsequence or
						// a map index...

						PExp first = readExpression();

						if (lastToken().is(VDMToken.COMMA))
						{
							reader.push();

							if (nextToken().is(VDMToken.RANGE))
							{
								nextToken();
								checkFor(VDMToken.COMMA, 2120, "Expecting 'e1,...,e2' in subsequence");
								PExp last = readExpression();
								checkFor(VDMToken.KET, 2121, "Expecting ')' after subsequence");
								reader.unpush();
								exp = AstFactory.newASubseqExp(exp, first, last);
								break;
							}

							reader.pop(); // Not a subsequence then...
						}

						// OK, so read a (list, of, arguments)...

						List<PExp> args = new NodeList<PExp>(null);
						args.add(first);

						while (ignore(VDMToken.COMMA))
						{
							args.add(readExpression());
						}

						checkFor(VDMToken.KET, 2122, "Expecting ')' after function args");
						exp = AstFactory.newAApplyExp(exp, args);
					}
					break;

				case SEQ_OPEN:
					// Polymorphic function instantiation
					List<PType> types = new Vector<PType>();
					TypeReader tr = getTypeReader();

					nextToken();
					types.add(tr.readType());

					while (ignore(VDMToken.COMMA))
					{
						types.add(tr.readType());
					}

					checkFor(VDMToken.SEQ_CLOSE, 2123, "Expecting ']' after function instantiation");
					exp = AstFactory.newAFuncInstatiationExp(exp, types);
					break;

				case POINT:
					// Field selection by name or number
					switch (nextToken().type)
					{
						case NAME:
							if (dialect != Dialect.VDM_SL)
							{
								exp = AstFactory.newAFieldExp(exp, lastNameToken());
							} else
							{
								throwMessage(2030, "Expecting simple field identifier");
							}
							break;

						case IDENTIFIER:
							exp = AstFactory.newAFieldExp(exp, lastIdToken());
							break;

						case HASH:
							if (nextToken().isNot(VDMToken.NUMBER))
							{
								throwMessage(2031, "Expecting field number after .#");
							}

							LexIntegerToken num = (LexIntegerToken) lastToken();
							exp = AstFactory.newAFieldNumberExp(exp, num);
							break;

						default:
							throwMessage(2032, "Expecting field name");
					}

					nextToken();
					break;

				default:
					more = false;
					break;
			}
		}

		// If we've collected as many applicators as we can, but we're still
		// just a variable, this is a bare variable expression. In VDM++, these
		// are always qualified (ie. x refers to C`x where it was declared, not
		// an overriding version lower down).

		if (exp instanceof AVariableExp)
		{
			AVariableExp ve = (AVariableExp) exp;
			ve.setName(ve.getName().getExplicit(true));
		}

		// Combinator Family. Right grouping.
		LexToken token = lastToken();

		if (token.is(VDMToken.COMP))
		{
			nextToken();
			return AstFactory.newACompBinaryExp(exp, token, readApplicatorExpression());
		}

		if (token.is(VDMToken.STARSTAR))
		{
			nextToken();
			return AstFactory.newAStarStarBinaryExp(exp, token, readEvaluatorP6Expression());
		}

		return exp;
	}
695209
Expression XreadSimpleValueSpecificationOrNull() {

        Expression e;

        switch (token.tokenType) {

            case Tokens.X_VALUE :
                e = new ExpressionValue(token.tokenValue, token.dataType);

                read();

                return e;

            case Tokens.QUESTION :
                e = new ExpressionColumn(OpTypes.DYNAMIC_PARAM);

                compileContext.parameters.add(e);
                read();

                return e;

            default :
                return null;
        }
    }
744659
private void resolveTableColumns(Table table) {
        HsqlList set = new HsqlArrayList();
        collectAllColumnExpressions(set);
        for (int i = 0; i < set.size(); i++) {
            ExpressionColumn array_element = (ExpressionColumn)set.get(i);
            ColumnSchema column = table.getColumn(table.getColumnIndex(array_element.getAlias()));
            array_element.setAttributesAsColumn(column, false);

        }
    }
844028
function translateFormat(formatString, mapping) {
  let len = formatString.length,
    i = 0,
    beginIndex = -1,
    lastChar = null,
    currentChar = "",
    resultString = "";

  for (; i < len; i++) {
    currentChar = formatString.charAt(i);

    if (lastChar === null || lastChar !== currentChar) {
      // change detected
      resultString = _appendMappedString(formatString, mapping, beginIndex, i, resultString);

      beginIndex = i;
    }

    lastChar = currentChar;
  }

  return _appendMappedString(formatString, mapping, beginIndex, i, resultString);
}
16580
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) {
        // get all the TVEs in the output columns
        int difftor = 0;
        for (SchemaColumn col : m_outputSchema) {
            col.setDifferentiator(difftor);
            ++difftor;
            Collection<TupleValueExpression> allTves =
                    ExpressionUtil.getTupleValueExpressions(col.getExpression());
            // and update their indexes against the table schema
            for (TupleValueExpression tve : allTves) {
                tve.setColumnIndexUsingSchema(inputSchema);
                assert (tve.getColumnIndex() >= 0 && tve.getColumnIndex() < inputSchema.size());
            }
        }
        // DON'T RE-SORT HERE
    }
847147
@Override
    public Object readFrom(Class<Object> c, Type t, Annotation[] anns, MediaType mt,
                           MultivaluedMap<String, String> headers, InputStream is) throws IOException, WebApplicationException {
        // TODO Auto-generated method stub
        //if Type t contains IAttachment, IMutibody, convert to Attachment, Mutibody to adapt CXF MultipartProvider.readFrom
        multipartProvider.setMessageContext(mc);
        ParameterizedType origType = null;
        Type[] actualType = null;
        if (ParameterizedType.class.isAssignableFrom(t.getClass())) {
            origType = (ParameterizedType) t;
            actualType = origType.getActualTypeArguments();
            for (int i = 0; i < actualType.length; i++) {
                if (actualType[i].equals(IAttachment.class)) {
                    actualType[i] = Attachment.class;
                } else if (actualType[i].equals(IMultipartBody.class)) {
                    actualType[i] = MultipartBody.class;
                }
            }

            if (actualType != null && origType != null) {
                t = IBMParameterizedTypeImpl.make(origType.getRawType().getClass(), actualType, origType.getOwnerType());
            }
        } else if (IMultipartBody.class.isAssignableFrom(getActualType(t, 0))) {
            t = MultipartBody.class;
        }
        if (IAttachment.class.equals(c)) {
            c = (Class<Object>) (Object) Attachment.class;
        } else if (IMultipartBody.class.equals(c)) {
            c = (Class<Object>) (Object) MultipartBody.class;
        }
        //add additional converting logic since the above converting doesn't work in personal build server.
        if ("com.ibm.websphere.jaxrs20.multipart.IAttachment".equals(c.getName())) {
            c = (Class<Object>) (Object) Attachment.class;
        } else if ("com.ibm.websphere.jaxrs20.multipart.IMultipartBody".equals(c.getName())) {
            c = (Class<Object>) (Object) MultipartBody.class;
        }
        Object object = multipartProvider.readFrom(c, t, anns, mt, headers, is);
        //if object contains Attachment/MultiBoday for CXF, convert to AttachmentImpl, MultipartBodyImpl for IBM
        //List Value type: DataHandler, DataSource, Attachment, only converty Attachment
        if (object instanceof List<?>) {
            List attList = (List) object;
            List<AttachmentImpl> attImplList;
            if (!attList.isEmpty()) {
                attImplList = new LinkedList<AttachmentImpl>();
                AttachmentImpl attImpl;
                for (Object obj : attList) {
                    if (obj != null && obj instanceof Attachment) {
                        attImpl = new AttachmentImpl((Attachment) obj);
                        attImplList.add(attImpl);
                    }
                }
                return attImplList;
            }
            return object;
        }
        //convert Map if contains Attachment, e.g. LinkedHashMap <a.getContentType().toString(),fromAttachment>, fromAttachment== List<>: DataHandler, DataSource, Attachment
        else if (object != null && Map.class.isAssignableFrom(object.getClass())) {
            Map<Object, Object> attMap = (Map) object;
            if (!attMap.isEmpty()) {
                for (Iterator it = attMap.entrySet().iterator(); it.hasNext();) {
                    Entry entrySet = (Entry) it.next();
                    if (entrySet.getValue() != null && List.class.isAssignableFrom(entrySet.getValue().getClass())) {
                        List attList = (List) entrySet.getValue();
                        List<AttachmentImpl> attImplList;
                        if (!attList.isEmpty()) {
                            attImplList = new LinkedList<AttachmentImpl>();
                            AttachmentImpl attImpl;
                            for (Object obj : attList) {
                                if (obj != null && Attachment.class.isAssignableFrom(obj.getClass())) {
                                    attImpl = new AttachmentImpl((Attachment) obj);
                                    attImplList.add(attImpl);
                                }
                            }
                            entrySet.setValue(attImplList);
                        }
                    }
                }
            }
            return attMap;
        }
        //if object is MultipartBody, convert to MultipartBodayImpl
        else if (object instanceof MultipartBody) {
            IMultipartBody imbody = new MultipartBodyImpl((MultipartBody) object);
            return imbody;
        }
        return object;
    }
550714
@Override
	public void caseASetCompSetExp(ASetCompSetExp node) throws AnalysisException
	{
		if (!proceed(node))
		{
			return;
		}

		handleMultipleBindConstruct(node, node.getBindings(), node.getFirst(), node.getPredicate());
	}
819529
private boolean markAsDeadCode(XExpression expression) {
		if (expression instanceof XBlockExpression) {
			final XBlockExpression block = (XBlockExpression) expression;
			final EList<XExpression> expressions = block.getExpressions();
			if (!expressions.isEmpty()) {
				markAsDeadCode(expressions.get(0));
				return true;
			}
		}
		if (expression != null) {
			error("Unreachable expression.", expression, null, IssueCodes.UNREACHABLE_CODE); //$NON-NLS-1$
			return true;
		}
		return false;
	}
27654
public static final void encodeColumn(ResponseWriter rw, UIComponent c, int span, int cxs, int csm, int clg,
			int offset, int oxs, int osm, int olg, String style, String sclass) throws IOException {

		rw.startElement("div", c);
		Map<String, Object> componentAttrs = new HashMap<String, Object>();

		if (c != null) {
			rw.writeAttribute("id", c.getClientId(), "id");
			Tooltip.generateTooltip(FacesContext.getCurrentInstance(), c, rw);
			componentAttrs = c.getAttributes();
		}

		StringBuilder sb = new StringBuilder();
		if (span > 0 || offset > 0) {
			if (span > 0) {
				sb.append(COLMD).append(span);
			}
			if (offset > 0) {
				if (span > 0) {
					sb.append(" ");
				}
				sb.append(OFFSET + offset);
			}
		}

		if (cxs > 0) {
			sb.append(" col-xs-").append(cxs);
		}
		if (componentAttrs.get("col-xs") != null && cxs == 0) {
			sb.append(" hidden-xs");
		}

		if (csm > 0) {
			sb.append(" col-sm-").append(csm);
		}
		if (componentAttrs.get("col-sm") != null && csm == 0) {
			sb.append(" hidden-sm");
		}

		if (clg > 0) {
			sb.append(" col-lg-").append(clg);
		}
		if (componentAttrs.get("col-lg") != null && clg == 0) {
			sb.append(" hidden-lg");
		}

		if (oxs > 0) {
			sb.append(" col-xs-offset-").append(oxs);
		}
		if (osm > 0) {
			sb.append(" col-sm-offset-").append(osm);
		}
		if (olg > 0) {
			sb.append(" col-lg-offset-").append(olg);
		}

		if (sclass != null) {
			sb.append(" ").append(sclass);
		}
		rw.writeAttribute("class", sb.toString().trim(), "class");
		if (style != null) {
			rw.writeAttribute("style", style, "style");
		}

		if (null != c) {
			Tooltip.activateTooltips(FacesContext.getCurrentInstance(), c);
		}
	}
1355075
protected XExpression _generate(XListLiteral literal, IAppendable it, IExtraLanguageGeneratorContext context) {
		appendReturnIfExpectedReturnedExpression(it, context);
		it.append("["); //$NON-NLS-1$
		boolean first = true;
		for (final XExpression value : literal.getElements()) {
			if (first) {
				first = false;
			} else {
				it.append(", "); //$NON-NLS-1$
			}
			generate(value, it, context);
		}
		it.append("]"); //$NON-NLS-1$
		return literal;
	}
1347486
@Override
    public String[] outputColumnNames() {
        List<String> l = transform(inputSchema).getColumnNames();
        return l.toArray(new String[l.size()]);
    }
263664
public AbstractExpression replaceWithTVE(
            Map<AbstractExpression, Integer> aggTableIndexMap,
            Map<Integer, ParsedColInfo> indexToColumnMap) {
        Integer ii = aggTableIndexMap.get(this);
        if (ii != null) {
            ParsedColInfo col = indexToColumnMap.get(ii);
            TupleValueExpression tve = new TupleValueExpression(
                    col.m_tableName, col.m_tableAlias,
                    col.m_columnName, col.m_alias,
                    this, ii);
            if (this instanceof TupleValueExpression) {
                tve.setOrigStmtId(((TupleValueExpression)this).getOrigStmtId());
            }
            // To prevent pushdown of LIMIT when ORDER BY references an agg. ENG-3487.
            if (hasAnySubexpressionOfClass(AggregateExpression.class)) {
                tve.setHasAggregate(true);
            }

            return tve;
        }

        AbstractExpression lnode = null;
        AbstractExpression rnode = null;
        if (m_left != null) {
            lnode = m_left.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
        }
        if (m_right != null) {
            rnode = m_right.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
        }

        ArrayList<AbstractExpression> newArgs = null;
        boolean changed = false;
        if (m_args != null) {
            newArgs = new ArrayList<>();
            for (AbstractExpression expr: m_args) {
                AbstractExpression ex = expr.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
                newArgs.add(ex);
                if (ex != expr) {
                    changed = true;
                }
            }
        }

        if (m_left != lnode || m_right != rnode || changed) {
            AbstractExpression resExpr = clone();
            resExpr.setLeft(lnode);
            resExpr.setRight(rnode);
            resExpr.setArgs(newArgs);
            return resExpr;
        }

        return this;
    }