/*
Private methods parsing Unicode Locale Extension subtags.
Duplicated attributes/keywords will be ignored.
The input must be a valid extension subtags (excluding singleton).
16852
private void setUnicodeLocaleExtension(String subtags) {
        // wipe out existing attributes/keywords
        if (_uattributes != null) {
            _uattributes.clear();
        }
        if (_ukeywords != null) {
            _ukeywords.clear();
        }

        StringTokenIterator itr = new StringTokenIterator(subtags, LanguageTag.SEP);

        // parse attributes
        while (!itr.isDone()) {
            if (!UnicodeLocaleExtension.isAttribute(itr.current())) {
                break;
            }
            if (_uattributes == null) {
                _uattributes = new HashSet<CaseInsensitiveString>(4);
            }
            _uattributes.add(new CaseInsensitiveString(itr.current()));
            itr.next();
        }

        // parse keywords
        CaseInsensitiveString key = null;
        String type;
        int typeStart = -1;
        int typeEnd = -1;
        while (!itr.isDone()) {
            if (key != null) {
                if (UnicodeLocaleExtension.isKey(itr.current())) {
                    // next keyword - emit previous one
                    assert(typeStart == -1 || typeEnd != -1);
                    type = (typeStart == -1) ? "" : subtags.substring(typeStart, typeEnd);
                    if (_ukeywords == null) {
                        _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
                    }
                    _ukeywords.put(key, type);

                    // reset keyword info
                    CaseInsensitiveString tmpKey = new CaseInsensitiveString(itr.current());
                    key = _ukeywords.containsKey(tmpKey) ? null : tmpKey;
                    typeStart = typeEnd = -1;
                } else {
                    if (typeStart == -1) {
                        typeStart = itr.currentStart();
                    }
                    typeEnd = itr.currentEnd();
                }
            } else if (UnicodeLocaleExtension.isKey(itr.current())) {
                // 1. first keyword or
                // 2. next keyword, but previous one was duplicate
                key = new CaseInsensitiveString(itr.current());
                if (_ukeywords != null && _ukeywords.containsKey(key)) {
                    // duplicate
                    key = null;
                }
            }

            if (!itr.hasNext()) {
                if (key != null) {
                    // last keyword
                    assert(typeStart == -1 || typeEnd != -1);
                    type = (typeStart == -1) ? "" : subtags.substring(typeStart, typeEnd);
                    if (_ukeywords == null) {
                        _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
                    }
                    _ukeywords.put(key, type);
                }
                break;
            }

            itr.next();
        }
    }
313215
private static void decodeTag(String stringTag, Map<TagKey, TagValueWithMetadata> tags) {
    String keyWithValue;
    int firstPropertyIndex = stringTag.indexOf(TAG_PROPERTIES_DELIMITER);
    if (firstPropertyIndex != -1) { // Tag with properties.
      keyWithValue = stringTag.substring(0, firstPropertyIndex);
      // TODO(songya): support decoding tag properties.
    } else { // Tag without properties.
      keyWithValue = stringTag;
    }
    List<String> keyValuePair = TAG_KEY_VALUE_SPLITTER.splitToList(keyWithValue);
    checkArgument(keyValuePair.size() == 2, "Malformed tag " + stringTag);
    TagKey key = TagKey.create(keyValuePair.get(0).trim());
    TagValue value = TagValue.create(keyValuePair.get(1).trim());
    TagValueWithMetadata valueWithMetadata =
        TagValueWithMetadata.create(value, METADATA_UNLIMITED_PROPAGATION);
    tags.put(key, valueWithMetadata);
  }
943104
public void deserializeIncludeTagTypes(String s) {
        includeTagTypes = new HashMap<String, String>();
        if (S.isEmpty(s)) {
            return;
        }
        String[] sa = s.split(";");
        for (String s0 : sa) {
            String[] sa0 = s0.split(":");
            if (sa0.length != 2) {
                throw new IllegalArgumentException("Unknown include tag types string: " + s);
            }
            includeTagTypes.put(sa0[0], sa0[1]);
        }
    }
266241
function I18NHtmlParser(_htmlParser, _translations, _translationsFormat) {
	          this._htmlParser = _htmlParser;
	          this._translations = _translations;
	          this._translationsFormat = _translationsFormat;
	      }
856998
protected boolean parseUnknownField(
      CodedInputStream input,
      ExtensionRegistryLite extensionRegistry,
      int tag) throws IOException {
    return input.skipField(tag);
  }
891232
private static Locale parseLocale(final String str) {
        if (isISO639LanguageCode(str)) {
            return new Locale(str);
        }

        final String[] segments = str.split("_", -1);
        final String language = segments[0];
        if (segments.length == 2) {
            final String country = segments[1];
            if (isISO639LanguageCode(language) && isISO3166CountryCode(country) ||
                    isNumericAreaCode(country)) {
                return new Locale(language, country);
            }
        } else if (segments.length == 3) {
            final String country = segments[1];
            final String variant = segments[2];
            if (isISO639LanguageCode(language) &&
                    (country.length() == 0 || isISO3166CountryCode(country) || isNumericAreaCode(country)) &&
                    variant.length() > 0) {
                return new Locale(language, country, variant);
            }
        }
        throw new IllegalArgumentException("Invalid locale format: " + str);
    }
875537
public CLDR.Locale resolve(String languageTag) {
    MetaLocale meta = MetaLocale.fromLanguageTag(languageTag);
    return resolve(meta);
  }
1122176
private void parseLanguageMatchingFix(JsonObject root) {
    JsonObject node = resolve(root, "supplemental", "languageMatching", "written_new");
    JsonArray matches = node.getAsJsonArray("languageMatch");
    for (JsonElement element : matches) {
      JsonObject value = (JsonObject) element;
      String desired = string(value, "desired");
      String supported = string(value, "supported");
      Integer distance = Integer.parseInt(string(value, "distance"));
      boolean oneway = string(value, "oneway", null) != null;
      
      LanguageMatch match = new LanguageMatch(desired, supported, distance, oneway);
      languageMatching.languageMatches.add(match);
    }
    
    JsonObject variables = resolve(node, "matchVariable");
    for (Map.Entry<String, JsonElement> entry : variables.entrySet()) {
      String value = entry.getValue().getAsString();
      languageMatching.matchVariables.add(Pair.pair(entry.getKey(), value));
    }
    
    for (String code : string(node, "paradigmLocales").split("\\s+")) {
      languageMatching.paradigmLocales.add(code);
    }
  }
1374999
public static Locale parseLocale(String localeString) {
        if (localeString == null || localeString.length() == 0) {
            return Locale.getDefault();
        }
        localeString = localeString.trim();

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

        String language = "";
        String country = "";
        String variant = "";

        // language
        int start = 0;
        int index = localeString.indexOf("_");

        if (index >= 0) {
            language = localeString.substring(start, index).trim();

            // country
            start = index + 1;
            index = localeString.indexOf("_", start);

            if (index >= 0) {
                country = localeString.substring(start, index).trim();

                // variant
                variant = localeString.substring(index + 1).trim();
            } else {
                country = localeString.substring(start).trim();
            }
        } else {
            language = localeString.substring(start).trim();
        }

        return new Locale(language, country, variant);
    }
540526
@Override
	public String retrieveLocale(String lang) {
		String r = locales.get(lang);
		if (r == null) {
			try {
				URL u = getClass().getResource("/locales-" + lang + ".xml");
				if (u == null) {
					throw new IllegalArgumentException("Unable to load locale " +
							lang + ". Make sure you have a file called " +
							"'/locales-" + lang + ".xml' at the root of your " +
							"classpath. Did you add the CSL locale files to "
							+ "your classpath?");
				}
				r = CSLUtils.readURLToString(u, "UTF-8");
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			locales.put(lang, r);
		}
		return r;
	}
732757
private void extractAttributes(final String attributes)
	{
		String s = attributes.trim();
		if (s.length() > 0 && s.charAt(s.length() - 1) == '/')
			emptyTag = true;

		while (s.length() != 0) {
			final int equal = s.indexOf('=');
			if (equal == -1 || equal == s.length() - 1)
				break;
			// cut off attribute name
			final String att = s.substring(0, equal).trim();
			s = s.substring(equal + 1).trim();
			if (s.length() == 0)
				break;
			final boolean quote = s.charAt(0) == '\'' || s.charAt(0) == '\"';
			if (att.length() > 0 && quote) {
				String value = s.substring(1);
				final int end = value.indexOf(s.charAt(0));
				if (end >= 0)
					value = value.substring(0, end);
				attributeName.add(att);
				attributeValue.add(References.replace(value, false));
			}
			final int i = s.indexOf(quote ? s.charAt(0) : ' ', 1);
			s = i == -1 ? "" : s.substring(i + 1);
		}
	}
440476
protected void parseAttributes() {
        burnWhitespaces();
        attribute = null;
        while (reader.hasNextCharacter()) {
            char character = reader.peekCharacter();
            if (Strings.isNewLine(character) && (attribute != null || Strings.isNotEmpty(builder))) {
                throwException("Expecting line end marker: '" + lineEnd + "'.");
            }
            character = next();
            if (Strings.isNewLine(character) && (attribute != null || Strings.isNotEmpty(builder))) {
                // Needs double check, possible comment along the way.
                throwException("Expecting line end marker: '" + lineEnd + "'.");
            } else if (character == blockClosing) {
                if (attribute != null || Strings.isNotEmpty(builder)) {
                    throwException("Unexpected tag close.");
                }
                return;
            } else if (Strings.isWhitespace(character) && attribute == null) {
                continue;
            } else if (character == separator && attribute == null) {
                addAttributeName();
                continue;
            } else if (character == lineEnd) {
                if (attribute == null) {
                    throwException("Found unexpected line end marker: '" + lineEnd + "'. Is separator (" + separator
                            + ") missing?");
                }
                addAttribute();
            } else {
                builder.append(character);
            }
        }
    }
341664
def _unicode(p):
    
    q = {}
    for tag in p:
        vals = []
        for v in p[tag]:
            if type(v) is not str:                                                              # pragma: no cover
                v = v.decode('utf-8')
            vals.append(v)
        if type(tag) is not str:                                                                # pragma: no cover
            tag = tag.decode('utf-8')
        q[tag] = vals
    return q
76386
private ExprKraken parseSimpleTerm()
  {
    Token token = scanToken();

    switch (token) {
    case MINUS:
      return new UnaryExpr(UnaryOp.MINUS, parseSimpleTerm());
      
    case LPAREN:
    {
      ExprKraken expr = parseExpr();
      
      if ((token = scanToken()) != Token.RPAREN) {
        throw error("Expected ')' at '{0}'", token);
      }
      
      return expr;
    }
      
      
    case IDENTIFIER:
      {
        String name = _lexeme;

        if ((token = peekToken()) == Token.DOT) {
          return parsePath(name);
        }
        else if (token == Token.LPAREN) {
          FunExpr fun = null;
          
          /*
          if (name.equalsIgnoreCase("max"))
            fun = new MaxExpr();
          else if (name.equalsIgnoreCase("min"))
            fun = new MinExpr();
          else if (name.equalsIgnoreCase("sum"))
            fun = new SumExpr();
          else if (name.equalsIgnoreCase("avg"))
            fun = new AvgExpr();
          else if (name.equalsIgnoreCase("count")) {
            fun = new CountExpr();

            token = scanToken();
            if (token == '*') {
              fun.addArg(new UnboundStarExpr());
            }
            else
              _token = token;
          }
          else */
          {
            String funName = (Character.toUpperCase(name.charAt(0)) +
                              name.substring(1).toLowerCase(Locale.ENGLISH));

            funName = "com.caucho.v5.kraken.fun." + funName + "Expr";

            try {
              ClassLoader loader = Thread.currentThread().getContextClassLoader();
              Class<?> cl = Class.forName(funName, false, loader);

              fun = (FunExpr) cl.newInstance();
            } catch (ClassNotFoundException e) {
              log.finer(e.toString());
            } catch (Exception e) {
              log.log(Level.FINER, e.toString(), e);
              
              throw error(e.toString());
            }

            if (fun == null) {
              throw error(L.l("'{0}' is an unknown function.", name));
            }
          }

          scanToken();
          token = peekToken();
          while (token != null && token != Token.RPAREN) {
            ExprKraken arg = parseExpr();

            fun.addArg(arg);

            token = peekToken();

            if (token == Token.COMMA) {
              scanToken();
              token = peekToken();
            }
          }

          scanToken();

          return fun;
        }
        else {
          return new IdExprBuilder(name);
        }
      }

    case STRING:
      return new LiteralExpr(_lexeme);

    case DOUBLE:
      return new LiteralExpr(Double.parseDouble(_lexeme));
      
    case INTEGER:
      return new LiteralExpr(Long.parseLong(_lexeme));
      
    case LONG:
      return new LiteralExpr(Long.parseLong(_lexeme));

    case NULL:
      return new NullExpr();

    case TRUE:
      return new LiteralExpr(true);

    case FALSE:
      return new LiteralExpr(false);

    case QUESTION_MARK:
      ParamExpr param = new ParamExpr(_params.size());
      _params.add(param);
      return param;

    default:
      throw error("unexpected term {0}", token);
    }
  }
633208
protected void parseNodeTypeDefinition( TokenStream tokens ) {
        // Parse the name, and create the path and a property for the name ...
        Name name = parseNodeTypeName(tokens);
        JcrNodeTypeTemplate nodeType = new JcrNodeTypeTemplate(context);
        try {
            nodeType.setName(string(name));
        } catch (ConstraintViolationException e) {
            assert false : "Names should always be syntactically valid";
        }

        // Read the (optional) supertypes ...
        List<Name> supertypes = parseSupertypes(tokens);
        try {
            nodeType.setDeclaredSuperTypeNames(names(supertypes));

            // Read the node type options (and vendor extensions) ...
            parseNodeTypeOptions(tokens, nodeType);

            // Parse property and child node definitions ...
            parsePropertyOrChildNodeDefinitions(tokens, nodeType);
        } catch (ConstraintViolationException e) {
            assert false : "Names should always be syntactically valid";
        }

        this.nodeTypes.add(nodeType);
    }
532151
def parse_local(elem)
    ParseRegexp =~ elem
    if $2
      ns = @tag2ns[$1]
      name = $2
      if !ns
	raise FormatError.new("unknown namespace qualifier: #{$1}")
      end
    elsif $1
      ns = nil
      name = $1
    else
      raise FormatError.new("illegal element format: #{elem}")
    end
    XSD::QName.new(ns, name)
  end
149096
private Document parseStringToDOM(String s, String encoding) {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory
          .newInstance();
      factory.setValidating(false);
      InputStream is = new ByteArrayInputStream(s.getBytes(encoding));
      Document doc = factory.newDocumentBuilder().parse(is);
      return doc;
    } catch (SAXException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    }
    return null;
  }