repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/StandardAttributeFactory.java
/* * @(#)StandardAttributeFactory * * Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.UnknownIdentifierException; import org.wso2.balana.XACMLConstants; import org.wso2.balana.attr.proxy.*; import org.wso2.balana.attr.proxy.xacml3.XPathAttributeProxy; import org.wso2.balana.attr.xacml3.XPathAttribute; import java.util.Collections; import java.util.HashMap; import java.util.Set; /** * This factory supports the standard set of datatypes specified in XACML 1.x and 2.0. It is the * default factory used by the system, and imposes a singleton pattern insuring that there is only * ever one instance of this class. * <p> * Note that because this supports only the standard datatypes, this factory does not allow the * addition of any other datatypes. If you call <code>addDatatype</code> on an instance of this * class, an exception will be thrown. If you need a standard factory that is modifiable, you should * create a new <code>BaseAttributeFactory</code> (or some other <code>AttributeFactory</code>) and * configure it with the standard datatypes using <code>addStandardDatatypes</code> (or, in the case * of <code>BaseAttributeFactory</code>, by providing the datatypes in the constructor). * * @since 1.2 * @author Seth Proctor */ public class StandardAttributeFactory extends BaseAttributeFactory { // the one instance of this factory private static volatile StandardAttributeFactory factoryInstance = null; // the datatypes supported by this factory private static HashMap supportedDatatypes = null; // the supported identifiers for each version of XACML private static Set supportedV1Identifiers; private static Set supportedV2Identifiers; private static Set supportedV3Identifiers; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(StandardAttributeFactory.class); /** * Private constructor that sets up proxies for all of the standard datatypes. */ private StandardAttributeFactory() { super(supportedDatatypes); } /** * Private initializer for the supported datatypes. This isn't called until something needs * these values, and is only called once. */ private static void initDatatypes() { if (logger.isDebugEnabled()) { logger.debug("Initializing standard datatypes"); } supportedDatatypes = new HashMap(); // the 1.x datatypes supportedDatatypes.put(BooleanAttribute.identifier, new BooleanAttributeProxy()); supportedDatatypes.put(StringAttribute.identifier, new StringAttributeProxy()); supportedDatatypes.put(DateAttribute.identifier, new DateAttributeProxy()); supportedDatatypes.put(TimeAttribute.identifier, new TimeAttributeProxy()); supportedDatatypes.put(DateTimeAttribute.identifier, new DateTimeAttributeProxy()); supportedDatatypes.put(DayTimeDurationAttribute.identifier, new DayTimeDurationAttributeProxy()); supportedDatatypes.put(YearMonthDurationAttribute.identifier, new YearMonthDurationAttributeProxy()); supportedDatatypes.put(DoubleAttribute.identifier, new DoubleAttributeProxy()); supportedDatatypes.put(IntegerAttribute.identifier, new IntegerAttributeProxy()); supportedDatatypes.put(AnyURIAttribute.identifier, new AnyURIAttributeProxy()); supportedDatatypes.put(HexBinaryAttribute.identifier, new HexBinaryAttributeProxy()); supportedDatatypes.put(Base64BinaryAttribute.identifier, new Base64BinaryAttributeProxy()); supportedDatatypes.put(X500NameAttribute.identifier, new X500NameAttributeProxy()); supportedDatatypes.put(RFC822NameAttribute.identifier, new RFC822NameAttributeProxy()); supportedV1Identifiers = Collections.unmodifiableSet(supportedDatatypes.keySet()); // the 2.0 datatypes supportedDatatypes.put(DNSNameAttribute.identifier, new DNSNameAttributeProxy()); supportedDatatypes.put(IPAddressAttribute.identifier, new IPAddressAttributeProxy()); supportedV2Identifiers = Collections.unmodifiableSet(supportedDatatypes.keySet()); // the 3.0 datatypes. supportedDatatypes.put(XPathAttribute.identifier, new XPathAttributeProxy()); supportedV3Identifiers = Collections.unmodifiableSet(supportedDatatypes.keySet()); } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. This is the default model used by the <code>AttributeFactory</code>, ensuring quick * access to this factory. * * @return the factory instance */ public static StandardAttributeFactory getFactory() { if (factoryInstance == null) { synchronized (StandardAttributeFactory.class) { if (factoryInstance == null) { initDatatypes(); factoryInstance = new StandardAttributeFactory(); } } } return factoryInstance; } /** * A convenience method that returns a new instance of an <codeAttributeFactory</code> that * supports all of the standard datatypes. The new factory allows adding support for new * datatypes. This method should only be used when you need a new, mutable instance (eg, when * you want to create a new factory that extends the set of supported datatypes). In general, * you should use <code>getFactory</code> which is more efficient and enforces a singleton * pattern. * * @return a new factory supporting the standard datatypes */ public static AttributeFactory getNewFactory() { // first we make sure that everything has been initialized... getFactory(); // ...then we create the new instance return new BaseAttributeFactory(supportedDatatypes); } /** * Returns the identifiers supported for the given version of XACML. Because this factory * supports identifiers from all versions of the XACML specifications, this method is useful for * getting a list of which specific identifiers are supported by a given version of XACML. * * @param xacmlVersion a standard XACML identifier string, as provided in * <code>PolicyMetaData</code> * * @return a <code>Set</code> of identifiers * * @throws UnknownIdentifierException if the version string is unknown */ public static Set getStandardDatatypes(String xacmlVersion) throws UnknownIdentifierException { if (xacmlVersion.equals(XACMLConstants.XACML_1_0_IDENTIFIER)) { return supportedV1Identifiers; } else if (xacmlVersion.equals(XACMLConstants.XACML_2_0_IDENTIFIER)) { return supportedV2Identifiers; } else if(xacmlVersion.equals(XACMLConstants.XACML_3_0_IDENTIFIER)){ return supportedV3Identifiers; } throw new UnknownIdentifierException("Unknown XACML version: " + xacmlVersion); } /** * Throws an <code>UnsupportedOperationException</code> since you are not allowed to modify what * a standard factory supports. * * @param id the name of the attribute type * @param proxy the proxy used to create new attributes of the given type * * @throws UnsupportedOperationException always */ public void addDatatype(String id, AttributeProxy proxy) { throw new UnsupportedOperationException("a standard factory cannot " + "support new datatypes"); } }
9,576
44.604762
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AttributeSelector.java
/* * @(#)AttributeSelector.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.*; import org.wso2.balana.cond.Evaluatable; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Supports the standard selector functionality in XACML 1.0 /2.0 version, which uses XPath expressions to resolve * values from the Request or elsewhere. All selector queries are done by * <code>AttributeFinderModule</code>s so that it's easy to plugin different XPath implementations. * * @since 1.0 * @author Seth Proctor */ public class AttributeSelector extends AbstractAttributeSelector { // the data type returned by this selector private URI type; // the XPath to search private String contextPath; // must resolution find something private boolean mustBePresent; // the xpath version we've been told to use private String xpathVersion; // the policy root, where we get namespace mapping details private Node policyRoot; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(AttributeSelector.class); /** * Creates a new <code>AttributeSelector</code> with no policy root. * * @param type the data type of the attribute values this selector looks for * @param contextPath the XPath to query * @param mustBePresent must resolution find a match * @param xpathVersion the XPath version to use, which must be a valid XPath version string (the * identifier for XPath 1.0 is provided in <code>PolicyMetaData</code>) */ public AttributeSelector(URI type, String contextPath, boolean mustBePresent, String xpathVersion) { this(type, contextPath, null, mustBePresent, xpathVersion); } /** * Creates a new <code>AttributeSelector</code>. * * @param type the data type of the attribute values this selector looks for * @param contextPath the XPath to query * @param policyRoot the root DOM Element for the policy containing this selector, which defines * namespace mappings * @param mustBePresent must resolution find a match * @param xpathVersion the XPath version to use, which must be a valid XPath version string (the * identifier for XPath 1.0 is provided in <code>PolicyMetaData</code>) */ public AttributeSelector(URI type, String contextPath, Node policyRoot, boolean mustBePresent, String xpathVersion) { this.type = type; this.contextPath = contextPath; this.mustBePresent = mustBePresent; this.xpathVersion = xpathVersion; this.policyRoot = policyRoot; } /** * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so * if the <code>xpathVersion</code> string is null, then this will throw an exception. * * @deprecated As of 2.0 you should avoid using this method and should instead use the version * that takes a <code>PolicyMetaData</code> instance. This method will only work for * XACML 1.x policies. * * @param root the root of the DOM tree for the XML AttributeSelectorType XML type * @param xpathVersion the XPath version to use, or null if this is unspecified (ie, not * supplied in the defaults section of the policy) * * @return an <code>AttributeSelector</code> * * @throws ParsingException if the AttributeSelectorType was invalid */ public static AttributeSelector getInstance(Node root, String xpathVersion) throws ParsingException { return getInstance(root, new PolicyMetaData(XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion)); } /** * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so * if the <code>xpathVersion</code> string is null, then this will throw an exception. * * @param root the root of the DOM tree for the XML AttributeSelectorType XML type * @param metaData the meta-data associated with the containing policy * * @return an <code>AttributeSelector</code> * * @throws ParsingException if the AttributeSelectorType was invalid */ public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI type = null; String contextPath = null; boolean mustBePresent = false; String xpathVersion = metaData.getXPathIdentifier(); // make sure we were given an xpath version if (xpathVersion == null) throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors"); NamedNodeMap attrs = root.getAttributes(); try { // there's always a DataType attribute type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e); } try { // there's always a RequestPath contextPath = attrs.getNamedItem("RequestContextPath").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required " + "RequestContextPath attribute in " + "AttributeSelector", e); } try { // there may optionally be a MustBePresent Node node = attrs.getNamedItem("MustBePresent"); if (node != null) if (node.getNodeValue().equals("true")) mustBePresent = true; } catch (Exception e) { // this shouldn't happen, since we check the cases, but still... throw new ParsingException("Error parsing optional attributes " + "in AttributeSelector", e); } // as of 1.2 we need the root element of the policy so we can get // the namespace mapping, but in order to leave the APIs unchanged, // we'll walk up the tree to find the root rather than pass this // element around through all the code Node policyRoot = null; Node node = root.getParentNode(); while ((node != null) && (node.getNodeType() == Node.ELEMENT_NODE)) { policyRoot = node; node = node.getParentNode(); } // create the new selector return new AttributeSelector(type, contextPath, policyRoot, mustBePresent, xpathVersion); } /** * Returns the XPath query used to resolve attribute values. * * @return the XPath query */ public String getContextPath() { return contextPath; } /** * Always returns true, since a selector always returns a bag of attribute values. * * @return true */ public boolean returnsBag() { return true; } /** * Always returns true, since a selector always returns a bag of attribute values. * * @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the * super-interface <code>Expression</code>. * * @return true */ public boolean evaluatesToBag() { return true; } /** * Always returns an empty list since selectors never have children. * * @return an empty <code>List</code> */ public List getChildren() { return Collections.EMPTY_LIST; } /** * Invokes the <code>AttributeFinder</code> used by the given <code>EvaluationCtx</code> to try * to resolve an attribute value. If the selector is defined with MustBePresent as true, then * failure to find a matching value will result in Indeterminate, otherwise it will result in an * empty bag. To support the basic selector functionality defined in the XACML specification, * use a finder that has only the <code>SelectorModule</code> as a module that supports selector * finding. * * @param context representation of the request to search * * @return a result containing a bag either empty because no values were found or containing at * least one value, or status associated with an Indeterminate result */ public EvaluationResult evaluate(EvaluationCtx context) { // query the context EvaluationResult result = context.getAttribute(contextPath, type, null, null, xpathVersion); // see if we got anything if (!result.indeterminate()) { BagAttribute bag = (BagAttribute) (result.getAttributeValue()); // see if it's an empty bag if (bag.isEmpty()) { // see if this is an error or not if (mustBePresent) { // this is an error if (logger.isDebugEnabled()) { logger.debug("AttributeSelector failed to resolve a " + "value for a required attribute: " + contextPath); } ArrayList code = new ArrayList(); code.add(Status.STATUS_MISSING_ATTRIBUTE); String message = "couldn't resolve XPath expression " + contextPath + " for type " + type.toString(); return new EvaluationResult(new Status(code, message)); } else { // return the empty bag return result; } } else { // return the values return result; } } else { // return the error return result; } } /** * Encodes this <code>AttributeSelector</code> into its XML form and writes this out to the provided * <code>StringBuilder<code> * * @param builder string stream into which the XML-encoded data is written */ public void encode(StringBuilder builder) { String tag = "<AttributeSelector RequestContextPath=\"" + contextPath + "\" DataType=\"" + type.toString() + "\""; if (mustBePresent){ tag += " MustBePresent=\"true\""; } tag += "/>\n"; builder.append(tag); } }
12,771
38.177914
114
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/X500NameAttribute.java
/* * @(#)X500NameAttribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import java.net.URI; import javax.security.auth.x500.X500Principal; import org.w3c.dom.Node; /** * Representation of an X500 Name. * * @since 1.0 * @author Marco Barreno * @author Seth Proctor */ public class X500NameAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; // the actual value being stored private X500Principal value; /** * URI version of name for this type * <p> * This field is initialized by a static initializer so that we can catch any exceptions thrown * by URI(String) and transform them into a RuntimeException, since this should never happen but * should be reported properly if it ever does. */ private static URI identifierURI; /** * RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if * none. */ private static RuntimeException earlyException; /** * Static initializer that initializes the identifierURI class field so that we can catch any * exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions * should never happen but should be reported properly if they ever do. */ static { try { identifierURI = new URI(identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; /** * Creates a new <code>X500NameAttribute</code> that represents the value supplied. * * @param value the X500 Name to be represented */ public X500NameAttribute(X500Principal value) { super(identifierURI); if (earlyException != null) throw earlyException; this.value = value; } /** * Returns a new <codeX500NameAttribute</code> that represents the X500 Name at a particular DOM * node. * * @param root the <code>Node</code> that contains the desired value * @return a new <code>X500NameAttribute</code> representing the appropriate value * @throws IllegalArgumentException if value is improperly specified */ public static X500NameAttribute getInstance(Node root) throws IllegalArgumentException { return getInstance(root.getFirstChild().getNodeValue()); } /** * Returns a new <code>X500NameAttribute</code> that represents the X500 Name value indicated by * the string provided. * * @param value a string representing the desired value * @return a new <code>X500NameAttribute</code> representing the appropriate value * @throws IllegalArgumentException if value is improperly specified */ public static X500NameAttribute getInstance(String value) throws IllegalArgumentException { return new X500NameAttribute(new X500Principal(value)); } /** * Returns the name value represented by this object * * @return the name */ public X500Principal getValue() { return value; } /** * Returns true if the input is an instance of this class and if its value equals the value * contained in this class. This method deviates slightly from the XACML spec in the way that it * handles RDNs with multiple attributeTypeAndValue pairs and some additional canonicalization * steps. This method uses the procedure used by * <code>javax.security.auth.x500.X500Principal.equals()</code>, while the XACML spec uses a * slightly different procedure. In practice, it is expected that this difference will not be * noticeable. For more details, refer to the javadoc for <code>X500Principal.equals()</code> * and the XACML specification. * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (!(o instanceof X500NameAttribute)) return false; X500NameAttribute other = (X500NameAttribute) o; return value.equals(other.value); } /** * Returns the hashcode value used to index and compare this object with others of the same * type. Typically this is the hashcode of the backing data object. * * @return the object's hashcode value */ public int hashCode() { return value.hashCode(); } /** * */ public String encode() { return value.getName(); } }
6,435
35.157303
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AnyURIAttribute.java
/* * @(#)AnyURIAttribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import java.net.URI; import java.net.URISyntaxException; import org.w3c.dom.Node; /** * Representation of an xs:anyURI value. This class supports parsing xs:anyURI values. * * @since 1.0 * @author Seth Proctor */ public class AnyURIAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "http://www.w3.org/2001/XMLSchema#anyURI"; // URI version of name for this type private static URI identifierURI; // RuntimeException that wraps an Exception thrown during the // creation of identifierURI, null if none private static RuntimeException earlyException; /** * Static initializer that initializes the identifierURI class field so that we can catch any * exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions * should never happen but should be reported properly if they ever do. */ static { try { identifierURI = new URI(identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; // the URI value that this class represents private URI value; /** * Creates a new <code>AnyURIAttribute</code> that represents the URI value supplied. * * @param value the <code>URI</code> value to be represented */ public AnyURIAttribute(URI value) { super(identifierURI); // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; this.value = value; } /** * Returns a new <code>AnyURIAttribute</code> that represents the xs:anyURI at a particular DOM * node. * * @param root the <code>Node</code> that contains the desired value * * @return a new <code>AnyURIAttribute</code> representing the appropriate value (null if there * is a parsing error) */ public static AnyURIAttribute getInstance(Node root) throws URISyntaxException { return getInstance(root.getFirstChild().getNodeValue()); } /** * Returns a new <code>AnyURIAttribute</code> that represents the xs:anyURI value indicated by * the <code>String</code> provided. * * @param value a string representing the desired value * * @return a new <code>AnyURIAttribute</code> representing the appropriate value */ public static AnyURIAttribute getInstance(String value) throws URISyntaxException { return new AnyURIAttribute(new URI(value)); } /** * Returns the <code>URI</code> value represented by this object. * * @return the <code>URI</code> value */ public URI getValue() { return value; } /** * Returns true if the input is an instance of this class and if its value equals the value * contained in this class. * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (!(o instanceof AnyURIAttribute)) return false; AnyURIAttribute other = (AnyURIAttribute) o; return value.equals(other.value); } /** * Returns the hashcode value used to index and compare this object with others of the same * type. Typically this is the hashcode of the backing data object. * * @return the object's hashcode value */ public int hashCode() { return value.hashCode(); } /** * Converts to a String representation. * * @return the String representation */ public String toString() { return "AnyURIAttribute: \"" + value.toString() + "\""; } /** * */ public String encode() { return value.toString(); } }
5,769
32.352601
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/DateTimeAttribute.java
/* * @(#)DateTimeAttribute.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import org.wso2.balana.ParsingException; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.w3c.dom.Node; /** * Representation of an xs:dateTime value. This class supports parsing xs:dateTime values. All * objects of this class are immutable and thread-safe. The <code>Date</code> objects returned are * not, but these objects are cloned before being returned. * * @since 1.0 * @author Marco Barreno * @author Seth Proctor * @author Steve Hanna */ public class DateTimeAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "http://www.w3.org/2001/XMLSchema#dateTime"; /** * URI version of name for this type * <p> * This field is initialized by a static initializer so that we can catch any exceptions thrown * by URI(String) and transform them into a RuntimeException, since this should never happen but * should be reported properly if it ever does. * <p> * This object is used for synchronization whenever we need protection across this whole class. */ private static URI identifierURI; /** * RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if * none. */ private static RuntimeException earlyException; /** * Static initializer that initializes the identifierURI class field so that we can catch any * exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions * should never happen but should be reported properly if they ever do. */ static { try { identifierURI = new URI(identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; /** * Parser for dates with no time zones * <p> * This field is only initialized if needed (by initParsers()). * <p> * NOTE: This object should only be accessed from code that has synchronized on it, since * SimpleDateFormat objects are not thread-safe. If this is causing performance problems, we * could easily make this a method variable in methods that use it instead of a class field. But * that would mean we'd need to spend a lot more time creating these objects. */ private static volatile DateFormat simpleParser; /** * Parser for dates with RFC 822 time zones (like +0300) * <p> * This field is only initialized if needed (by initParsers()). * <p> * NOTE: This object should only be accessed from code that has synchronized on it, since * SimpleDateFormat objects are not thread-safe. */ private static DateFormat zoneParser; /** * Calendar for GMT * <p> * NOTE: This object should only be accessed from code that has a lock on it, since Calendar * objects are not generally thread-safe. */ private static volatile Calendar gmtCalendar; /** * Time zone value that indicates that the time zone was not specified. */ public static final int TZ_UNSPECIFIED = -1000000; /** * The actual date and time that this object represents (in GMT, as with all Date objects). If * no time zone was specified, the local time zone is used to convert to GMT. * <p> * This Date does not include fractions of a second. Those are handled by the separate * nanoseconds field, since Date only provides millisecond accuracy and the XML Query spec * requires at least 100 nanosecond accuracy. */ private Date value; /** * The number of nanoseconds beyond the Date given by the value field. The XML Query document * says that fractional seconds must be supported down to at least 100 nanosecond resolution. * The Date class only supports milliseconds, so we include here support for nanosecond * resolution. */ private int nanoseconds; /** * The time zone specified for this object (or TZ_UNSPECIFIED if unspecified). The offset to * GMT, in minutes. */ private int timeZone; /** * The time zone actually used for this object (if it was originally unspecified, the default * time zone used). The offset to GMT, in minutes. */ private int defaultedTimeZone; /** * Cached encoded value (null if not cached yet). */ private String encodedValue = null; /** * Creates a new <code>DateTimeAttribute</code> that represents the current date in the default * time zone. */ public DateTimeAttribute() { this(new Date()); } /** * Creates a new <code>DateTimeAttribute</code> that represents the supplied date but uses * default timezone and offset values. * * @param dateTime a <code>Date</code> object representing the specified date and time down to * second resolution. If this object has non-zero milliseconds, they are combined * with the nanoseconds parameter. */ public DateTimeAttribute(Date dateTime) { super(identifierURI); int currOffset = getDefaultTZOffset(dateTime); init(dateTime, 0, currOffset, currOffset); } /** * Creates a new <code>DateTimeAttribute</code> that represents the date supplied. * * @param dateTime a <code>Date</code> object representing the specified date and time down to * second resolution. If this object has non-zero milliseconds, they are combined * with the nanoseconds parameter. * @param nanoseconds the number of nanoseconds beyond the Date specified in the date parameter * @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified). * The offset to GMT, in minutes. * @param defaultedTimeZone the time zone actually used for this object (if it was originally * unspecified, the default time zone used). The offset to GMT, in minutes. */ public DateTimeAttribute(Date dateTime, int nanoseconds, int timeZone, int defaultedTimeZone) { super(identifierURI); init(dateTime, nanoseconds, timeZone, defaultedTimeZone); } /** * Initialization code shared by constructors. * * @param date a <code>Date</code> object representing the specified date and time down to * second resolution. If this object has non-zero milliseconds, they are combined * with the nanoseconds parameter. * @param nanoseconds the number of nanoseconds beyond the Date specified in the date parameter * @param timeZone the time zone specified for this object (or TZ_UNSPECIFIED if unspecified). * The offset to GMT, in minutes. * @param defaultedTimeZone the time zone actually used for this object (if it was originally * unspecified, the default time zone used). The offset to GMT, in minutes. */ private void init(Date date, int nanoseconds, int timeZone, int defaultedTimeZone) { // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; // Make a new Date object this.value = (Date) date.clone(); // Combine the nanoseconds so they are between 0 and 999,999,999 this.nanoseconds = combineNanos(this.value, nanoseconds); this.timeZone = timeZone; this.defaultedTimeZone = defaultedTimeZone; } /** * Returns a new <code>DateTimeAttribute</code> that represents the xs:dateTime at a particular * DOM node. * * @param root the <code>Node</code> that contains the desired value * @return a new <code>DateTimeAttribute</code> representing the appropriate value * @throws ParsingException if any problems occurred while parsing */ public static DateTimeAttribute getInstance(Node root) throws ParsingException, NumberFormatException, ParseException { return getInstance(root.getFirstChild().getNodeValue()); } /** * Returns a new <code>DateTimeAttribute</code> that represents the xs:dateTime value indicated * by the string provided. * * @param value a string representing the desired value * @return a new <code>DateTimeAttribute</code> representing the desired value * @throws ParsingException if the text is formatted incorrectly * @throws NumberFormatException if the nanosecond format is incorrect * @throws ParseException */ public static DateTimeAttribute getInstance(String value) throws ParsingException, NumberFormatException, ParseException { Date dateValue = null; int nanoseconds = 0; int timeZone; int defaultedTimeZone; initParsers(); // If string ends with Z, it's in GMT. Chop off the Z and // add +00:00 to make the time zone explicit. if (value.endsWith("Z")) value = value.substring(0, value.length() - 1) + "+00:00"; // Figure out if the string has a time zone. // If string ends with +XX:XX or -XX:XX, it must have // a time zone or be invalid. int len = value.length(); // This variable is often not up-to-date boolean hasTimeZone = ((value.charAt(len - 3) == ':') && ((value.charAt(len - 6) == '-') || (value .charAt(len - 6) == '+'))); // If string contains a period, it must have fractional // seconds (or be invalid). Strip them out and put the // value in nanoseconds. int dotIndex = value.indexOf('.'); if (dotIndex != -1) { // Decide where fractional seconds end. int secondsEnd = value.length(); if (hasTimeZone) secondsEnd -= 6; // Copy the fractional seconds out of the string. String nanoString = value.substring(dotIndex + 1, secondsEnd); // Check that all those characters are ASCII digits. for (int i = nanoString.length() - 1; i >= 0; i--) { char c = nanoString.charAt(i); if ((c < '0') || (c > '9')) throw new ParsingException("non-ascii digit found"); } // If there are less than 9 digits in the fractional seconds, // pad with zeros on the right so it's nanoseconds. if (nanoString.length() < 9) { StringBuffer buffer = new StringBuffer(nanoString); while (buffer.length() < 9) { buffer.append("0"); } nanoString = buffer.toString(); } // If there are more than 9 digits in the fractional seconds, // drop the least significant digits. if (nanoString.length() > 9) { nanoString = nanoString.substring(0, 9); } // Parse the fractional seconds. nanoseconds = Integer.parseInt(nanoString); // Remove the fractional seconds from the string. value = value.substring(0, dotIndex) + value.substring(secondsEnd, value.length()); } // this is the code that may trow a ParseException if (hasTimeZone) { // Strip off the purported time zone and make sure what's // left is a valid unzoned date and time (by parsing in GMT). // If so, reformat the time zone by stripping out the colon // and parse the revised string with the timezone parser. len = value.length(); Date gmtValue = strictParse(zoneParser, value.substring(0, len - 6) + "+0000"); value = value.substring(0, len - 3) + value.substring(len - 2, len); dateValue = strictParse(zoneParser, value); timeZone = (int) (gmtValue.getTime() - dateValue.getTime()); timeZone = timeZone / 60000; defaultedTimeZone = timeZone; } else { // No funny business. This must be a simple date and time. dateValue = strictParse(simpleParser, value); timeZone = TZ_UNSPECIFIED; // Figure out what time zone was used. Date gmtValue = strictParse(zoneParser, value + "+0000"); defaultedTimeZone = (int) (gmtValue.getTime() - dateValue.getTime()); defaultedTimeZone = defaultedTimeZone / 60000; } // If parsing went OK, create a new DateTimeAttribute object and // return it. DateTimeAttribute attr = new DateTimeAttribute(dateValue, nanoseconds, timeZone, defaultedTimeZone); return attr; } /** * Parse a String using a DateFormat parser, requiring that the entire String be consumed by the * parser. On success, return a Date. On failure, throw a ParseException. * <p> * Synchronize on the parser object when using it, since we assume they're the shared static * objects in this class. */ private static Date strictParse(DateFormat parser, String str) throws ParseException { ParsePosition pos = new ParsePosition(0); Date ret; synchronized (parser) { ret = parser.parse(str, pos); } if (pos.getIndex() != str.length()) throw new ParseException("", 0); return ret; } /** * Initialize the parser objects. */ private static void initParsers() { // If simpleParser is already set, we're done. if (simpleParser != null) return; // Make sure that identifierURI is not null if (earlyException != null) throw earlyException; // Synchronize on identifierURI while initializing parsers // so we don't end up using a half-way initialized parser synchronized (identifierURI) { // This simple parser has no time zone simpleParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); simpleParser.setLenient(false); // This parser has a four digit offset to GMT with sign zoneParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); zoneParser.setLenient(false); } } /** * Gets the date and time represented by this object. The return value is a <code>Date</code> * object representing the specified date and time down to second resolution. Subsecond values * are handled by the {@link #getNanoseconds getNanoseconds} method. * <p> * <b>NOTE:</b> The <code>Date</code> object is cloned before it is returned to avoid * unauthorized changes. * * @return a <code>Date</code> object representing the date and time represented by this object */ public Date getValue() { return (Date) value.clone(); } /** * Gets the nanoseconds of this object. * * @return the number of nanoseconds */ public int getNanoseconds() { return nanoseconds; } /** * Gets the time zone of this object (or TZ_UNSPECIFIED if unspecified). * * @return the offset to GMT in minutes (positive or negative) */ public int getTimeZone() { return timeZone; } /** * Gets the time zone actually used for this object (if it was originally unspecified, the * default time zone used). * * @return the offset to GMT in minutes (positive or negative) */ public int getDefaultedTimeZone() { return defaultedTimeZone; } /** * Returns true if the input is an instance of this class and if its value equals the value * contained in this class. * <p> * Two <code>DateTimeAttribute</code>s are equal if and only if the dates and times represented * are identical (down to the nanosecond). * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (!(o instanceof DateTimeAttribute)) return false; DateTimeAttribute other = (DateTimeAttribute) o; // Since the value field is normalized into GMT, this is a // good way to compare. return (value.equals(other.value) && (nanoseconds == other.nanoseconds)); } /** * Returns the hashcode value used to index and compare this object with others of the same * type. * * @return the object's hashcode value */ public int hashCode() { // Both the value field and the nanoseconds field are considered // by the equals method, so it's best if the hashCode is derived // from both of those fields. int hashCode = value.hashCode(); hashCode = 31 * hashCode + nanoseconds; return hashCode; } /** * Converts to a String representation. * * @return the String representation */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("DateTimeAttribute: [\n"); sb.append(" Date: " + value + " local time"); sb.append(" Nanoseconds: " + nanoseconds); sb.append(" TimeZone: " + timeZone); sb.append(" Defaulted TimeZone: " + defaultedTimeZone); sb.append("]"); return sb.toString(); } /** * Encodes the value in a form suitable for including in XML data like a request or an * obligation. This must return a value that could in turn be used by the factory to create a * new instance with the same value. * * @return a <code>String</code> form of the value */ public String encode() { if (encodedValue != null) return encodedValue; if (timeZone == TZ_UNSPECIFIED) { // If no time zone was specified, format Date value in // local time with no time zone string. initParsers(); synchronized (simpleParser) { encodedValue = simpleParser.format(value); } if (nanoseconds != 0) { encodedValue = encodedValue + "." + DateAttribute.zeroPadInt(nanoseconds, 9); } } else { // If a time zone was specified, don't use SimpleParser // because it can only format dates in the local (default) // time zone. And the offset between that time zone and the // time zone we need to display can vary in complicated ways. // Instead, do it ourselves using our formatDateWithTZ method. encodedValue = formatDateTimeWithTZ(); } return encodedValue; } /** * Encodes the value of this object as an xsi:dateTime. Only for use when the time zone is * specified. * * @return a <code>String</code> form of the value */ private String formatDateTimeWithTZ() { if (gmtCalendar == null) { TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); // Locale doesn't make much difference here. We don't use // any of the strings in the Locale and we don't do anything // that depends on week count conventions. We use the US // locale because it's always around and it ensures that we // will always get a Gregorian calendar, which is necessary // for compliance with ISO 8501. gmtCalendar = Calendar.getInstance(gmtTimeZone, Locale.US); } // "YYYY-MM-DDThh:mm:ss.sssssssss+hh:mm".length() = 35 // Length may be longer if years < -999 or > 9999 StringBuffer buf = new StringBuffer(35); synchronized (gmtCalendar) { // Start with the proper time in GMT. gmtCalendar.setTime(value); // Bump by the timeZone, since we're going to be extracting // the value in GMT gmtCalendar.add(Calendar.MINUTE, timeZone); // Now, assemble the string int year = gmtCalendar.get(Calendar.YEAR); buf.append(DateAttribute.zeroPadInt(year, 4)); buf.append('-'); // JANUARY is 0 int month = gmtCalendar.get(Calendar.MONTH) + 1; buf.append(DateAttribute.zeroPadInt(month, 2)); buf.append('-'); int dom = gmtCalendar.get(Calendar.DAY_OF_MONTH); buf.append(DateAttribute.zeroPadInt(dom, 2)); buf.append('T'); int hour = gmtCalendar.get(Calendar.HOUR_OF_DAY); buf.append(DateAttribute.zeroPadInt(hour, 2)); buf.append(':'); int minute = gmtCalendar.get(Calendar.MINUTE); buf.append(DateAttribute.zeroPadInt(minute, 2)); buf.append(':'); int second = gmtCalendar.get(Calendar.SECOND); buf.append(DateAttribute.zeroPadInt(second, 2)); } if (nanoseconds != 0) { buf.append('.'); buf.append(DateAttribute.zeroPadInt(nanoseconds, 9)); } int tzNoSign = timeZone; if (timeZone < 0) { tzNoSign = -tzNoSign; buf.append('-'); } else buf.append('+'); int tzHours = tzNoSign / 60; buf.append(DateAttribute.zeroPadInt(tzHours, 2)); buf.append(':'); int tzMinutes = tzNoSign % 60; buf.append(DateAttribute.zeroPadInt(tzMinutes, 2)); return buf.toString(); } /** * Gets the offset in minutes between the default time zone and UTC for the specified date. * * @param the <code>Date</code> whose offset is desired * @return the offset in minutes */ static int getDefaultTZOffset(Date date) { int offset = TimeZone.getDefault().getOffset(date.getTime()); offset = offset / DateAttribute.MILLIS_PER_MINUTE; return offset; } /** * Combines a number of nanoseconds with a <code>Date</code> so that the Date has no fractional * seconds and the number of nanoseconds is non-negative and less than a second. * <p> * <b>WARNING</b>: This function changes the value stored in the date parameter! * * @param date the <code>Date</code> to be combined (<b>value may be modified!</b>) * @param nanos the nanoseconds to be combined * @return the resulting number of nanoseconds */ static int combineNanos(Date date, int nanoseconds) { long millis = date.getTime(); int milliCarry = (int) (millis % DateAttribute.MILLIS_PER_SECOND); // If nothing needs fixing, get out quick if ((milliCarry == 0) && (nanoseconds > 0) && (nanoseconds < DateAttribute.NANOS_PER_SECOND)) return nanoseconds; // Remove any non-zero milliseconds from the date. millis -= milliCarry; // Add them into the nanoseconds. long nanoTemp = nanoseconds; nanoTemp += milliCarry * DateAttribute.NANOS_PER_MILLI; // Get the nanoseconds that represent fractional seconds. // This we'll return. int nanoResult = (int) (nanoTemp % DateAttribute.NANOS_PER_SECOND); // Get nanoseconds that represent whole seconds. nanoTemp -= nanoResult; // Convert that to milliseconds and add it back to the date. millis += nanoTemp / DateAttribute.NANOS_PER_MILLI; date.setTime(millis); return nanoResult; } }
22,845
34.365325
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/BagAttribute.java
/* * @(#)BagAttribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import java.net.URI; import java.util.*; /** * Represents a bag used in the XACML spec as return values from functions and designators/selectors * that provide more than one value. All values in the bag are of the same type, and the bag may be * empty. The bag is immutable, although its contents may not be. * <p> * NOTE: This is the one standard attribute type that can't be created from the factory, since you * can't have this in an XML block (it is used only in return values & dynamic inputs). I think this * is right, but we may need to add some functionality to let this go into the factory. * * @since 1.0 * @author Seth Proctor * @author Steve Hanna */ public class BagAttribute extends AttributeValue { // The List of AttributeValues that this object encapsulates private List<AttributeValue> bag; /** * Creates a new <code>BagAttribute</code> that represents the <code>Collection</code> of * <code>AttributeValue</code>s supplied. If the set is null or empty, then the new bag is * empty. * * @param type the data type of all the attributes in the set * @param bag a <code>List</code> of <code>AttributeValue</code>s */ public BagAttribute(URI type, List<AttributeValue> bag) { super(type); if (type == null) throw new IllegalArgumentException("Bags require a non-null " + "type be provided"); // see if the bag is empty/null if ((bag == null) || (bag.size() == 0)) { // empty bag this.bag = new ArrayList(); } else { // go through the collection to make sure it's a valid bag Iterator it = bag.iterator(); while (it.hasNext()) { AttributeValue attr = (AttributeValue) (it.next()); // a bag cannot contain other bags, so make sure that each // value isn't actually another bag if (attr.isBag()) throw new IllegalArgumentException("bags cannot contain " + "other bags"); // make sure that they're all the same type if (!type.toString().equals(attr.getType().toString())) throw new IllegalArgumentException("Bag items must all be of " + "the same type"); } // if we get here, then they're all the same type this.bag = bag; } } /** * Overrides the default method to always return true. * * @return a value of true */ public boolean isBag() { return true; } /** * Convenience function that returns a bag with no elements * * @param type the types contained in the bag * * @return a new empty bag */ public static BagAttribute createEmptyBag(URI type) { return new BagAttribute(type, null); } /** * A convenience function that returns whether or not the bag is empty (ie, whether or not the * size of the bag is zero) * * @return whether or not the bag is empty */ public boolean isEmpty() { return (bag.size() == 0); } /** * Returns the number of elements in this bag * * @return the number of elements in this bag */ public int size() { return bag.size(); } /** * Returns true if this set contains the specified value. More formally, returns true if and * only if this bag contains a value v such that (value==null ? v==null : value.equals(v)). Note * that this will only work correctly if the <code>AttributeValue</code> has overridden the * <code>equals</code> method. * * @param value the value to look for * * @return true if the value is in the bag */ public boolean contains(AttributeValue value) { return bag.contains(value); } /** * Returns true if this bag contains all of the values of the specified bag. Note that this will * only work correctly if the <code>AttributeValue</code> type contained in the bag has * overridden the <code>equals</code> method. * * @param bag the bag to compare * * @return true if the input is a subset of this bag */ public boolean containsAll(BagAttribute bag) { return this.bag.containsAll(bag.bag); } /** * Returns an iterator over te */ public Iterator iterator() { return new ImmutableIterator(bag.iterator()); } /** * This is a version of Iterator that overrides the <code>remove</code> method so that items * can't be taken out of the bag. */ private static class ImmutableIterator implements Iterator { // the iterator we're wrapping private Iterator iterator; /** * Create a new ImmutableIterator */ public ImmutableIterator(Iterator iterator) { this.iterator = iterator; } /** * Standard hasNext method */ public boolean hasNext() { return iterator.hasNext(); } /** * Standard next method */ public Object next() throws NoSuchElementException { return iterator.next(); } /** * Makes sure that no one can remove any elements from the bag */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } /** * Because a bag cannot be included in a request/response or a policy, this will always throw an * <code>UnsupportedOperationException</code>. */ public String encode() { throw new UnsupportedOperationException("Bags cannot be encoded"); } }
7,651
33.468468
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/AbstractAttributeSelector.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr; import org.wso2.balana.cond.Evaluatable; import java.net.URI; /** * Supports the standard selector functionality in XACML 3.0 version, which uses XPath expressions to resolve * values from the Request or elsewhere. This absrtact implementation of */ public abstract class AbstractAttributeSelector implements Evaluatable { /** * the data type returned by this selector */ protected URI type; /** * must resolution find something */ protected boolean mustBePresent; /** * the xpath version we've been told to use */ protected String xpathVersion; /** * Returns the data type of the attribute values that this selector will resolve * * @return the data type of the values found by this selector */ public URI getType() { return type; } /** * Returns whether or not a value is required to be resolved by this selector. * * @return true if a value is required, false otherwise */ public boolean isMustBePresent() { return mustBePresent; } /** * Returns the XPath version this selector is supposed to use. This is typically provided by the * defaults section of the policy containing this selector. * * @return the XPath version */ public String getXPathVersion() { return xpathVersion; } }
2,081
27.135135
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/BooleanAttribute.java
/* * @(#)BooleanAttribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr; import org.wso2.balana.ParsingException; import java.net.URI; import org.w3c.dom.Node; /** * Representation of an xs:boolean value. This class supports parsing xs:boolean values. All objects * of this class are immutable and all methods of the class are thread-safe. * * @since 1.0 * @author Marco Barreno * @author Steve Hanna */ public class BooleanAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "http://www.w3.org/2001/XMLSchema#boolean"; /** * URI version of name for this type * <p> * This field is initialized by a static initializer so that we can catch any exceptions thrown * by URI(String) and transform them into a RuntimeException, since this should never happen but * should be reported properly if it ever does. */ private static URI identifierURI; /** * RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if * none. */ private static RuntimeException earlyException; /** * Single instance of BooleanAttribute that represents true. Initialized by the static * initializer below. */ private static BooleanAttribute trueInstance; /** * Single instance of BooleanAttribute that represents false. Initialized by the static * initializer below. */ private static BooleanAttribute falseInstance; /** * Static initializer that initializes many static fields. * <p> * It is possible identifierURI class field so that we can catch any exceptions thrown by * URI(String) and transform them into a RuntimeException. Such exceptions should never happen * but should be reported properly if they ever do. */ static { try { identifierURI = new URI(identifier); trueInstance = new BooleanAttribute(true); falseInstance = new BooleanAttribute(false); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; /** * The actual boolean value that this object represents. */ private boolean value; /** * Creates a new <code>BooleanAttribute</code> that represents the boolean value supplied. * <p> * This constructor is private because it should not be used by anyone other than the static * initializer in this class. Instead, please use one of the getInstance methods, which will * ensure that only two BooleanAttribute objects are created, thus avoiding excess object * creation. */ private BooleanAttribute(boolean value) { super(identifierURI); this.value = value; } /** * Returns a <code>BooleanAttribute</code> that represents the xs:boolean at a particular DOM * node. * * @param root the <code>Node</code> that contains the desired value * @return a <code>BooleanAttribute</code> representing the appropriate value (null if there is * a parsing error) */ public static BooleanAttribute getInstance(Node root) throws ParsingException { return getInstance(root.getFirstChild().getNodeValue()); } /** * Returns a <code>BooleanAttribute</code> that represents the xs:boolean value indicated by the * string provided. * * @param value a string representing the desired value * @return a <code>BooleanAttribute</code> representing the appropriate value (null if there is * a parsing error) */ public static BooleanAttribute getInstance(String value) throws ParsingException { // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; if (value.equals("true")) return trueInstance; if (value.equals("false")) return falseInstance; throw new ParsingException("Boolean string must be true or false"); } /** * Returns a <code>BooleanAttribute</code> that represents the boolean value provided. * * @param value a boolean representing the desired value * @return a <code>BooleanAttribute</code> representing the appropriate value */ public static BooleanAttribute getInstance(boolean value) { // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; if (value) return trueInstance; else return falseInstance; } /** * Returns a <code>BooleanAttribute</code> that represents a true value. * * @return a <code>BooleanAttribute</code> representing a true value */ public static BooleanAttribute getTrueInstance() { // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; return trueInstance; } /** * Returns a <code>BooleanAttribute</code> that represents a false value. * * @return a <code>BooleanAttribute</code> representing a false value */ public static BooleanAttribute getFalseInstance() { // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; return falseInstance; } /** * Returns the <code>boolean</code> value represented by this object. * * @return the <code>boolean</code> value */ public boolean getValue() { return value; } /** * Returns true if the input is an instance of this class and if its value equals the value * contained in this class. * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (!(o instanceof BooleanAttribute)) return false; BooleanAttribute other = (BooleanAttribute) o; return (value == other.value); } /** * Returns the hashcode value used to index and compare this object with others of the same * type. Typically this is the hashcode of the backing data object. * * @return the object's hashcode value */ public int hashCode() { // these numbers come from the javadoc for java.lang.Boolean...no, // really, they do. I can't imagine what they were thinking... return (value ? 1231 : 1237); } /** * */ public String encode() { return (value ? "true" : "false"); } }
8,465
33.137097
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/xacml3/XPathAttribute.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.wso2.balana.attr.AttributeValue; import java.net.URI; /** * Representation of Xpath attribute type */ public class XPathAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "urn:oasis:names:tc:xacml:3.0:data-type:xpathExpression"; /** * URI version of name for this type * <p> * This field is initialized by a static initializer so that we can catch any exceptions thrown * by URI(String) and transform them into a RuntimeException, since this should never happen but * should be reported properly if it ever does. */ private static URI identifierURI; /** * RuntimeException that wraps an Exception thrown during the creation of identifierURI, null if * none. */ private static RuntimeException earlyException; /** * Static initializer that initializes the identifierURI class field so that we can catch any * exceptions thrown by URI(String) and transform them into a RuntimeException. Such exceptions * should never happen but should be reported properly if they ever do. */ static { try { identifierURI = new URI(identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; /** * The actual xpath expression as String value */ private String value; /** * The namespace context is defined by this value */ private String xPathCategory; /** * Creates a new <code>XPathAttribute</code> that represents the String value supplied. * * @param value the <code>String</code> that represent xpath expression * @param xPathCategory the <code>String</code> that represent the namespace context */ public XPathAttribute(String value, String xPathCategory) { super(identifierURI); // Shouldn't happen, but just in case... if (earlyException != null){ throw earlyException; } if (value == null){ this.value = ""; } else { this.value = value; } if(xPathCategory == null){ this.xPathCategory = ""; } else { this.xPathCategory = xPathCategory; } } /** * Returns a new <code>XPathAttribute</code> that represents a particular DOM node. * * @param root the <code>Node</code> that contains the desired value * @return a new <code>XPathAttribute</code> representing the appropriate value (null if there * is a parsing error) */ public static XPathAttribute getInstance(Node root) { String xPathCategory = null; NamedNodeMap nodeMap = root.getAttributes(); if(nodeMap != null){ Node categoryNode = nodeMap.getNamedItem("XPathCategory"); xPathCategory = categoryNode.getNodeValue(); } return getInstance(root.getFirstChild().getNodeValue(), xPathCategory); } /** * Returns a new <code>XPathAttribute</code> that represents value indicated by * the <code>String</code> provided. * * @param value a string representing the desired xpath expression value * @param xPathCategory a String represents the namespace context * @return a new <code>XPathAttribute</code> representing the appropriate value */ public static XPathAttribute getInstance(String value, String xPathCategory) { return new XPathAttribute(value, xPathCategory); } /** * Returns the <code>String</code> value that represents xpath expression * * @return the <code>String</code> value */ public String getValue() { return value; } /** * Returns the <code>String</code> value that represents the namespace context * * @return the <code>String</code> xPathCategory */ public String getXPathCategory() { return xPathCategory; } /** * Returns true if the input is an instance of this class and if its value equals the value * contained in this class. * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (!(o instanceof XPathAttribute)) return false; XPathAttribute other = (XPathAttribute) o; return value.equals(other.value) && xPathCategory.equals(other.xPathCategory); } /** * Returns the hashcode value used to index and compare this object with others of the same * type. Typically this is the hashcode of the backing data object. * * @return the object's hashcode value */ public int hashCode() { return value.hashCode(); } @Override public String encode() { return value; } @Override public String encodeWithTags(boolean includeType) { StringBuilder builder = new StringBuilder(); builder.append("<AttributeValue"); if (includeType && getType() != null) { builder.append(" DataType=\""); builder.append(getType().toString()); builder.append("\" XPathCategory=\""); builder.append(getXPathCategory()); builder.append("\""); } builder.append(">"); builder.append(encode()); builder.append("</AttributeValue>"); return builder.toString(); } }
6,314
29.955882
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/xacml3/AttributeDesignator.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr.xacml3; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.wso2.balana.*; import org.wso2.balana.attr.AbstractDesignator; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.MissingAttributeDetail; import org.wso2.balana.ctx.Status; import org.wso2.balana.ctx.StatusDetail; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * */ public class AttributeDesignator extends AbstractDesignator { // required attributes private URI type; private URI id; // optional attribute private String issuer; // must resolution find something private boolean mustBePresent; private URI category; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(AttributeDesignator.class); /** * Creates a new <code>AttributeDesignator</code> without the optional issuer. * * @param type the data type resolved by this designator * @param id the attribute id looked for by this designator * @param mustBePresent whether resolution must find a value * @param category */ public AttributeDesignator(URI type, URI id, boolean mustBePresent, URI category) { this(type, id, mustBePresent, null, category); } /** * Creates a new <code>AttributeDesignator</code> with the optional issuer. * * @param type the data type resolved by this designator * @param id the attribute id looked for by this designator * @param mustBePresent whether resolution must find a value * @param issuer the issuer of the values to search for or null if no issuer is specified * @param category * @throws IllegalArgumentException if the input target isn't a valid value */ public AttributeDesignator(URI type, URI id, boolean mustBePresent, String issuer, URI category) throws IllegalArgumentException { this.type = type; this.id = id; this.mustBePresent = mustBePresent; this.issuer = issuer; this.category = category; } /** * Creates a new <code>AttributeDesignator</code> based on the DOM root of the XML data. * * @param root the DOM root of the AttributeDesignatorType XML type * @return the designator * @throws ParsingException if the AttributeDesignatorType was invalid */ public static AttributeDesignator getInstance(Node root) throws ParsingException { URI type = null; URI id = null; String issuer = null; URI category = null; boolean mustBePresent = false; // First check to be sure the node passed is indeed a AttributeDesignator node. String tagName = DOMHelper.getLocalName(root); if (!tagName.equals("AttributeDesignator")) { throw new ParsingException("AttributeDesignator cannot be constructed using " + "type: " + DOMHelper.getLocalName(root)); } NamedNodeMap attrs = root.getAttributes(); try { id = new URI(attrs.getNamedItem("AttributeId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Required AttributeId missing in " + "AttributeDesignator", e); } try { category = new URI(attrs.getNamedItem("Category").getNodeValue()); } catch (Exception e) { throw new ParsingException("Required Category missing in " + "AttributeDesignator", e); } try { String nodeValue = attrs.getNamedItem("MustBePresent").getNodeValue(); if ("true".equals(nodeValue)) { mustBePresent = true; } } catch (Exception e) { throw new ParsingException("Required MustBePresent missing in " + "AttributeDesignator", e); } try { type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Required DataType missing in " + "AttributeDesignator", e); } try { Node node = attrs.getNamedItem("Issuer"); if (node != null){ issuer = node.getNodeValue(); } } catch (Exception e) { throw new ParsingException( "Error parsing AttributeDesignator " + "optional attributes", e); } return new AttributeDesignator(type, id, mustBePresent, issuer, category); } /** * Returns the type of attribute that is resolved by this designator. While an AD will always * return a bag, this method will always return the type that is stored in the bag. * * @return the attribute type */ public URI getType() { return type; } /** * Returns the AttributeId of the values resolved by this designator. * * @return identifier for the values to resolve */ public URI getId() { return id; } /** * Returns the category for this designator. * * @return the category */ public URI getCategory() { return category; } /** * Returns the issuer of the values resolved by this designator if specified. * * @return the attribute issuer or null if unspecified */ public String getIssuer() { return issuer; } /** * Returns whether or not a value is required to be resolved by this designator. * * @return true if a value is required, false otherwise */ public boolean mustBePresent() { return mustBePresent; } /** * Always returns true, since a designator always returns a bag of attribute values. * * @return true */ public boolean returnsBag() { return true; } /** * Always returns true, since a designator always returns a bag of attribute values. * * @return true * @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the * super-interface <code>Expression</code>. */ public boolean evaluatesToBag() { return true; } /** * Always returns an empty list since designators never have children. * * @return an empty <code>List</code> */ public List getChildren() { return Collections.EMPTY_LIST; } /** * Evaluates the pre-assigned meta-data against the given context, trying to find some matching * values. * * @param context the representation of the request * @return a result containing a bag either empty because no values were found or containing at * least one value, or status associated with an Indeterminate result */ public EvaluationResult evaluate(EvaluationCtx context) { EvaluationResult result = null; // look in attribute values result = context.getAttribute(type, id, issuer, category); // if the lookup was indeterminate, then we return immediately if (result.indeterminate()){ return result; } BagAttribute bag = (BagAttribute) (result.getAttributeValue()); if (bag.isEmpty()) { // if it's empty, this may be an error if (mustBePresent) { if (logger.isDebugEnabled()) { logger.debug("AttributeDesignator failed to resolve a " + "value for a required attribute: " + id.toString()); } ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_MISSING_ATTRIBUTE); ArrayList<MissingAttributeDetail> missingAttributes = new ArrayList<MissingAttributeDetail>(); MissingAttributeDetail missingAttribute = new MissingAttributeDetail(id, type, category, issuer, null, XACMLConstants.XACML_VERSION_3_0); missingAttributes.add(missingAttribute); StatusDetail detail = new StatusDetail(missingAttributes); String message = "Couldn't find AttributeDesignator attribute"; // Note that there is a bug in the XACML spec. You can't // specify an identifier without specifying acceptable // values. Until this is fixed, this code will only // return the status code, and not any hints about what // was missing /* * List attrs = new ArrayList(); attrs.add(new Attribute(id, ((issuer == null) ? * null : issuer.toString()), null, null)); StatusDetail detail = new * StatusDetail(attrs); */ return new EvaluationResult(new Status(code, message, detail)); } } // if we got here the bag wasn't empty, or mustBePresent was false, // so we just return the result return result; } /** * Encodes this <code>AttributeDesignator</code> into its XML form and writes this out to the provided * <code>StringBuilder<code> * * @param builder string stream into which the XML-encoded data is written */ public void encode(StringBuilder builder) { builder.append("<AttributeDesignator"); builder.append(" AttributeId=\"").append(id.toString()).append("\""); builder.append(" DataType=\"").append(type.toString()).append("\""); builder.append(" Category=\"").append(category.toString()).append("\""); if (issuer != null) { builder.append(" Issuer=\"").append(issuer).append("\""); } if (mustBePresent) { builder.append(" MustBePresent=\"true\""); } else { builder.append(" MustBePresent=\"false\""); } builder.append("/>\n"); } }
10,934
32.959627
110
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/xacml3/AttributeSelector.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr.xacml3; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.wso2.balana.ParsingException; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.attr.AbstractAttributeSelector; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Supports the standard selector functionality in XACML 3.0 version, which uses XPath expressions to resolve * values from the Request or elsewhere. All selector queries are done by * <code>AttributeFinderModule</code>s so that it's easy to plugin different XPath implementations. */ public class AttributeSelector extends AbstractAttributeSelector { /** * category of the select */ private URI category; /** * the XPath search for context node */ private URI contextSelectorId; /** * the XPath to search fpr attributes */ private String path; /** * the logger we'll use for all messages */ private static final Log logger = LogFactory.getLog(AttributeSelector.class); /** * Creates a new <code>AttributeSelector</code>. * * @param category category of the attribute select * @param type the data type of the attribute values this selector looks for * @param contextSelectorId XPath search for context node * @param path the XPath to query attribute * @param mustBePresent must resolution find a match * @param xpathVersion the XPath version to use, which must be a valid XPath version string (the * identifier for XPath 1.0 is provided in <code>PolicyMetaData</code>) */ public AttributeSelector(URI category, URI type, URI contextSelectorId, String path, boolean mustBePresent, String xpathVersion) { this.category = category; this.type = type; this.contextSelectorId = contextSelectorId; this.mustBePresent = mustBePresent; this.xpathVersion = xpathVersion; this.path = path; } /** * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so * if the <code>xpathVersion</code> string is null, then this will throw an exception. * * @param root the root of the DOM tree for the XML AttributeSelectorType XML type * @param metaData the meta-data associated with the containing policy * * @return an <code>AttributeSelector</code> * * @throws ParsingException if the AttributeSelectorType was invalid */ public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI category = null; URI type = null; URI contextSelectorId = null; String path = null; boolean mustBePresent = false; String xpathVersion = metaData.getXPathIdentifier(); // make sure we were given an xpath version if (xpathVersion == null){ throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors"); } NamedNodeMap attrs = root.getAttributes(); try { // there's always a DataType attribute category = new URI(attrs.getNamedItem("Category").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required Category " + "attribute in AttributeSelector", e); } try { // there's always a DataType attribute type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e); } try { // there's always a RequestPath path = attrs.getNamedItem("Path").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required " + "Path attribute in " + "AttributeSelector", e); } try { String stringValue = attrs.getNamedItem("MustBePresent").getNodeValue(); mustBePresent = Boolean.parseBoolean(stringValue); } catch (Exception e) { throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector", e); } try { Node node = attrs.getNamedItem("ContextSelectorId"); if(node != null){ contextSelectorId = new URI(node.getNodeValue()); } } catch (Exception e) { throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector", e); } return new AttributeSelector(category, type, contextSelectorId, path, mustBePresent, xpathVersion); } /** * Invokes the <code>AttributeFinder</code> used by the given <code>EvaluationCtx</code> to try * to resolve an attribute value. If the selector is defined with MustBePresent as true, then * failure to find a matching value will result in Indeterminate, otherwise it will result in an * empty bag. To support the basic selector functionality defined in the XACML specification, * use a finder that has only the <code>SelectorModule</code> as a module that supports selector * finding. * * @param context representation of the request to search * * @return a result containing a bag either empty because no values were found or containing at * least one value, or status associated with an Indeterminate result */ public EvaluationResult evaluate(EvaluationCtx context) { // query the context EvaluationResult result = context.getAttribute(path, type, category, contextSelectorId, xpathVersion); // see if we got anything if (!result.indeterminate()) { BagAttribute bag = (BagAttribute) (result.getAttributeValue()); // see if it's an empty bag if (bag.isEmpty()) { // see if this is an error or not if (mustBePresent) { // this is an error if (logger.isDebugEnabled()) { logger.debug("AttributeSelector failed to resolve a " + "value for a required attribute: " + path); } ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_MISSING_ATTRIBUTE); String message = "couldn't resolve XPath expression " + path + " for type " + type.toString(); return new EvaluationResult(new Status(code, message)); } else { // return the empty bag return result; } } else { // return the values return result; } } else { // return the error return result; } } public boolean evaluatesToBag() { return true; } public List getChildren() { return null; } public boolean returnsBag() { return true; } public void encode(StringBuilder builder) { } }
8,685
35.805085
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/StringAttributeProxy.java
/* * @(#)StringAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.StringAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class StringAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) { return StringAttribute.getInstance(root); } public AttributeValue getInstance(String value) { return StringAttribute.getInstance(value); } }
2,445
39.098361
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/Base64BinaryAttributeProxy.java
/* * @(#)Base64BinaryAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.Base64BinaryAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class Base64BinaryAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return Base64BinaryAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return Base64BinaryAttribute.getInstance(value); } }
2,509
40.147541
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/DayTimeDurationAttributeProxy.java
/* * @(#)DayTimeDurationAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DayTimeDurationAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class DayTimeDurationAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return DayTimeDurationAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return DayTimeDurationAttribute.getInstance(value); } }
2,524
40.393443
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/DNSNameAttributeProxy.java
/* * @(#)DNSNameAttributeProxy.java * * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.ParsingException; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DNSNameAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 2.0 * @author Seth Proctor */ public class DNSNameAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws ParsingException { return DNSNameAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws ParsingException { return DNSNameAttribute.getInstance(value); } }
2,540
39.333333
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/IntegerAttributeProxy.java
/* * @(#)IntegerAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.IntegerAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class IntegerAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return IntegerAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return IntegerAttribute.getInstance(value); } }
2,484
39.737705
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/AnyURIAttributeProxy.java
/* * @(#)AnyURIAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AnyURIAttribute; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class AnyURIAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return AnyURIAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return AnyURIAttribute.getInstance(value); } }
2,479
39.655738
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/YearMonthDurationAttributeProxy.java
/* * @(#)YearMonthDurationAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.YearMonthDurationAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class YearMonthDurationAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return YearMonthDurationAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return YearMonthDurationAttribute.getInstance(value); } }
2,534
40.557377
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/RFC822NameAttributeProxy.java
/* * @(#)RFC822NameAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.RFC822NameAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class RFC822NameAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return RFC822NameAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return RFC822NameAttribute.getInstance(value); } }
2,499
39.983607
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/X500NameAttributeProxy.java
/* * @(#)X500NameAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.X500NameAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class X500NameAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return X500NameAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return X500NameAttribute.getInstance(value); } }
2,489
39.819672
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/TimeAttributeProxy.java
/* * @(#)TimeAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.TimeAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class TimeAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return TimeAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return TimeAttribute.getInstance(value); } }
2,469
39.491803
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/AbstractAttributeProxy.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; /** * Abstract represent of <code>AttributeProxy</code> introduces simple method when there is no * additional parameters to create the instance */ public abstract class AbstractAttributeProxy implements AttributeProxy { /** * Tries to create a new <code>AttributeValue</code> based on the given String data. * * @param value the text form of some attribute data * * @return an <code>AttributeValue</code> representing the given data * * @throws Exception if the data couldn't be used (the exception is typically wrapping some * other exception) */ public abstract AttributeValue getInstance(String value) throws Exception; public AttributeValue getInstance(String value, String[] params) throws Exception { if(params == null || params.length < 1){ return getInstance(value); } else { throw new Exception("Invalid method is called."); } } }
1,751
34.04
95
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/HexBinaryAttributeProxy.java
/* * @(#)HexBinaryAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.HexBinaryAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class HexBinaryAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return HexBinaryAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return HexBinaryAttribute.getInstance(value); } }
2,494
39.901639
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/DoubleAttributeProxy.java
/* * @(#)DoubleAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DoubleAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class DoubleAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return DoubleAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return DoubleAttribute.getInstance(value); } }
2,479
39.655738
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/IPAddressAttributeProxy.java
/* * @(#)IPAddressAttributeProxy.java * * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.ParsingException; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.IPAddressAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 2.0 * @author Seth Proctor */ public class IPAddressAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws ParsingException { return IPAddressAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws ParsingException { return IPAddressAttribute.getInstance(value); } }
2,550
39.492063
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/BooleanAttributeProxy.java
/* * @(#)BooleanAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BooleanAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class BooleanAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return BooleanAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return BooleanAttribute.getInstance(value); } }
2,484
39.737705
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/DateTimeAttributeProxy.java
/* * @(#)DateTimeAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DateTimeAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class DateTimeAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return DateTimeAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return DateTimeAttribute.getInstance(value); } }
2,489
39.819672
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/DateAttributeProxy.java
/* * @(#)DateAttributeProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.attr.proxy; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DateAttribute; import org.w3c.dom.Node; /** * A proxy class that is provided mainly for the run-time configuration code to use. * * @since 1.2 * @author Seth Proctor */ public class DateAttributeProxy extends AbstractAttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return DateAttribute.getInstance(root); } public AttributeValue getInstance(String value) throws Exception { return DateAttribute.getInstance(value); } }
2,469
39.491803
84
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/attr/proxy/xacml3/XPathAttributeProxy.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.attr.proxy.xacml3; import org.w3c.dom.Node; import org.wso2.balana.attr.AttributeProxy; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.xacml3.XPathAttribute; /** * proxy class that is provided mainly for the run-time configuration code to use. */ public class XPathAttributeProxy implements AttributeProxy { public AttributeValue getInstance(Node root) throws Exception { return XPathAttribute.getInstance(root); } public AttributeValue getInstance(String value, String[] params) throws Exception { //only one parameter is needed which is called XPathcategory String xPathCategory = null; if(params != null){ xPathCategory = params[0]; } return XPathAttribute.getInstance(value, xPathCategory); } }
1,492
32.931818
87
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/PolicyFinderResult.java
/* * @(#)PolicyFinderResult.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.ctx.Status; /** * This is used as the return value for the findPolicy() methods in the <code>PolicyFinder</code>. * It communicates either a found policy that applied to the request (eg, the target matches), an * Indeterminate state, or no applicable policies. * <p> * The OnlyOneApplicable combining logic is used in looking for a policy, so the result from calling * findPolicy can never be more than one policy. * * @since 1.0 * @author Seth Proctor */ public class PolicyFinderResult { // the single policy being returned private AbstractPolicy policy; // status that represents an error occurred private Status status; /** * Creates a result saying that no applicable policies were found. */ public PolicyFinderResult() { policy = null; status = null; } /** * Creates a result containing a single applicable policy. * * @param policy the applicable policy */ public PolicyFinderResult(AbstractPolicy policy) { this.policy = policy; status = null; } /** * Create a result of Indeterminate, including Status data. * * @param status the error information */ public PolicyFinderResult(Status status) { policy = null; this.status = status; } /** * Returns true if the result was NotApplicable. * * @return true if the result was NotApplicable */ public boolean notApplicable() { return ((policy == null) && (status == null)); } /** * Returns true if the result was Indeterminate. * * @return true if there was an error */ public boolean indeterminate() { return (status != null); } /** * Returns the found policy, or null if there was an error or no policy was found. * * @return the applicable policy or null */ public AbstractPolicy getPolicy() { return policy; } /** * Returns the status if there was an error, or null if no error occurred. * * @return the error status data or null */ public Status getStatus() { return status; } }
4,096
31.515873
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/ResourceFinderResult.java
/* * @(#)ResourceFinderResult.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.wso2.balana.attr.AttributeValue; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * This is used to return Resource Ids from the ResourceFinder. Unlike the PolicyFinder, this never * returns an empty set, since it will always contain at least the original parent resource. This * class will provide two sets of identifiers: those that were successfully resolved and those that * had an error. * * @since 1.0 * @author Seth Proctor */ public class ResourceFinderResult { // the set of resource identifiers private Set<AttributeValue> resources; // the map of failed identifiers to their failure status data private Map failures; // a flag specifying whether or not result contains resource listings private boolean empty; /** * Creates an empty result. */ public ResourceFinderResult() { resources = Collections.unmodifiableSet(new HashSet<AttributeValue>()); failures = Collections.unmodifiableMap(new HashMap()); empty = true; } /** * Creates a result containing the given <code>Set</code> of resource identifiers. The * <code>Set</code>must not be null. The new <code>ResourceFinderResult</code> represents a * resource retrieval that encountered no errors. * * @param resources a non-null <code>Set</code> of <code>AttributeValue</code>s */ public ResourceFinderResult(Set<AttributeValue> resources) { this(resources, new HashMap()); } /** * Creates a result containing only Resource Ids that caused errors. The <code>Map</code> must * not be null. The keys in the <code>Map</code> are <code>AttributeValue</code>s identifying * the resources that could not be resolved, and they map to a <code>Status</code> object * explaining the error. The new <code>ResourceFinderResult</code> represents a resource * retrieval that did not succeed in finding any resource identifiers. * * @param failures a non-null <code>Map</code> mapping failed <code>AttributeValue</code> * identifiers to their <code>Status</code> */ public ResourceFinderResult(HashMap failures) { this(new HashSet(), failures); } /** * Creates a new result containing both successfully resolved Resource Ids and resources that * caused errors. * * @param resources a non-null <code>Set</code> of <code>AttributeValue</code>s * @param failures a non-null <code>Map</code> mapping failed <code>AttributeValue</code> * identifiers to their <code>Status</code> */ public ResourceFinderResult(Set resources, Map failures) { this.resources = Collections.unmodifiableSet(new HashSet<AttributeValue>(resources)); this.failures = Collections.unmodifiableMap(new HashMap(failures)); empty = false; } /** * Returns whether or not this result contains any Resource Id listings. This will return false * if either the set of successfully resolved resource identifiers or the map of failed * resources is not empty. * * @return false if this result names any resources, otherwise true */ public boolean isEmpty() { return empty; } /** * Returns the <code>Set</code> of successfully resolved Resource Id <code>AttributeValue</code> * s, which will be empty if no resources were successfully resolved. * * @return a <code>Set</code> of <code>AttributeValue</code>s */ public Set<AttributeValue> getResources() { return resources; } /** * Returns the <code>Map</code> of Resource Ids that caused an error on resolution, which will * be empty if no resources caused any error. * * @return a <code>Map</code> of <code>AttributeValue</code>s to <code>Status</code> */ public Map getFailures() { return failures; } }
5,860
39.143836
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/AttributeFinder.java
/* * @(#)AttributeFinder.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.EvaluationResult; import java.net.URI; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.w3c.dom.Node; /** * This class is used by the PDP to find attribute values that weren't originally supplied in the * request. It can be called with the data supplied in * <code>AttributeDesignator<code>s or <code>AttributeSelector</code>s. Because the modules in this * finder may themselves need attribute data to search for attribute data, it's possible that the * modules will look for values in the <code>EvaluationCtx</code>, which may in turn result in the * invocation of this finder again, so module writers need to be careful about how they build their * modules. * <p> * Note that unlike the PolicyFinder, this class doesn't always need to use every module it has to * find a value. The ordering is maintained, however, so it will always start with the first module, * and proceed in order until it finds a value or runs out of modules. * * @since 1.0 * @author Seth Proctor */ public class AttributeFinder { // the list of all modules private List<AttributeFinderModule> allModules; // private List<AttributeFinderModule> designatorModules; // private List<AttributeFinderModule> selectorModules; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(AttributeFinder.class); /** * Default constructor. */ public AttributeFinder() { allModules = new ArrayList<AttributeFinderModule>(); designatorModules = new ArrayList<AttributeFinderModule>(); selectorModules = new ArrayList<AttributeFinderModule>(); } /** * Returns the ordered <code>List</code> of <code>AttributeFinderModule</code>s used by this * class to find attribute values. * * @return a <code>List</code> of <code>AttributeFinderModule</code>s */ public List<AttributeFinderModule> getModules() { return new ArrayList<AttributeFinderModule>(allModules); } /** * Sets the ordered <code>List</code> of <code>AttributeFinderModule</code>s used by this class * to find attribute values. The ordering will be maintained. * * @param modules a <code>List</code> of <code>AttributeFinderModule</code>s */ public void setModules(List<AttributeFinderModule> modules) { Iterator it = modules.iterator(); allModules = new ArrayList<AttributeFinderModule>(modules); designatorModules = new ArrayList<AttributeFinderModule>(); selectorModules = new ArrayList<AttributeFinderModule>(); while (it.hasNext()) { AttributeFinderModule module = (AttributeFinderModule) (it.next()); if (module.isDesignatorSupported()) designatorModules.add(module); if (module.isSelectorSupported()) selectorModules.add(module); } } /** * Tries to find attribute values based on the given designator data. The result, if successful, * will always contain a <code>BagAttribute</code>, even if only one value was found. If no * values were found, but no other error occurred, an empty bag is returned. * * @param attributeType the datatype of the attributes to find * @param attributeId the identifier of the attributes to find * @param issuer the issuer of the attributes, or null if unspecified * @param category the category of the attribute if the designatorType is SUBJECT_TARGET, * otherwise null * @param context the representation of the request data * * @return the result of attribute retrieval, which will be a bag of attributes or an error */ public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, URI category, EvaluationCtx context) { Iterator it = designatorModules.iterator(); // start with empty list of Attribute ValuesS List<AttributeValue> attributeValues = new ArrayList<AttributeValue>(); // go through each module in order while (it.hasNext()) { AttributeFinderModule module = (AttributeFinderModule) (it.next()); // see if the module supports this type, note: if supportedIds and supportedCategories are null // it implies that the module will resolve any type attributes if(module.getSupportedIds() != null && module.getSupportedCategories() != null){ if (!module.getSupportedCategories().contains(category.toString()) || !module.getSupportedIds().contains(attributeId.toString())){ continue; } } // see if the module can find an attribute value EvaluationResult result = module.findAttribute(attributeType, attributeId, issuer, category, context); // if there was an error, we stop right away if (result.indeterminate()) { logger.error("Error while trying to resolve values: " + result.getStatus().getMessage()); return result; } // if the result wasn't empty, add the found attributes to list of AttributeValues and continue iterating BagAttribute bag = (BagAttribute) (result.getAttributeValue()); if (!bag.isEmpty()) { Iterator iterator = bag.iterator(); while (iterator.hasNext()) { AttributeValue attr = (AttributeValue) (iterator.next()); attributeValues.add(attr); } } } // check whether we were able to find any attributes, if not return an empty bag if (attributeValues.isEmpty()){ // if we got here then there were no errors but there were also no // matches if (logger.isDebugEnabled()) { logger.debug("Failed to resolve any values for " + attributeId.toString()); } } return new EvaluationResult(new BagAttribute(attributeType,attributeValues)); } /** * Tries to find attribute values based on the given selector data. The result, if successful, * must always contain a <code>BagAttribute</code>, even if only one value was found. If no * values were found, but no other error occurred, an empty bag is returned. * * @param contextPath the XPath expression to search against * @param attributeType the datatype of the attributes to find * @param context the representation of the request data * @param xpathVersion the XPath version to use * * @return the result of attribute retrieval, which will be a bag of attributes or an error */ public EvaluationResult findAttribute(String contextPath, URI attributeType, EvaluationCtx context, String xpathVersion) { Iterator it = selectorModules.iterator(); // start with empty list of Attribute Values List<AttributeValue> attributeValues = new ArrayList<AttributeValue>(); // go through each module in order while (it.hasNext()) { AttributeFinderModule module = (AttributeFinderModule) (it.next()); // see if the module can find an attribute value EvaluationResult result = module.findAttribute(contextPath, attributeType, null, null, context, xpathVersion); // if there was an error, we stop right away if (result.indeterminate()) { logger.error("Error while trying to resolve values: " + result.getStatus().getMessage()); return result; } // if the result wasn't empty, add the found attributes to list of AttributeValues and continue iterating BagAttribute bag = (BagAttribute) (result.getAttributeValue()); if (!bag.isEmpty()) { Iterator iterator = bag.iterator(); while (iterator.hasNext()) { AttributeValue attr = (AttributeValue) (iterator.next()); attributeValues.add(attr); } } } // check whether we were able to find any attributes, if not return an empty bag if (attributeValues.isEmpty()) { // if we got here then there were no errors but there were also no // matches if (logger.isDebugEnabled()) { logger.debug("Failed to resolve any values for " + contextPath); } } return new EvaluationResult(new BagAttribute(attributeType,attributeValues)); } /** * Tries to find attribute values based on the given selector data. The result, if successful, * must always contain a <code>BagAttribute</code>, even if only one value was found. If no * values were found, but no other error occurred, an empty bag is returned. * * @param contextPath the XPath expression to search against * @param contextSelector select the context to evaluate * @param attributeType the datatype of the attributes to find * @param root root XML node * @param context the representation of the request data * @param xpathVersion the XPath version to use * * @return the result of attribute retrieval, which will be a bag of attributes or an error */ public EvaluationResult findAttribute(String contextPath, String contextSelector, URI attributeType, Node root, EvaluationCtx context, String xpathVersion) { Iterator it = selectorModules.iterator(); // start with empty list of Attribute Values List<AttributeValue> attributeValues = new ArrayList<AttributeValue>(); // go through each module in order while (it.hasNext()) { AttributeFinderModule module = (AttributeFinderModule) (it.next()); // see if the module can find an attribute value EvaluationResult result = module.findAttribute(contextPath, attributeType, contextSelector, root, context, xpathVersion); // if there was an error, we stop right away if (result.indeterminate()) { logger.error("Error while trying to resolve values: " + result.getStatus().getMessage()); return result; } // if the result wasn't empty, add the found attributes to list of AttributeValues and continue iterating BagAttribute bag = (BagAttribute) (result.getAttributeValue()); if (!bag.isEmpty()) { Iterator iterator = bag.iterator(); while (iterator.hasNext()) { AttributeValue attr = (AttributeValue) (iterator.next()); attributeValues.add(attr); } } } // check whether we were able to find any attributes, if not return an empty bag if (attributeValues.isEmpty()) { // if we got here then there were no errors but there were also no // matches if (logger.isDebugEnabled()) { logger.debug("Failed to resolve any values for " + contextPath); } } return new EvaluationResult(new BagAttribute(attributeType,attributeValues)); } }
13,636
42.155063
117
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/PolicyFinder.java
/* * @(#)PolicyFinder.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * This class is used by the PDP to find all policies used in evaluation. A PDP is given a * pre-configured <code>PolicyFinder</code> on construction. The <code>PolicyFinder</code> provides * the functionality both to find policies based on a request (ie, retrieve policies and match * against the target) and based on an idReference (as can be included in a PolicySet). * <p> * While this class is typically used by the PDP, it is intentionally designed to support * stand-alone use, so it could be the base for a distributed service, or for some application that * needs just this functionality. There is nothing in the <code>PolicyFinder</code that relies on * the functionality in the PDP. An example of this is a PDP that offloads all policy work by * passing requests to another server that does all the retrieval, and passes back the applicable * policy. This would require custom code undefined in the XACML spec, but it would free up the * server to focus on core policy processing. * <p> * Note that it is an error to have more than one top-level policy (as explained in the * OnlyOneApplicable combining algorithm), so any module that is added to this finder will be * evaluated each time a policy is requested. This means that you should think carefully about how * many modules you include, and how they can cache policy data. * * @since 1.0 * @author Seth Proctor */ public class PolicyFinder { /** * all modules in this finder */ private Set allModules; /** * all the request modules */ private Set requestModules; /** * all the reference modules */ private Set referenceModules; /** * the logger we'll use for all messages */ private static final Log logger = LogFactory.getLog(PolicyFinder.class); /** * Default constructor that creates a <code>PDPConfig</code> from components. */ public PolicyFinder() { } /** * Returns the unordered <code>Set</code> of <code>PolicyFinderModule</code>s used by this class * to find policies. * * @return a <code>Set</code> of <code>PolicyFinderModule</code>s */ public Set getModules() { return new HashSet(allModules); } /** * Sets the unordered <code>Set</code> of <code>PolicyFinderModule</code>s used by this class to * find policies. * * @param modules a <code>Set</code> of <code>PolicyFinderModule</code>s */ public void setModules(Set modules) { Iterator it = modules.iterator(); allModules = new HashSet(modules); requestModules = new HashSet(); referenceModules = new HashSet(); while (it.hasNext()) { PolicyFinderModule module = (PolicyFinderModule) (it.next()); if (module.isRequestSupported()) requestModules.add(module); if (module.isIdReferenceSupported()) referenceModules.add(module); } } /** * Initializes all modules in this finder. */ public void init() { if (logger.isDebugEnabled()) { logger.debug("Initializing PolicyFinder"); } Iterator it = allModules.iterator(); while (it.hasNext()) { PolicyFinderModule module = (PolicyFinderModule) (it.next()); module.init(this); } } /** * Finds a policy based on a request's context. This may involve using the request data as * indexing data to lookup a policy. This will always do a Target match to make sure that the * given policy applies. If more than one applicable policy is found, this will return an error. * * @param context the representation of the request data * * @return the result of trying to find an applicable policy */ public PolicyFinderResult findPolicy(EvaluationCtx context) { PolicyFinderResult result = null; Iterator it = requestModules.iterator(); // look through all of the modules while (it.hasNext()) { PolicyFinderModule module = (PolicyFinderModule) (it.next()); PolicyFinderResult newResult = module.findPolicy(context); // if there was an error, we stop right away if (newResult.indeterminate()) { logger.error("An error occured while trying to find a " + "single applicable policy for a request: " + newResult.getStatus().getMessage()); return newResult; } // if we found a policy... if (!newResult.notApplicable()) { // ...if we already had found a policy, this is an error... if (result != null) { logger.error("More than one top-level applicable policy " + "for the request"); ArrayList code = new ArrayList(); code.add(Status.STATUS_PROCESSING_ERROR); Status status = new Status(code, "too many applicable " + "top-level policies"); return new PolicyFinderResult(status); } // ...otherwise we remember the result result = newResult; } } // if we got here then we didn't have any errors, so the only // question is whether or not we found anything if (result != null) { return result; } else { logger.debug("No applicable policies were found for the request"); return new PolicyFinderResult(); } } /** * Finds a policy based on an id reference. This may involve using the reference as indexing * data to lookup a policy. This will always do a Target match to make sure that the given * policy applies. If more than one applicable policy is found, this will return an error. * * @param idReference the identifier used to resolve a policy * @param type type of reference (policy or policySet) as identified by the fields in * <code>PolicyReference</code> * @param constraints any optional constraints on the version of the referenced policy * @param parentMetaData the meta-data from the parent policy, which provides XACML version, * factories, etc. * * @return the result of trying to find an applicable policy * * @throws IllegalArgumentException if <code>type</code> is invalid */ public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints, PolicyMetaData parentMetaData) throws IllegalArgumentException { PolicyFinderResult result = null; Iterator it = referenceModules.iterator(); if ((type != PolicyReference.POLICY_REFERENCE) && (type != PolicyReference.POLICYSET_REFERENCE)) throw new IllegalArgumentException("Unknown reference type"); // look through all of the modules while (it.hasNext()) { PolicyFinderModule module = (PolicyFinderModule) (it.next()); PolicyFinderResult newResult = module.findPolicy(idReference, type, constraints, parentMetaData); // if there was an error, we stop right away if (newResult.indeterminate()) { logger.error("An error occured while trying to find the " + "referenced policy " + idReference.toString() + ": " + newResult.getStatus().getMessage()); return newResult; } // if we found a policy... if (!newResult.notApplicable()) { // ...if we already had found a policy, this is an error... if (result != null) { logger.error("More than one policy applies for the " + "reference: " + idReference.toString()); ArrayList code = new ArrayList(); code.add(Status.STATUS_PROCESSING_ERROR); Status status = new Status(code, "too many applicable " + "top-level policies"); return new PolicyFinderResult(status); } // ...otherwise we remember the result result = newResult; } } // if we got here then we didn't have any errors, so the only // question is whether or not we found anything if (result != null) { return result; } else { logger.debug("No policies were resolved for the reference: " + idReference.toString()); return new PolicyFinderResult(); } } }
10,888
38.596364
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/ResourceFinder.java
/* * @(#)ResourceFinder.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.attr.AttributeValue; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This class is used by the PDP to handle resource scopes other than Immediate. In the case of a * scope of Children or Descendants, the PDP needs a list of Resource Ids to evaluate, each of which * will get its own Result. Like the PolicyFinder, this is not tied in any way to the rest of the * PDP code, and could be provided as a stand-alone resource. * <p> * This class basically is a coordinator that asks each module in turn if it can handle the given * identifier. Evaluation proceeds in order through the given modules, and once a module returns a * non-empty response (whether or not it contains any errors or only errors), the evaluation is * finished and the result is returned. One of the issues here is ordering, since a given resource * may look to several modules like something that they can handle. So, you must be careful when * assigning to ordering of the modules in this finder. * <p> * Note that in release 1.2 the interfaces were updated to include the evaluation context. In the * next major release the interfaces without the context information will be removed, but for now * both exist. This means that if this finder is called with the context, then only the methods in * <code>ResourceFinderModule</code> supporting the context will be called (and likewise only the * methods without context will be called when this finder is called without the context). In * practice this means that the methods with context will always get invoked, since this is what the * default PDP implementation calls. * * @since 1.0 * @author Seth Proctor */ public class ResourceFinder { // the list of all modules private List<ResourceFinderModule> allModules; // the list of child modules private List<ResourceFinderModule> childModules; // the list of descendant modules private List<ResourceFinderModule> descendantModules; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(ResourceFinder.class); /** * Default constructor. */ public ResourceFinder() { allModules = new ArrayList<ResourceFinderModule>(); childModules = new ArrayList<ResourceFinderModule>(); descendantModules = new ArrayList<ResourceFinderModule>(); } /** * Returns the ordered <code>List</code> of <code>ResourceFinderModule</code>s used by this * class to find resources. * * @return a <code>List</code> of <code>ResourceFinderModule</code>s */ public List<ResourceFinderModule> getModules() { return new ArrayList<ResourceFinderModule>(allModules); } /** * Sets the ordered <code>List</code> of <code>ResourceFinderModule</code>s used by this class * to find resources. The ordering will be maintained. * * @param modules a code>List</code> of <code>ResourceFinderModule</code>s */ public void setModules(List<ResourceFinderModule> modules) { Iterator it = modules.iterator(); allModules = new ArrayList<ResourceFinderModule>(modules); childModules = new ArrayList<ResourceFinderModule>(); descendantModules = new ArrayList<ResourceFinderModule>(); while (it.hasNext()) { ResourceFinderModule module = (ResourceFinderModule) (it.next()); if (module.isChildSupported()) childModules.add(module); if (module.isDescendantSupported()) descendantModules.add(module); } } /** * Finds Resource Ids using the Children scope, and returns all resolved identifiers as well as * any errors that occurred. If no modules can handle the given Resource Id, then an empty * result is returned. * * @param parentResourceId the root of the resources * @param context the representation of the request data * * @return the result of looking for child resources */ public ResourceFinderResult findChildResources(AttributeValue parentResourceId, EvaluationCtx context) { Iterator it = childModules.iterator(); while (it.hasNext()) { ResourceFinderModule module = (ResourceFinderModule) (it.next()); // ask the module to find the resources ResourceFinderResult result = module.findChildResources(parentResourceId, context); // if we found something, then always return that result if (!result.isEmpty()) return result; } // no modules applied, so we return an empty result logger.info("No ResourceFinderModule existed to handle the " + "children of " + parentResourceId.encode()); return new ResourceFinderResult(); } /** * Finds Resource Ids using the Children scope, and returns all resolved identifiers as well as * any errors that occurred. If no modules can handle the given Resource Id, then an empty * result is returned. * * @deprecated As of version 1.2, replaced by * {@link #findChildResources(AttributeValue,EvaluationCtx)}. This version does not * provide the evaluation context to the modules, and will be removed in a future * release. * * @param parentResourceId the root of the resources * * @return the result of looking for child resources */ public ResourceFinderResult findChildResources(AttributeValue parentResourceId) { Iterator it = childModules.iterator(); while (it.hasNext()) { ResourceFinderModule module = (ResourceFinderModule) (it.next()); // ask the module to find the resources ResourceFinderResult result = module.findChildResources(parentResourceId); // if we found something, then always return that result if (!result.isEmpty()) return result; } // no modules applied, so we return an empty result logger.info("No ResourceFinderModule existed to handle the " + "children of " + parentResourceId.encode()); return new ResourceFinderResult(); } /** * Finds Resource Ids using the Descendants scope, and returns all resolved identifiers as well * as any errors that occurred. If no modules can handle the given Resource Id, then an empty * result is returned. * * @param parentResourceId the root of the resources * @param context the representation of the request data * * @return the result of looking for descendant resources */ public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId, EvaluationCtx context) { Iterator it = descendantModules.iterator(); while (it.hasNext()) { ResourceFinderModule module = (ResourceFinderModule) (it.next()); // ask the module to find the resources ResourceFinderResult result = module.findDescendantResources(parentResourceId, context); // if we found something, then always return that result if (!result.isEmpty()) return result; } // no modules applied, so we return an empty result logger.info("No ResourceFinderModule existed to handle the " + "descendants of " + parentResourceId.encode()); return new ResourceFinderResult(); } /** * Finds Resource Ids using the Descendants scope, and returns all resolved identifiers as well * as any errors that occurred. If no modules can handle the given Resource Id, then an empty * result is returned. * * @deprecated As of version 1.2, replaced by * {@link #findDescendantResources(AttributeValue,EvaluationCtx)}. This version does * not provide the evaluation context to the modules, and will be removed in a * future release. * * @param parentResourceId the root of the resources * * @return the result of looking for child resources */ public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId) { Iterator it = descendantModules.iterator(); while (it.hasNext()) { ResourceFinderModule module = (ResourceFinderModule) (it.next()); // ask the module to find the resources ResourceFinderResult result = module.findDescendantResources(parentResourceId); // if we found something, then always return that result if (!result.isEmpty()) return result; } // no modules applied, so we return an empty result logger.info("No ResourceFinderModule existed to handle the " + "descendants of " + parentResourceId.encode()); return new ResourceFinderResult(); } }
11,012
40.715909
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/ResourceFinderModule.java
/* * @(#)ResourceFinderModule.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.attr.AttributeValue; /** * This is the abstract class that all <code>ResourceFinder</code> modules extend. All methods have * default values to represent that the given feature isn't supported by this module, so module * writers needs only implement the methods for the features they're supporting. * * @since 1.0 * @author Seth Proctor */ public abstract class ResourceFinderModule { /** * Returns this module's identifier. A module does not need to provide a unique identifier, but * it is a good idea, especially in support of management software. Common identifiers would be * the full package and class name (the default if this method isn't overridden), just the class * name, or some other well-known string that identifies this class. * * @return this module's identifier */ public String getIdentifier() { return getClass().getName(); } /** * Returns true if this module supports finding resources with the "Children" scope. By default * this method returns false. * * @return true if the module supports the Children scope */ public boolean isChildSupported() { return false; } /** * Returns true if this module supports finding resources with the "Descendants" scope. By * default this method returns false. * * @return true if the module supports the Descendants scope */ public boolean isDescendantSupported() { return false; } /** * This is an experimental method that asks the module to invalidate any cache values it may * contain. This is not used by any of the core processing code, but it may be used by * management software that wants to have some control over these modules. Since a module is * free to decide how or if it caches values, and whether it is capable of updating values once * in a cache, a module is free to intrepret this message in any way it sees fit (including * igoring the message). It is preferable, however, for a module to make every effort to clear * any dynamically cached values it contains. * <p> * This method has been introduced to see what people think of this functionality, and how they * would like to use it. It may be removed in future versions, or it may be changed to a more * general message-passing system (if other useful messages are identified). * * @since 1.2 */ public void invalidateCache() { } /** * Tries to find the child Resource Ids associated with the parent. If this module cannot handle * the given identifier, then an empty result is returned, otherwise the result will always * contain at least the parent Resource Id, either as a successfully resolved Resource Id or an * error case, but never both. * * @param parentResourceId the parent resource identifier * @param context the representation of the request data * * @return the result of finding child resources */ public ResourceFinderResult findChildResources(AttributeValue parentResourceId, EvaluationCtx context) { return new ResourceFinderResult(); } /** * Tries to find the child Resource Ids associated with the parent. If this module cannot handle * the given identifier, then an empty result is returned, otherwise the result will always * contain at least the parent Resource Id, either as a successfully resolved Resource Id or an * error case, but never both. * * @deprecated As of version 1.2, replaced by * {@link #findChildResources(AttributeValue,EvaluationCtx)}. This version does not * provide the evaluation context, and will be removed in a future release. Also, * not that this will never get called when using the default PDP. * * @param parentResourceId the parent resource identifier * * @return the result of finding child resources */ public ResourceFinderResult findChildResources(AttributeValue parentResourceId) { return new ResourceFinderResult(); } /** * Tries to find the descendant Resource Ids associated with the parent. If this module cannot * handle the given identifier, then an empty result is returned, otherwise the result will * always contain at least the parent Resource Id, either as a successfuly resolved Resource Id * or an error case, but never both. * * @param parentResourceId the parent resource identifier * @param context the representation of the request data * * @return the result of finding descendant resources */ public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId, EvaluationCtx context) { return new ResourceFinderResult(); } /** * Tries to find the descendant Resource Ids associated with the parent. If this module cannot * handle the given identifier, then an empty result is returned, otherwise the result will * always contain at least the parent Resource Id, either as a successfuly resolved Resource Id * or an error case, but never both. * * @deprecated As of version 1.2, replaced by * {@link #findDescendantResources(AttributeValue,EvaluationCtx)}. This version does * not provide the evaluation context, and will be removed in a future release. * Also, not that this will never get called when using the default PDP. * * @param parentResourceId the parent resource identifier * * @return the result of finding descendant resources */ public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId) { return new ResourceFinderResult(); } }
7,800
43.833333
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/AttributeFinderModule.java
/* * @(#)AttributeFinderModule.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.EvaluationResult; import java.net.URI; import java.util.Set; import org.w3c.dom.Node; /** * This is the abstract class that all <code>AttributeFinder</code> modules extend. All methods have * default values to represent that the given feature isn't supported by this module, so module * writers needs only implement the methods for the features they're supporting. * * @since 1.0 * @author Seth Proctor */ public abstract class AttributeFinderModule { /** * Returns this module's identifier. A module does not need to provide a unique identifier, but * it is a good idea, especially in support of management software. Common identifiers would be * the full package and class name (the default if this method isn't overridden), just the class * name, or some other well-known string that identifies this class. * * @return this module's identifier */ public String getIdentifier() { return getClass().getName(); } /** * Returns true if this module supports retrieving attributes based on the data provided in an * AttributeDesignatorType. By default this method returns false. * * @return true if retrieval based on designator data is supported */ public boolean isDesignatorSupported() { return false; } /** * Returns true if this module supports retrieving attributes based on the data provided in an * AttributeSelectorType. By default this method returns false. * * @return true if retrieval based on selector data is supported */ public boolean isSelectorSupported() { return false; } /** * Returns a <code>Set</code> of <code>String</code>s that represent which AttributeDesignator * categories are supported (eg, Subject, Resource, etc.), or null meaning that no particular types * are supported. A return value of null can mean that this module doesn't support designator * retrieval, or that it supports designators of all types. If the set is non-null, it should * contain the values specified in the <code>AttributeDesignator</code> * * @return a <code>Set</code> of <code>Integer</code>s, or null */ public Set<String> getSupportedCategories() { return null; } /** * Returns a <code>Set</code> of <code>URI</code>s that represent the attributeIds handled by * this module, or null if this module doesn't handle any specific attributeIds. A return value * of null means that this module will try to resolve attributes of any id. * * @return a <code>Set</code> of <code>URI</code>s, or null */ public Set getSupportedIds() { return null; } /** * This is an experimental method that asks the module to invalidate any cache values it may * contain. This is not used by any of the core processing code, but it may be used by * management software that wants to have some control over these modules. Since a module is * free to decide how or if it caches values, and whether it is capable of updating values once * in a cache, a module is free to intrepret this message in any way it sees fit (including * igoring the message). It is preferable, however, for a module to make every effort to clear * any dynamically cached values it contains. * <p> * This method has been introduced to see what people think of this functionality, and how they * would like to use it. It may be removed in future versions, or it may be changed to a more * general message-passing system (if other useful messages are identified). * * @since 1.2 */ public void invalidateCache() { } /** * Tries to find attribute values based on the given designator data. The result, if successful, * must always contain a <code>BagAttribute</code>, even if only one value was found. If no * values were found, but no other error occurred, an empty bag is returned. This method may * need to invoke the context data to look for other attribute values, so a module writer must * take care not to create a scenario that loops forever. * * @param attributeType the datatype of the attributes to find * @param attributeId the identifier of the attributes to find * @param issuer the issuer of the attributes, or null if unspecified * @param category the category of the attribute whether it is Subject, Resource or any thing * @param context the representation of the request data * * @return the result of attribute retrieval, which will be a bag of attributes or an error */ public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, URI category, EvaluationCtx context) { return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } /** * Tries to find attribute values based on the given selector data. The result, if successful, * must always contain a <code>BagAttribute</code>, even if only one value was found. If no * values were found, but no other error occurred, an empty bag is returned. This method may * need to invoke the context data to look for other attribute values, so a module writer must * take care not to create a scenario that loops forever. * * @param contextPath the XPath expression to search against * @param attributeType the datatype of the attributes to find * @param contextSelector the selector to find the context to apply XPath expression * if this is null, applied for default content. This is only used with XACML 3.0 * @param root the DOM node that XPath evaluation is done. this only used by XACML 3.0 * this can be null, if other XACML versions are used. * @param context the representation of the request data * @param xpathVersion the XPath version to use * * @return the result of attribute retrieval, which will be a bag of attributes or an error */ public EvaluationResult findAttribute(String contextPath, URI attributeType, String contextSelector, Node root, EvaluationCtx context, String xpathVersion) { return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } }
8,349
45.388889
103
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/PolicyFinderModule.java
/* * @(#)PolicyFinderModule.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.VersionConstraints; import java.net.URI; /** * This is the abstract class that all <code>PolicyFinder</code> modules extend. All methods have * default values to represent that the given feature isn't supported by this module, so module * writers needs only implement the methods for the features they're supporting. * * @since 1.0 * @author Seth Proctor */ public abstract class PolicyFinderModule { /** * Returns this module's identifier. A module does not need to provide a unique identifier, but * it is a good idea, especially in support of management software. Common identifiers would be * the full package and class name (the default if this method isn't overridden), just the class * name, or some other well-known string that identifies this class. * * @return this module's identifier */ public String getIdentifier() { return getClass().getName(); } /** * Returns true if the module supports finding policies based on a request (ie, target * matching). By default this method returns false. * * @return true if request retrieval is supported */ public boolean isRequestSupported() { return false; } /** * Returns true if the module supports finding policies based on an id reference (in a * PolicySet). By default this method returns false. * * @return true if idReference retrieval is supported */ public boolean isIdReferenceSupported() { return false; } /** * Initializes this module for use by the given finder. Typically this is called when a * <code>PDP</code> is initialized with a <code>PDPConfig</code> containing the given * <code>PolicyFinder</code>. Because <code>PolicyFinderModule</code>s usually need to parse * policies, and this requires knowing their <code>PolicyFinder<code>, * parsing is usually done at or after this point in the lifetime * of this module. This might also be a good time to reset any internal * caches or temporary data. Note that this method may be called more * than once in the lifetime of a module. * * @param finder the <code>PolicyFinder</code> using this module */ public abstract void init(PolicyFinder finder); /** * This is an experimental method that asks the module to invalidate any cache values it may * contain. This is not used by any of the core processing code, but it may be used by * management software that wants to have some control over these modules. Since a module is * free to decide how or if it caches values, and whether it is capable of updating values once * in a cache, a module is free to intrepret this message in any way it sees fit (including * igoring the message). It is preferable, however, for a module to make every effort to clear * any dynamically cached values it contains. * <p> * This method has been introduced to see what people think of this functionality, and how they * would like to use it. It may be removed in future versions, or it may be changed to a more * general message-passing system (if other useful messages are identified). * * @since 1.2 */ public void invalidateCache() { } /** * Tries to find one and only one matching policy given the request represented by the context * data. If more than one policy is found, this is an error and must be reported as such. If no * policies are found, then an empty result must be returned. By default this method returns an * empty result. This method should never return null. * * @param context the representation of the request * * @return the result of looking for a matching policy */ public PolicyFinderResult findPolicy(EvaluationCtx context) { return new PolicyFinderResult(); } /** * Tries to find one and only one matching policy given the idReference If more than one policy * is found, this is an error and must be reported as such. If no policies are found, then an * empty result must be returned. By default this method returns an empty result. This method * should never return null. * * @param idReference an identifier specifying some policy * @param type type of reference (policy or policySet) as identified by the fields in * <code>PolicyReference</code> * @param constraints any optional constraints on the version of the referenced policy (this * will never be null, but it may impose no constraints, and in fact will never * impose constraints when used from a pre-2.0 XACML policy) * @param parentMetaData the meta-data from the parent policy, which provides XACML version, * factories, etc. * * @return the result of looking for a matching policy */ public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints, PolicyMetaData parentMetaData) { return new PolicyFinderResult(); } }
7,099
44.512821
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/impl/CurrentEnvModule.java
/* * @(#)CurrentEnvModule.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder.impl; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.XACMLConstants; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.attr.DateAttribute; import org.wso2.balana.attr.DateTimeAttribute; import org.wso2.balana.attr.TimeAttribute; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.Status; import org.wso2.balana.finder.AttributeFinderModule; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Supports the current date, time, and dateTime values. The XACML specification states that these * three values must always be available to a PDP. They may be included in the request, but if * they're not, a PDP must be able to recognize the attribute and generate a correct value. * <p> * The XACML specification doesn't require that values be cached (ie, remain consistent within an * evaluation), but does allow it. Any caching, as well as details of which time to use (time at the * PEP, PDP, etc.) is taken care of by the <code>EvaluationCtx</code> which is used to supply the * current values. * * @since 1.0 * @author Seth Proctor */ public class CurrentEnvModule extends AttributeFinderModule { /** * Standard environment variable that represents the current time */ public static final String ENVIRONMENT_CURRENT_TIME = "urn:oasis:names:tc:xacml:1.0:environment:current-time"; /** * Standard environment variable that represents the current date */ public static final String ENVIRONMENT_CURRENT_DATE = "urn:oasis:names:tc:xacml:1.0:environment:current-date"; /** * Standard environment variable that represents the current date and time */ public static final String ENVIRONMENT_CURRENT_DATETIME = "urn:oasis:names:tc:xacml:1.0:environment:current-dateTime"; /** * Returns true always because this module supports designators. * * @return true always */ public boolean isDesignatorSupported() { return true; } /** * Returns a <code>Set</code> with a single <code>String</code> specifying that environment * attributes are supported by this module. * * @return a <code>Set</code> with <code>AttributeDesignator</code> included */ public Set<String> getSupportedCategories() { HashSet<String> set = new HashSet<String>(); set.add(XACMLConstants.ENT_CATEGORY); return set; } /** * Used to get the current time, date, or dateTime. If one of those values isn't being asked * for, or if the types are wrong, then an empty bag is returned. * * @param attributeType the datatype of the attributes to find, which must be time, date, or * dateTime for this module to resolve a value * @param attributeId the identifier of the attributes to find, which must be one of the three * ENVIRONMENT_* fields for this module to resolve a value * @param issuer the issuer of the attributes, or null if unspecified * @param category the category of the attribute * @param context the representation of the request data * * @return the result of attribute retrieval, which will be a bag with a single attribute, an * empty bag, or an error */ public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, URI category, EvaluationCtx context) { // we only know about environment attributes if (!XACMLConstants.ENT_CATEGORY.equals(category.toString())){ return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } // figure out which attribute we're looking for String attrName = attributeId.toString(); if (attrName.equals(ENVIRONMENT_CURRENT_TIME)) { return handleTime(attributeType, issuer, context); } else if (attrName.equals(ENVIRONMENT_CURRENT_DATE)) { return handleDate(attributeType, issuer, context); } else if (attrName.equals(ENVIRONMENT_CURRENT_DATETIME)) { return handleDateTime(attributeType, issuer, context); } // if we got here, then it's an attribute that we don't know return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } /** * Handles requests for the current Time. */ private EvaluationResult handleTime(URI type, String issuer, EvaluationCtx context) { // make sure they're asking for a time attribute if (!type.toString().equals(TimeAttribute.identifier)) return new EvaluationResult(BagAttribute.createEmptyBag(type)); // get the value from the context return makeBag(context.getCurrentTime()); } /** * Handles requests for the current Date. */ private EvaluationResult handleDate(URI type, String issuer, EvaluationCtx context) { // make sure they're asking for a date attribute if (!type.toString().equals(DateAttribute.identifier)) return new EvaluationResult(BagAttribute.createEmptyBag(type)); // get the value from the context return makeBag(context.getCurrentDate()); } /** * Handles requests for the current DateTime. */ private EvaluationResult handleDateTime(URI type, String issuer, EvaluationCtx context) { // make sure they're asking for a dateTime attribute if (!type.toString().equals(DateTimeAttribute.identifier)) return new EvaluationResult(BagAttribute.createEmptyBag(type)); // get the value from the context return makeBag(context.getCurrentDateTime()); } /** * Private helper that generates a new processing error status and includes the given string. */ private EvaluationResult makeProcessingError(String message) { ArrayList code = new ArrayList(); code.add(Status.STATUS_PROCESSING_ERROR); return new EvaluationResult(new Status(code, message)); } /** * Private helper that makes a bag containing only the given attribute. */ private EvaluationResult makeBag(AttributeValue attribute) { List<AttributeValue> set = new ArrayList<AttributeValue>(); set.add(attribute); BagAttribute bag = new BagAttribute(attribute.getType(), set); return new EvaluationResult(bag); } }
8,347
39.721951
122
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/impl/SelectorModule.java
/* * @(#)SelectorModule.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.finder.impl; import org.w3c.dom.Document; import org.wso2.balana.*; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.Status; import org.wso2.balana.finder.AttributeFinderModule; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.utils.Utils; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.*; /** * This module implements the basic behavior of the AttributeSelectorType, looking for attribute * values in the physical request document using the given XPath expression. This is implemented as * a separate module (instead of being implemented directly in <code>AttributeSelector</code> so * that programmers can remove this functionality if they want (it's optional in the spec), so they * can replace this code with more efficient, specific code as needed, and so they can easily swap * in different XPath libraries. * <p> * Note that if no matches are found, this module will return an empty bag (unless some error * occurred). The <code>AttributeSelector</code> is still deciding what to return to the policy * based on the MustBePresent attribute. * <p> * This module uses the Xalan XPath implementation, and supports only version 1.0 of XPath. It is a * fully functional, correct implementation of XACML's AttributeSelector functionality, but is not * designed for environments that make significant use of XPath queries. Developers for any such * environment should consider implementing their own module. * * @since 1.0 * @author Seth Proctor */ public class SelectorModule extends AttributeFinderModule { /** * Returns true since this module supports retrieving attributes based on the data provided in * an AttributeSelectorType. * * @return true */ public boolean isSelectorSupported() { return true; } @Override public EvaluationResult findAttribute(String contextPath, URI attributeType, String contextSelector, Node root, EvaluationCtx context, String xpathVersion) { Node contextNode = null; NamespaceContext namespaceContext = null; if(root == null){ // root == null means there is not content element defined with the attributes element // therefore complete request is evaluated. // get the DOM root of the request document contextNode = context.getRequestRoot(); } else if(contextSelector != null) { // root != null means content element is there. we can find the context node by // evaluating the contextSelector // 1st assume context node as the root contextNode = root; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); //see if the request root is in a namespace String namespace = null; if(contextNode != null){ namespace = contextNode.getNamespaceURI(); } // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = contextNode.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue= n.getNodeValue(); nsMap.put(prefix, nodeValue); } // if there is not any namespace is defined for content element, default XACML request // name space would be there. if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)){ nsMap.put("xacml", namespace); } namespaceContext = new DefaultNamespaceContext(nsMap); xpath.setNamespaceContext(namespaceContext); try{ XPathExpression expression = xpath.compile(contextSelector); NodeList result = (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET); if(result == null || result.getLength() == 0){ throw new Exception("No node is found from context selector id evaluation"); } else if(result.getLength() != 1){ throw new Exception("More than one node is found from context selector id evaluation"); } contextNode = result.item(0); if(contextNode != null){ // make the node appear to be a direct child of the Document try{ DocumentBuilderFactory dbf = Utils.getSecuredDocumentBuilderFactory(); DocumentBuilder builder = dbf.newDocumentBuilder(); dbf.setNamespaceAware(true); Document docRoot = builder.newDocument(); Node topRoot = docRoot.importNode(contextNode, true); docRoot.appendChild(topRoot); contextNode = docRoot.getDocumentElement(); } catch (Exception e){ // } } } catch (Exception e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } } else { contextNode = root; } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if(namespaceContext == null){ //see if the request root is in a namespace String namespace = null; if(contextNode != null){ namespace = contextNode.getNamespaceURI(); } // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = contextNode.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue= n.getNodeValue(); nsMap.put(prefix, nodeValue); } // if there is not any namespace is defined for content element, default XACML request // name space would be there. if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)){ nsMap.put("xacml", namespace); } namespaceContext = new DefaultNamespaceContext(nsMap); } xpath.setNamespaceContext(namespaceContext); NodeList matches; try { XPathExpression expression = xpath.compile(contextPath); matches = (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET); if(matches == null || matches.getLength() < 1){ throw new Exception("No node is found from xpath evaluation"); } } catch (XPathExpressionException e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } catch (Exception e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } if (matches.getLength() == 0) { // we didn't find anything, so we return an empty bag return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } // there was at least one match, so try to generate the values try { ArrayList<AttributeValue> list = new ArrayList<AttributeValue>(); AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); for (int i = 0; i < matches.getLength(); i++) { String text = null; Node node = matches.item(i); short nodeType = node.getNodeType(); // see if this is straight text, or a node with data under // it and then get the values accordingly if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE) || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) { // there is no child to this node text = node.getNodeValue(); } else { // the data is in a child node text = node.getFirstChild().getNodeValue(); } list.add(attrFactory.createValue(attributeType, text)); } return new EvaluationResult(new BagAttribute(attributeType, list)); } catch (ParsingException pe) { ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); return new EvaluationResult(new Status(code, pe.getMessage())); } catch (UnknownIdentifierException uie) { ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); return new EvaluationResult(new Status(code, "Unknown attribute type : " + attributeType)); } } }
12,655
42.641379
118
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/finder/impl/FileBasedPolicyFinderModule.java
/* * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.finder.impl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.DOMHelper; import org.wso2.balana.MatchResult; import org.wso2.balana.Policy; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.PolicyReference; import org.wso2.balana.PolicySet; import org.wso2.balana.VersionConstraints; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.combine.xacml2.DenyOverridesPolicyAlg; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import org.wso2.balana.finder.PolicyFinder; import org.wso2.balana.finder.PolicyFinderModule; import org.wso2.balana.finder.PolicyFinderResult; import org.wso2.balana.utils.Utils; /** * This is file based policy repository. Policies can be inside the directory in a file system. * Then you can set directory location using "org.wso2.balana.PolicyDirectory" JAVA property */ public class FileBasedPolicyFinderModule extends PolicyFinderModule { private PolicyFinder finder = null; private Map<URI, AbstractPolicy> policies; private Set<String> policyLocations; private PolicyCombiningAlgorithm combiningAlg; /** * the logger we'll use for all messages */ private static final Log log = LogFactory.getLog(FileBasedPolicyFinderModule.class); public static final String POLICY_DIR_PROPERTY = "org.wso2.balana.PolicyDirectory"; public FileBasedPolicyFinderModule() { policies = new HashMap<URI, AbstractPolicy>(); if (System.getProperty(POLICY_DIR_PROPERTY) != null) { policyLocations = new HashSet<String>(); policyLocations.add(System.getProperty(POLICY_DIR_PROPERTY)); } } public FileBasedPolicyFinderModule(Set<String> policyLocations) { policies = new HashMap<URI, AbstractPolicy>(); this.policyLocations = policyLocations; } @Override public void init(PolicyFinder finder) { this.finder = finder; loadPolicies(); combiningAlg = new DenyOverridesPolicyAlg(); } @Override public PolicyFinderResult findPolicy(EvaluationCtx context) { ArrayList<AbstractPolicy> selectedPolicies = new ArrayList<AbstractPolicy>(); Set<Map.Entry<URI, AbstractPolicy>> entrySet = policies.entrySet(); // iterate through all the policies we currently have loaded for (Map.Entry<URI, AbstractPolicy> entry : entrySet) { AbstractPolicy policy = entry.getValue(); MatchResult match = policy.match(context); int result = match.getResult(); // if target matching was indeterminate, then return the error if (result == MatchResult.INDETERMINATE) return new PolicyFinderResult(match.getStatus()); // see if the target matched if (result == MatchResult.MATCH) { if ((combiningAlg == null) && (selectedPolicies.size() > 0)) { // we found a match before, so this is an error ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); Status status = new Status(code, "too many applicable " + "top-level policies"); return new PolicyFinderResult(status); } // this is the first match we've found, so remember it selectedPolicies.add(policy); } } // no errors happened during the search, so now take the right // action based on how many policies we found switch (selectedPolicies.size()) { case 0: if (log.isDebugEnabled()) { log.debug("No matching XACML policy found"); } return new PolicyFinderResult(); case 1: return new PolicyFinderResult((selectedPolicies.get(0))); default: return new PolicyFinderResult(new PolicySet(null, combiningAlg, null, selectedPolicies)); } } @Override public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints, PolicyMetaData parentMetaData) { AbstractPolicy policy = policies.get(idReference); if (policy != null) { if (type == PolicyReference.POLICY_REFERENCE) { if (policy instanceof Policy) { return new PolicyFinderResult(policy); } } else { if (policy instanceof PolicySet) { return new PolicyFinderResult(policy); } } } // if there was an error loading the policy, return the error ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); Status status = new Status(code, "couldn't load referenced policy"); return new PolicyFinderResult(status); } @Override public boolean isIdReferenceSupported() { return true; } @Override public boolean isRequestSupported() { return true; } /** * Re-sets the policies known to this module to those contained in the * given files. */ protected void loadPolicies() { policies.clear(); for (String policyLocation : policyLocations) { File file = new File(policyLocation); if (!file.exists()) { continue; } if (file.isDirectory()) { String[] files = file.list(); if (files != null) { for (String policyFileLocation : files) { File policyFile = new File(policyLocation + File.separator + policyFileLocation); // we check for hidden files to avoid hidden OS files. if (!policyFile.isDirectory() && !policyFile.isHidden()) { loadPolicy(policyLocation + File.separator + policyFileLocation, finder); } } } } else { loadPolicy(policyLocation, finder); } } } /** * Private helper that tries to load the given file-based policy, and * returns null if any error occurs. * * @param policyFile file path to policy * @param finder policy finder * @return org.w3c.dom.Element */ protected Element loadPolicy(String policyFile, PolicyFinder finder) { Element root = null; AbstractPolicy policy = null; InputStream stream = null; try { // create the factory DocumentBuilderFactory factory = Utils.getSecuredDocumentBuilderFactory(); factory.setIgnoringComments(true); factory.setNamespaceAware(true); factory.setValidating(false); // create a builder based on the factory & try to load the policy DocumentBuilder db = factory.newDocumentBuilder(); stream = new FileInputStream(policyFile); Document doc = db.parse(stream); // handle the policy, if it's a known type root = doc.getDocumentElement(); String name = DOMHelper.getLocalName(root); if (name.equals("Policy")) { policy = Policy.getInstance(root); } else if (name.equals("PolicySet")) { policy = PolicySet.getInstance(root, finder); } } catch (Exception e) { // just only logs log.error("Fail to load policy : " + policyFile, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { log.error("Error while closing input stream"); } } } if (policy != null) { policies.put(policy.getId(), policy); } return root; } }
9,244
33.625468
105
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/SyntaxError.java
package com.semmle.jcorn; import com.semmle.js.ast.Position; public class SyntaxError extends RuntimeException { private static final long serialVersionUID = -4883173648492364902L; private final Position position; public SyntaxError(String msg, Position loc, int raisedAt) { super(msg); this.position = loc; } public Position getPosition() { return position; } }
392
19.684211
69
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/Identifiers.java
package com.semmle.jcorn; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /// identifier.js public class Identifiers { public static enum Dialect { ECMA_3, ECMA_5, ECMA_6, ECMA_7, ECMA_8, STRICT, STRICT_BIND } // Reserved word lists for various dialects of the language public static final Map<Dialect, Set<String>> reservedWords = new LinkedHashMap<>(); static { reservedWords.put( Dialect.ECMA_3, stringSet( "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile")); reservedWords.put(Dialect.ECMA_5, stringSet("class enum extends super const export import")); reservedWords.put(Dialect.ECMA_6, stringSet("enum")); reservedWords.put(Dialect.ECMA_7, stringSet("enum")); reservedWords.put(Dialect.ECMA_8, stringSet("enum")); reservedWords.put( Dialect.STRICT, stringSet("implements interface let package private protected public static yield")); reservedWords.put(Dialect.STRICT_BIND, stringSet("eval arguments")); } // And the keywords private static final String ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; private static final String ecma6Keywords = ecma5AndLessKeywords + " const class extends export import super"; public static final Map<Dialect, Set<String>> keywords = new LinkedHashMap<>(); static { keywords.put(Dialect.ECMA_5, stringSet(ecma5AndLessKeywords)); keywords.put(Dialect.ECMA_6, stringSet(ecma6Keywords)); } private static Set<String> stringSet(String words) { Set<String> result = new LinkedHashSet<String>(); for (String word : words.split(" ")) result.add(word); return result; } // ## Character categories private static final String nonASCIIidentifierStartChars = "\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05d0-\\u05ea\\u05f0-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u08a0-\\u08b4\\u08b6-\\u08bd\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e87\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1877\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312d\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fd5\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7ae\\ua7b0-\\ua7b7\\ua7f7-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab65\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc"; private static final String nonASCIIidentifierChars = "\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u08d4-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c03\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0d01-\\u0d03\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d82\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf2-\\u1cf4\\u1cf8\\u1cf9\\u1dc0-\\u1df5\\u1dfb-\\u1dff\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua900-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f"; private static Pattern nonASCIIidentifierStartPattern; private static Pattern nonASCIIidentifierPattern; private static Pattern nonASCIIidentifierStart() { if (nonASCIIidentifierStartPattern == null) nonASCIIidentifierStartPattern = Pattern.compile("[" + nonASCIIidentifierStartChars + "]"); return nonASCIIidentifierStartPattern; } private static Pattern nonASCIIidentifier() { if (nonASCIIidentifierPattern == null) nonASCIIidentifierPattern = Pattern.compile("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); return nonASCIIidentifierPattern; } // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by bin/generate-identifier-regex.js private static final int[] astralIdentifierStartCodes = { 0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 10591, 541 }; private static final int[] astralIdentifierCodes = { 509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239 }; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. private static boolean isInAstralSet(int code, int[] set) { int pos = 0x10000; for (int i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } return false; } // Test whether a given character code starts an identifier. public static boolean isIdentifierStart(int code, boolean astral) { if (code < 65) return code == 36; if (code < 91) return true; if (code < 97) return code == 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart().matcher(str(code)).matches(); if (!astral) return false; return isInAstralSet(code, astralIdentifierStartCodes); } public static boolean isIdentifierChar(int code, boolean astral) { if (code < 48) return code == 36; if (code < 58) return true; if (code < 65) return false; if (code < 91) return true; if (code < 97) return code == 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier().matcher(str(code)).matches(); if (!astral) return false; return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } private static String str(int i) { return new String(Character.toChars(i)); } }
14,866
93.694268
4,956
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/ESNextParser.java
package com.semmle.jcorn; import com.semmle.jcorn.TokenType.Properties; import com.semmle.jcorn.jsx.JSXParser; import com.semmle.js.ast.BindExpression; import com.semmle.js.ast.BlockStatement; import com.semmle.js.ast.CatchClause; import com.semmle.js.ast.ClassDeclaration; import com.semmle.js.ast.ClassExpression; import com.semmle.js.ast.DeclarationFlags; import com.semmle.js.ast.Decorator; import com.semmle.js.ast.DynamicImport; import com.semmle.js.ast.ExportDeclaration; import com.semmle.js.ast.ExportDefaultDeclaration; import com.semmle.js.ast.ExportDefaultSpecifier; import com.semmle.js.ast.ExportNamedDeclaration; import com.semmle.js.ast.ExportNamespaceSpecifier; import com.semmle.js.ast.ExportSpecifier; import com.semmle.js.ast.Expression; import com.semmle.js.ast.FieldDefinition; import com.semmle.js.ast.ForOfStatement; import com.semmle.js.ast.INode; import com.semmle.js.ast.IPattern; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.Literal; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.MemberExpression; import com.semmle.js.ast.MetaProperty; import com.semmle.js.ast.Node; import com.semmle.js.ast.ObjectPattern; import com.semmle.js.ast.Position; import com.semmle.js.ast.Property; import com.semmle.js.ast.RestElement; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.SpreadElement; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Token; import com.semmle.util.collections.CollectionUtil; import com.semmle.util.data.Pair; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * An extension of the {@link JSXParser} with support for various unfinished ECMAScript proposals * that are not supported by Acorn/jcorn yet. * * <p>Once support becomes available, they should be removed from this class. */ public class ESNextParser extends JSXParser { public ESNextParser(Options options, String input, int startPos) { super(options.allowImportExportEverywhere(true), input, startPos); } /* * Support for proposed language feature "Object Rest/Spread Properties" * (http://sebmarkbage.github.io/ecmascript-rest-spread/). */ @Override protected Property parseProperty( boolean isPattern, DestructuringErrors refDestructuringErrors, Map<String, PropInfo> propHash) { Position start = this.startLoc; List<Decorator> decorators = parseDecorators(); Property prop = null; if (this.type == TokenType.ellipsis) { SpreadElement spread = this.parseSpread(null); Expression val; if (isPattern) val = new RestElement(spread.getLoc(), spread.getArgument()); else val = spread; prop = this.finishNode( new Property( new SourceLocation(start), null, val, Property.Kind.INIT.name(), false, false)); } if (prop == null) prop = super.parseProperty(isPattern, refDestructuringErrors, propHash); prop.addDecorators(decorators); return prop; } @Override protected INode toAssignable(INode node, boolean isBinding) { if (node instanceof SpreadElement) return new RestElement(node.getLoc(), ((SpreadElement) node).getArgument()); return super.toAssignable(node, isBinding); } @Override protected void checkLVal(INode expr, boolean isBinding, Set<String> checkClashes) { super.checkLVal(expr, isBinding, checkClashes); if (expr instanceof ObjectPattern) { ObjectPattern op = (ObjectPattern) expr; if (op.hasRest()) checkLVal(op.getRest(), isBinding, checkClashes); } } /* * Support for proposed language feature "Public Class Fields" * (http://jeffmo.github.io/es-class-public-fields/). */ private boolean classProperties() { return options.esnext(); } @Override protected MemberDefinition<?> parseClassPropertyBody( PropertyInfo pi, boolean hadConstructor, boolean isStatic) { if (classProperties() && !pi.isGenerator && this.isClassProperty()) return this.parseFieldDefinition(pi, isStatic); return super.parseClassPropertyBody(pi, hadConstructor, isStatic); } protected boolean isClassProperty() { return this.type == TokenType.eq || this.type == TokenType.semi || this.canInsertSemicolon(); } protected FieldDefinition parseFieldDefinition(PropertyInfo pi, boolean isStatic) { Expression value = null; if (this.type == TokenType.eq) { this.next(); boolean oldInFunc = this.inFunction; this.inFunction = true; value = parseMaybeAssign(false, null, null); this.inFunction = oldInFunc; } this.semicolon(); int flags = DeclarationFlags.getStatic(isStatic) | DeclarationFlags.getComputed(pi.computed); return this.finishNode( new FieldDefinition(new SourceLocation(pi.startLoc), flags, pi.key, value)); } /* * Support for proposed language feature "Generator function.sent Meta Property" * (https://github.com/allenwb/ESideas/blob/master/Generator%20metaproperty.md) */ private boolean functionSent() { return options.esnext(); } @Override protected INode parseFunction( Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean isAsync) { if (isFunctionSent(isStatement)) { Identifier meta = this.finishNode(new Identifier(new SourceLocation(startLoc), "function")); this.next(); Identifier property = parseIdent(true); if (!property.getName().equals("sent")) this.raiseRecoverable( property, "The only valid meta property for function is function.sent"); return this.finishNode(new MetaProperty(new SourceLocation(startLoc), meta, property)); } return super.parseFunction(startLoc, isStatement, allowExpressionBody, isAsync); } protected boolean isFunctionSent(boolean isStatement) { return functionSent() && !isStatement && inGenerator && !inAsync && this.type == TokenType.dot; } /* * Support for proposed language feature "Class and Property Decorators" * (https://github.com/wycats/javascript-decorators) */ private boolean decorators() { return options.esnext(); } protected TokenType at = new TokenType(new Properties("@").beforeExpr()); @Override protected Token getTokenFromCode(int code) { if (decorators() && code == 64) { ++this.pos; return this.finishToken(at); } if (functionBind() && code == 58 && charAt(this.pos + 1) == 58) { this.pos += 2; return this.finishToken(doubleColon); } return super.getTokenFromCode(code); } @Override protected Statement parseStatement(boolean declaration, boolean topLevel, Set<String> exports) { List<Decorator> decorators = this.parseDecorators(); Statement stmt = super.parseStatement(declaration, topLevel, exports); if (!decorators.isEmpty()) { if (stmt instanceof ExportDeclaration) { Node exported = null; if (stmt instanceof ExportDefaultDeclaration) { exported = ((ExportDefaultDeclaration) stmt).getDeclaration(); } else if (stmt instanceof ExportNamedDeclaration) { exported = ((ExportNamedDeclaration) stmt).getDeclaration(); } if (exported instanceof ClassDeclaration) { ((ClassDeclaration) exported).addDecorators(decorators); } else if (exported instanceof ClassExpression) { ((ClassExpression) exported).addDecorators(decorators); } else { this.raise(stmt, "Decorators can only be attached to class exports"); } } else if (stmt instanceof ClassDeclaration) { ((ClassDeclaration) stmt).addDecorators(decorators); } else if (stmt != null) { this.raise(stmt, "Leading decorators must be attached to a class declaration"); } } return stmt; } @Override protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { if (this.type == at) { List<Decorator> decorators = parseDecorators(); ClassExpression ce = (ClassExpression) this.parseClass(startLoc, false); ce.addDecorators(decorators); return ce; } if (this.type == doubleColon) { SourceLocation startLoc = new SourceLocation(this.startLoc); this.next(); int innerStart = this.start; Position innerStartLoc = this.startLoc; Expression callee = parseSubscripts(parseExprAtom(null), innerStart, innerStartLoc, true); if (!(callee instanceof MemberExpression)) this.raiseRecoverable(callee, "Binding should be performed on a member expression."); return this.finishNode(new BindExpression(startLoc, null, callee)); } if (this.type == TokenType._import) { Position startLoc = this.startLoc; this.next(); if (this.eat(TokenType.dot)) { return parseImportMeta(startLoc); } this.expect(TokenType.parenL); return parseDynamicImport(startLoc); } return super.parseExprAtom(refDestructuringErrors); } @Override protected MemberDefinition<?> parseClassMember(boolean hadConstructor) { List<Decorator> decorators = parseDecorators(); MemberDefinition<?> member = super.parseClassMember(hadConstructor); if (!decorators.isEmpty() && member.isConstructor()) this.raiseRecoverable(member, "Decorators cannot be attached to class constructors."); member.addDecorators(decorators); return member; } public List<Decorator> parseDecorators() { List<Decorator> result = new ArrayList<Decorator>(); while (this.type == at) result.add(this.parseDecorator()); return result; } private Decorator parseDecorator() { Position start = startLoc; this.next(); Expression body = parseDecoratorBody(); Decorator decorator = new Decorator(new SourceLocation(start), body); return this.finishNode(decorator); } protected Expression parseDecoratorBody() { Expression base; int startPos = this.start; Position startLoc = this.startLoc; if (this.type == TokenType.parenL) { base = parseParenExpression(); } else { base = parseIdent(true); } return parseSubscripts(base, startPos, startLoc, false); } /* * Support for proposed extensions to `export` * (http://leebyron.com/ecmascript-export-ns-from and http://leebyron.com/ecmascript-export-default-from) */ private boolean exportExtensions() { return options.esnext(); } @Override protected ExportDeclaration parseExportRest(SourceLocation exportStart, Set<String> exports) { if (exportExtensions() && this.isExportDefaultSpecifier()) { Position specStart = this.startLoc; Identifier exported = this.parseIdent(true); ExportDefaultSpecifier defaultSpec = this.finishNode(new ExportDefaultSpecifier(new SourceLocation(specStart), exported)); List<ExportSpecifier> specifiers = CollectionUtil.makeList(defaultSpec); if (this.type == TokenType.comma && this.lookahead(1, true).equals("*")) { this.next(); specStart = this.startLoc; this.expect(TokenType.star); this.expectContextual("as"); exported = this.parseIdent(false); ExportNamespaceSpecifier nsSpec = this.finishNode(new ExportNamespaceSpecifier(new SourceLocation(specStart), exported)); specifiers.add(nsSpec); } else { this.parseExportSpecifiersMaybe(specifiers, exports); } Literal source = (Literal) this.parseExportFrom(specifiers, null, true); return this.finishNode(new ExportNamedDeclaration(exportStart, null, specifiers, source)); } return super.parseExportRest(exportStart, exports); } @Override protected ExportDeclaration parseExportAll( SourceLocation exportStart, Position starLoc, Set<String> exports) { if (exportExtensions() && this.eatContextual("as")) { Identifier exported = this.parseIdent(false); ExportNamespaceSpecifier nsSpec = this.finishNode(new ExportNamespaceSpecifier(new SourceLocation(starLoc), exported)); List<ExportSpecifier> specifiers = CollectionUtil.makeList(nsSpec); this.parseExportSpecifiersMaybe(specifiers, exports); Literal source = (Literal) this.parseExportFrom(specifiers, null, true); return this.finishNode(new ExportNamedDeclaration(exportStart, null, specifiers, source)); } return super.parseExportAll(exportStart, starLoc, exports); } private boolean isExportDefaultSpecifier() { if (this.type == TokenType.name) { return !this.value.equals("type") && !this.value.equals("async") && !this.value.equals("interface") && !this.value.equals("let"); } if (this.type != TokenType._default) return false; return this.lookahead(1, true).equals(",") || this.lookaheadIsIdent("from", true); } private void parseExportSpecifiersMaybe(List<ExportSpecifier> specifiers, Set<String> exports) { if (this.eat(TokenType.comma)) { specifiers.addAll(this.parseExportSpecifiers(exports)); } } /* * Support for proposed language feature "Function Bind Syntax" * (https://github.com/tc39/proposal-bind-operator) */ private boolean functionBind() { return options.esnext(); } protected TokenType doubleColon = new TokenType(new Properties("::").beforeExpr()); @Override protected Pair<Expression, Boolean> parseSubscript( Expression base, Position startLoc, boolean noCalls) { if (!noCalls && this.eat(doubleColon)) { Expression callee = parseSubscripts(parseExprAtom(null), this.start, this.startLoc, true); BindExpression bind = new BindExpression(new SourceLocation(startLoc), base, callee); return Pair.make(this.finishNode(bind), true); } return super.parseSubscript(base, startLoc, noCalls); } /* * Support for proposed language feature "Optional Catch Binding" * (https://github.com/tc39/proposal-optional-catch-binding) */ @Override protected CatchClause parseCatchClause(Position startLoc) { this.next(); Expression param = null; if (this.eat(TokenType.parenL)) { param = this.parseBindingAtom(); this.checkLVal(param, true, null); this.expect(TokenType.parenR); } else if (options.ecmaVersion() < 10) { this.unexpected(); } BlockStatement catchBody = this.parseBlock(false); return this.finishNode( new CatchClause(new SourceLocation(startLoc), (IPattern) param, null, catchBody)); } /* * Support for proposed language feature "Dynamic import" * (https://github.com/tc39/proposal-dynamic-import). */ @Override protected Statement parseImport(Position startLoc) { if (!options.esnext()) return super.parseImport(startLoc); int startPos = this.start; SourceLocation loc = new SourceLocation(startLoc); this.next(); if (this.eat(TokenType.parenL)) { DynamicImport di = parseDynamicImport(startLoc); Expression expr = parseSubscripts(di, startPos, startLoc, false); return parseExpressionStatement(false, startLoc, expr); } else { return super.parseImportRest(loc); } } /** * Parses an import.meta expression, assuming that the initial "import" and "." has been consumed. */ private MetaProperty parseImportMeta(Position loc) { Position propertyLoc = this.startLoc; Identifier property = this.parseIdent(true); if (!property.getName().equals("meta")) { this.unexpected(propertyLoc); } return this.finishNode( new MetaProperty(new SourceLocation(loc), new Identifier(new SourceLocation(loc), "import"), property)); } /** * Parses a dynamic import, assuming that the keyword `import` and the opening parenthesis have * already been consumed. */ private DynamicImport parseDynamicImport(Position startLoc) { Expression source = parseMaybeAssign(false, null, null); this.expect(TokenType.parenR); DynamicImport di = this.finishNode(new DynamicImport(new SourceLocation(startLoc), source)); return di; } /* * Support for proposed language feature "Asynchronous iteration" * (https://github.com/tc39/proposal-async-iteration) */ @Override protected Statement parseForStatement(Position startLoc) { int startPos = this.start; boolean isAwait = false; if (this.inAsync && this.eatContextual("await")) isAwait = true; Statement forStmt = super.parseForStatement(startLoc); if (isAwait) { if (forStmt instanceof ForOfStatement) ((ForOfStatement) forStmt).setAwait(true); else this.raiseRecoverable(startPos, "Only for-of statements can be annotated with 'await'."); } return forStmt; } @Override protected boolean parseGeneratorMarker(boolean isAsync) { // always allow `*`, even if `isAsync` is true return this.eat(TokenType.star); } /* * Support for proposed language feature "Numeric separators" * (https://github.com/tc39/proposal-numeric-separator) */ @Override protected Number readInt(int radix, Integer len) { // implementation mostly copied from super class int start = this.pos, code = -1; double total = 0; // no leading underscore boolean underscoreAllowed = false; for (int i = 0, e = len == null ? Integer.MAX_VALUE : len; i < e; ++i) { if (this.pos >= this.input.length()) break; code = this.input.charAt(this.pos); if (code == '_') { if (underscoreAllowed) { seenUnderscoreNumericSeparator = true; // no adjacent underscores underscoreAllowed = false; ++this.pos; continue; } } else { underscoreAllowed = true; } int val; if (code >= 97) val = code - 97 + 10; // a else if (code >= 65) val = code - 65 + 10; // A else if (code >= 48 && code <= 57) val = code - 48; // 0-9 else val = Integer.MAX_VALUE; if (val >= radix) break; ++this.pos; total = total * radix + val; } if (this.pos == start || len != null && this.pos - start != len) return null; if (code == '_') // no trailing underscore return null; return total; } }
18,193
34.396887
110
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/Locutil.java
package com.semmle.jcorn; import com.semmle.js.ast.Position; import java.util.regex.Matcher; /// locutil.js public class Locutil { /** * The `getLineInfo` function is mostly useful when the `locations` option is off (for performance * reasons) and you want to find the line/column position for a given character offset. `input` * should be the code string that the offset refers into. */ public static Position getLineInfo(String input, int offset) { Matcher lineBreakG = Whitespace.lineBreakG.matcher(input); for (int line = 1, cur = 0; ; ) { if (lineBreakG.find(cur) && lineBreakG.start() < offset) { ++line; cur = lineBreakG.end(); } else { return new Position(line, offset - cur, offset); } } } }
775
30.04
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/Whitespace.java
package com.semmle.jcorn; import java.util.regex.Pattern; /// whitespace.js public class Whitespace { public static final String lineBreak = "\r\n?|\n|\u2028|\u2029"; public static final Pattern lineBreakG = Pattern.compile(lineBreak); // global public static boolean isNewLine(int code) { return code == 10 || code == 13 || code == 0x2028 || code == 0x2029; } public static final String nonASCIIwhitespace = "\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff"; public static final Pattern skipWhiteSpace = Pattern.compile("(?:\\s|//.*|/\\*([^*]|\\*(?!/))*\\*/)*"); // global public static final Pattern skipWhiteSpaceNoNewline = Pattern.compile("(?:[ \\t\\x0B\\f]|//.*|/\\*([^*]|\\*(?!/))*\\*/)*"); }
796
35.227273
111
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/Parser.java
package com.semmle.jcorn; import static com.semmle.jcorn.Whitespace.isNewLine; import static com.semmle.jcorn.Whitespace.lineBreak; import com.semmle.jcorn.Identifiers.Dialect; import com.semmle.jcorn.Options.AllowReserved; import com.semmle.jcorn.TokenType.Properties; import com.semmle.js.ast.ArrayExpression; import com.semmle.js.ast.ArrayPattern; import com.semmle.js.ast.ArrowFunctionExpression; import com.semmle.js.ast.AssignmentExpression; import com.semmle.js.ast.AssignmentPattern; import com.semmle.js.ast.AwaitExpression; import com.semmle.js.ast.BinaryExpression; import com.semmle.js.ast.BlockStatement; import com.semmle.js.ast.BreakStatement; import com.semmle.js.ast.CallExpression; import com.semmle.js.ast.CatchClause; import com.semmle.js.ast.Chainable; import com.semmle.js.ast.ClassBody; import com.semmle.js.ast.ClassDeclaration; import com.semmle.js.ast.ClassExpression; import com.semmle.js.ast.ConditionalExpression; import com.semmle.js.ast.ContinueStatement; import com.semmle.js.ast.DebuggerStatement; import com.semmle.js.ast.DeclarationFlags; import com.semmle.js.ast.DoWhileStatement; import com.semmle.js.ast.EmptyStatement; import com.semmle.js.ast.EnhancedForStatement; import com.semmle.js.ast.ExportAllDeclaration; import com.semmle.js.ast.ExportDeclaration; import com.semmle.js.ast.ExportDefaultDeclaration; import com.semmle.js.ast.ExportNamedDeclaration; import com.semmle.js.ast.ExportSpecifier; import com.semmle.js.ast.Expression; import com.semmle.js.ast.ExpressionStatement; import com.semmle.js.ast.ForInStatement; import com.semmle.js.ast.ForOfStatement; import com.semmle.js.ast.ForStatement; import com.semmle.js.ast.FunctionDeclaration; import com.semmle.js.ast.FunctionExpression; import com.semmle.js.ast.IFunction; import com.semmle.js.ast.INode; import com.semmle.js.ast.IPattern; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.IfStatement; import com.semmle.js.ast.FieldDefinition; import com.semmle.js.ast.ImportDeclaration; import com.semmle.js.ast.ImportDefaultSpecifier; import com.semmle.js.ast.ImportNamespaceSpecifier; import com.semmle.js.ast.ImportSpecifier; import com.semmle.js.ast.LabeledStatement; import com.semmle.js.ast.Literal; import com.semmle.js.ast.LogicalExpression; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.MemberExpression; import com.semmle.js.ast.MetaProperty; import com.semmle.js.ast.MethodDefinition; import com.semmle.js.ast.NewExpression; import com.semmle.js.ast.Node; import com.semmle.js.ast.ObjectExpression; import com.semmle.js.ast.ObjectPattern; import com.semmle.js.ast.ParenthesizedExpression; import com.semmle.js.ast.Position; import com.semmle.js.ast.Program; import com.semmle.js.ast.Property; import com.semmle.js.ast.RestElement; import com.semmle.js.ast.ReturnStatement; import com.semmle.js.ast.SequenceExpression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.SpreadElement; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Super; import com.semmle.js.ast.SwitchCase; import com.semmle.js.ast.SwitchStatement; import com.semmle.js.ast.TaggedTemplateExpression; import com.semmle.js.ast.TemplateElement; import com.semmle.js.ast.TemplateLiteral; import com.semmle.js.ast.ThisExpression; import com.semmle.js.ast.ThrowStatement; import com.semmle.js.ast.Token; import com.semmle.js.ast.TryStatement; import com.semmle.js.ast.UnaryExpression; import com.semmle.js.ast.UpdateExpression; import com.semmle.js.ast.VariableDeclaration; import com.semmle.js.ast.VariableDeclarator; import com.semmle.js.ast.WhileStatement; import com.semmle.js.ast.WithStatement; import com.semmle.js.ast.YieldExpression; import com.semmle.ts.ast.ITypeExpression; import com.semmle.util.collections.CollectionUtil; import com.semmle.util.data.Pair; import com.semmle.util.data.StringUtil; import com.semmle.util.exception.CatastrophicError; import com.semmle.util.exception.Exceptions; import com.semmle.util.io.WholeIO; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Stack; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Java port of Acorn. * * <p>This version corresponds to <a * href="https://github.com/ternjs/acorn/commit/bb54adcdbceef01997a9549732139ca8f53a4e28">Acorn * 4.0.3</a>, but does not support plugins, and always tracks full source locations. */ public class Parser { protected final Options options; protected final Set<String> keywords; private final Set<String> reservedWords, reservedWordsStrict, reservedWordsStrictBind; protected final String input; private boolean containsEsc; protected boolean exprAllowed; protected boolean strict; private boolean inModule; protected boolean inFunction; protected boolean inGenerator; protected boolean inClass; protected boolean inAsync; protected boolean inTemplateElement; protected int pos; protected int lineStart; protected int curLine; protected int start; protected int end; protected TokenType type; protected Object value; protected Position startLoc; protected Position endLoc; protected Position lastTokEndLoc, lastTokStartLoc; protected int lastTokStart, lastTokEnd; protected Stack<TokContext> context; protected int potentialArrowAt; private Stack<LabelInfo> labels; protected int yieldPos, awaitPos; /** * Set to true by {@link ESNextParser#readInt} if the parsed integer contains an underscore. */ protected boolean seenUnderscoreNumericSeparator = false; /** * For readability purposes, we pass this instead of false as the argument to the * hasDeclareKeyword parameter (which only exists in TypeScript). */ private static final boolean noDeclareKeyword = false; /** * For readability purposes, we pass this instead of false as the argument to the isAbstract * parameter (which only exists in TypeScript). */ protected static final boolean notAbstract = false; /** * For readability purposes, we pass this instead of null as the argument to the type annotation * parameters (which only exists in TypeScript). */ private static final ITypeExpression noTypeAnnotation = null; protected static class LabelInfo { String name, kind; int statementStart; public LabelInfo(String name, String kind, int statementStart) { this.name = name; this.kind = kind; this.statementStart = statementStart; } } public static void main(String[] args) { new Parser(new Options(), new WholeIO().strictread(new File(args[0])), 0).parse(); } /// begin state.js public Parser(Options options, String input, int startPos) { this.options = options; this.keywords = new LinkedHashSet<String>( Identifiers.keywords.get( options.ecmaVersion() >= 6 ? Identifiers.Dialect.ECMA_6 : Identifiers.Dialect.ECMA_5)); this.reservedWords = new LinkedHashSet<String>(); if (!options.allowReserved().isTrue()) { this.reservedWords.addAll(Identifiers.reservedWords.get(options.getDialect())); if (options.sourceType().equals("module")) this.reservedWords.add("await"); } this.reservedWordsStrict = new LinkedHashSet<String>(this.reservedWords); this.reservedWordsStrict.addAll(Identifiers.reservedWords.get(Dialect.STRICT)); this.reservedWordsStrictBind = new LinkedHashSet<String>(this.reservedWordsStrict); this.reservedWordsStrictBind.addAll(Identifiers.reservedWords.get(Dialect.STRICT_BIND)); this.input = input; // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos != 0) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = inputSubstring(0, this.lineStart).split(Whitespace.lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = TokenType.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.strict = this.inModule = options.sourceType().equals("module"); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Flags to track whether we are in a function, a generator, an async function, a class. this.inFunction = this.inGenerator = this.inAsync = this.inClass = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = 0; // Labels in scope. this.labels = new Stack<LabelInfo>(); // If enabled, skip leading hashbang line. if (this.pos == 0 && options.allowHashBang() && this.input.startsWith("#!")) this.skipLineComment(2); } public Program parse() { Position startLoc = this.startLoc; this.nextToken(); return this.parseTopLevel(startLoc, this.options.program()); } /// end state.js /// begin location.js protected void raise(int pos, String msg, boolean recoverable) { Position loc = Locutil.getLineInfo(input, pos); raise(loc, msg, recoverable); } protected void raise(int pos, String msg) { raise(pos, msg, false); } protected void raise(Position loc, String msg, boolean recoverable) { msg += " (" + loc.getLine() + ":" + loc.getColumn() + ")"; SyntaxError err = new SyntaxError(msg, loc, this.pos); if (recoverable && options.onRecoverableError() != null) options.onRecoverableError().apply(err); else throw err; } protected void raise(Position loc, String msg) { raise(loc, msg, false); } protected void raise(INode nd, String msg) { raise(nd.getLoc().getStart(), msg, false); } protected void raiseRecoverable(int pos, String msg) { raise(pos, msg, true); } protected void raiseRecoverable(INode nd, String msg) { raise(nd.getLoc().getStart(), msg, true); } protected Position curPosition() { return new Position(curLine, pos - lineStart, pos); } /// end location.js /// begin tokenize.js // Move to the next token protected void next() { if (this.options.onToken() != null) this.options.onToken().apply(mkToken()); this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). public void setStrict(boolean strict) { this.strict = strict; if (this.type != TokenType.num && this.type != TokenType.string) return; this.pos = this.start; while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; --this.curLine; } this.nextToken(); } public TokContext curContext() { return context.peek(); } // Read a single token, updating the parser object's token-related // properties. public Token nextToken() { TokContext curContext = this.curContext(); if (curContext == null || !curContext.preserveSpace) this.skipSpace(); this.start = this.pos; this.startLoc = this.curPosition(); if (this.pos >= this.input.length()) return this.finishToken(TokenType.eof); if (curContext != null && curContext.override != null) return curContext.override.apply(this); else return this.readToken(this.fullCharCodeAtPos()); } protected Token readToken(int code) { // Identifier or keyword. '\\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (Identifiers.isIdentifierStart(code, this.options.ecmaVersion() >= 6) || code == 92 /* '\' */) return this.readWord(); return this.getTokenFromCode(code); } protected int fullCharCodeAtPos() { int code = charAt(this.pos); if (code <= 0xd7ff || code >= 0xe000) return code; int next = charAt(this.pos + 1); return (code << 10) + next - 0x35fdc00; } protected void skipBlockComment() { Position startLoc = this.options.onComment() != null ? this.curPosition() : null; int start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end == -1) this.raise(this.pos - 2, "Unterminated comment"); this.pos = end + 2; Matcher m = Whitespace.lineBreakG.matcher(this.input); int next = start; while (m.find(next) && m.start() < this.pos) { ++this.curLine; lineStart = m.end(); next = lineStart; } if (this.options.onComment() != null) this.options .onComment() .call( true, this.input, inputSubstring(start + 2, end), start, this.pos, startLoc, this.curPosition()); } protected void skipLineComment(int startSkip) { int start = this.pos; Position startLoc = this.options.onComment() != null ? this.curPosition() : null; this.pos += startSkip; int ch = charAt(this.pos); while (this.pos < this.input.length() && ch != 10 && ch != 13 && ch != 8232 && ch != 8233) { ++this.pos; ch = charAt(this.pos); } if (this.options.onComment() != null) this.options .onComment() .call( false, this.input, inputSubstring(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } // Called at the start of the parse and after every token. Skips // whitespace and comments, and. protected void skipSpace() { loop: while (this.pos < this.input.length()) { int ch = this.input.charAt(this.pos); switch (ch) { case 32: case 160: // ' ' ++this.pos; break; case 13: if (charAt(this.pos + 1) == 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; ++this.curLine; this.lineStart = this.pos; break; case 47: // '/' switch (charAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break; case 47: this.skipLineComment(2); break; default: break loop; } break; default: if (ch > 8 && ch < 14 || ch >= 5760 && Whitespace.nonASCIIwhitespace.indexOf(ch) > -1) { ++this.pos; } else { break loop; } } } } // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. protected Token finishToken(TokenType type, Object val) { this.end = this.pos; this.endLoc = this.curPosition(); TokenType prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); return mkToken(); } private Token mkToken() { String src = inputSubstring(start, end); SourceLocation loc = new SourceLocation(src, startLoc, endLoc); String label, keyword; if (isKeyword(src)) { label = keyword = src; } else { label = type.label; keyword = type.keyword; } return new Token(loc, label, keyword); } protected boolean isKeyword(String src) { if (type.keyword != null) return true; if (type == TokenType.name) { if (keywords.contains(src)) return true; if (options.ecmaVersion() >= 6 && ("let".equals(src) || "yield".equals(src))) return true; } return false; } protected Token finishToken(TokenType type) { return finishToken(type, null); } // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // private Token readToken_dot() { int next = charAt(this.pos + 1); if (next >= 48 && next <= 57) return this.readNumber(true); int next2 = charAt(this.pos + 2); if (this.options.ecmaVersion() >= 6 && next == 46 && next2 == 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(TokenType.ellipsis); } else { ++this.pos; return this.finishToken(TokenType.dot); } } private Token readToken_question() { // '?' int next = charAt(this.pos + 1); int next2 = charAt(this.pos + 2); if (this.options.esnext()) { if (next == '.' && !('0' <= next2 && next2 <= '9')) // '?.', but not '?.X' where X is a digit return this.finishOp(TokenType.questiondot, 2); if (next == '?') // '??' return this.finishOp(TokenType.questionquestion, 2); } return this.finishOp(TokenType.question, 1); } private Token readToken_slash() { // '/' int next = charAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp(); } if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.slash, 1); } private Token readToken_mult_modulo_exp(int code) { // '%*' int next = charAt(this.pos + 1); int size = 1; TokenType tokentype = code == 42 ? TokenType.star : TokenType.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion() >= 7 && code == 42 && next == 42) { ++size; tokentype = TokenType.starstar; next = charAt(this.pos + 2); } if (next == 61) return this.finishOp(TokenType.assign, size + 1); return this.finishOp(tokentype, size); } private Token readToken_pipe_amp(int code) { // '|&' int next = charAt(this.pos + 1); if (next == code) return this.finishOp(code == 124 ? TokenType.logicalOR : TokenType.logicalAND, 2); if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(code == 124 ? TokenType.bitwiseOR : TokenType.bitwiseAND, 1); } private Token readToken_caret() { // '^' int next = charAt(this.pos + 1); if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.bitwiseXOR, 1); } private Token readToken_plus_min(int code) { // '+-' int next = charAt(this.pos + 1); if (next == code) { if (next == 45 && charAt(this.pos + 2) == 62 && inputSubstring(this.lastTokEnd, this.pos).matches("(?s).*(?:" + lineBreak + ").*")) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken(); } return this.finishOp(TokenType.incDec, 2); } if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.plusMin, 1); } private Token readToken_lt_gt(int code) { // '<>' int next = charAt(this.pos + 1); int size = 1; if (next == code) { size = code == 62 && charAt(this.pos + 2) == 62 ? 3 : 2; if (charAt(this.pos + size) == 61) return this.finishOp(TokenType.assign, size + 1); return this.finishOp(TokenType.bitShift, size); } if (next == 33 && code == 60 && charAt(this.pos + 2) == 45 && charAt(this.pos + 3) == 45) { if (this.inModule) this.unexpected(); // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4); this.skipSpace(); return this.nextToken(); } if (next == 61) size = 2; return this.finishOp(TokenType.relational, size); } private Token readToken_eq_excl(int code) { // '=!' int next = charAt(this.pos + 1); if (next == 61) return this.finishOp(TokenType.equality, charAt(this.pos + 2) == 61 ? 3 : 2); if (code == 61 && next == 62 && this.options.ecmaVersion() >= 6) { // '=>' this.pos += 2; return this.finishToken(TokenType.arrow); } return this.finishOp(code == 61 ? TokenType.eq : TokenType.prefix, 1); } protected Token getTokenFromCode(int code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: // '.' return this.readToken_dot(); // Punctuation tokens. case 40: ++this.pos; return this.finishToken(TokenType.parenL); case 41: ++this.pos; return this.finishToken(TokenType.parenR); case 59: ++this.pos; return this.finishToken(TokenType.semi); case 44: ++this.pos; return this.finishToken(TokenType.comma); case 91: ++this.pos; return this.finishToken(TokenType.bracketL); case 93: ++this.pos; return this.finishToken(TokenType.bracketR); case 123: ++this.pos; return this.finishToken(TokenType.braceL); case 125: ++this.pos; return this.finishToken(TokenType.braceR); case 58: ++this.pos; return this.finishToken(TokenType.colon); case 35: ++this.pos; return this.finishToken(TokenType.pound); case 63: return this.readToken_question(); case 96: // '`' if (this.options.ecmaVersion() < 6) break; ++this.pos; return this.finishToken(TokenType.backQuote); case 48: // '0' int next = charAt(this.pos + 1); if (next == 120 || next == 88) return this.readRadixNumber(16); // '0x', '0X' - hex number if (this.options.ecmaVersion() >= 6) { if (next == 111 || next == 79) return this.readRadixNumber(8); // '0o', '0O' - octal number if (next == 98 || next == 66) return this.readRadixNumber(2); // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 return this.readNumber(false); // Quotes produce strings. case 34: case 39: // '"', "'" return this.readString((char) code); // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: // '/' return this.readToken_slash(); case 37: case 42: // '%*' return this.readToken_mult_modulo_exp(code); case 124: case 38: // '|&' return this.readToken_pipe_amp(code); case 94: // '^' return this.readToken_caret(); case 43: case 45: // '+-' return this.readToken_plus_min(code); case 60: case 62: // '<>' return this.readToken_lt_gt(code); case 61: case 33: // '=!' return this.readToken_eq_excl(code); case 126: // '~' return this.finishOp(TokenType.prefix, 1); } String msg = String.format("Unexpected character '%s' (U+%04X)", codePointToString(code), code); this.raise(this.pos, msg); return null; } protected Token finishOp(TokenType type, int size) { String str = inputSubstring(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str); } private Token readRegexp() { boolean escaped = false, inClass = false; int start = this.pos; for (; ; ) { if (this.pos >= this.input.length()) this.raise(start, "Unterminated regular expression"); int ch = this.input.charAt(this.pos); if (isNewLine(ch)) this.raise(start, "Unterminated regular expression"); if (!escaped) { if (ch == '[') inClass = true; else if (ch == ']' && inClass) inClass = false; else if (ch == '/' && !inClass) break; escaped = ch == '\\'; } else { escaped = false; } ++this.pos; } String content = inputSubstring(start, this.pos); ++this.pos; // Need to use `readWord1` because '\\uXXXX' sequences are allowed // here (don't ask). String mods = this.readWord1(); if (mods != null) { String validFlags = "gim"; if (this.options.ecmaVersion() >= 6) validFlags = "gimuy"; if (this.options.ecmaVersion() >= 9) validFlags = "gimsuy"; if (!mods.matches("^[" + validFlags + "]*$")) this.raise(start, "Invalid regular expression flag"); if (mods.indexOf('u') >= 0) { Matcher m = Pattern.compile("\\\\u\\{([0-9a-fA-F]+)\\}").matcher(content); while (m.find()) { try { int code = Integer.parseInt(m.group(1), 16); if (code > 0x10FFFF) this.raiseRecoverable(start + m.start() + 3, "Code point out of bounds"); } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "Don't complain about code points we don't understand."); } } } } return this.finishToken(TokenType.regexp, content); } // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. protected Number readInt(int radix, Integer len) { int start = this.pos; double total = 0; for (int i = 0, e = len == null ? Integer.MAX_VALUE : len; i < e; ++i) { if (this.pos >= this.input.length()) break; int code = this.input.charAt(this.pos), val; if (code >= 97) val = code - 97 + 10; // a else if (code >= 65) val = code - 65 + 10; // A else if (code >= 48 && code <= 57) val = code - 48; // 0-9 else val = Integer.MAX_VALUE; if (val >= radix) break; ++this.pos; total = total * radix + val; } if (this.pos == start || len != null && this.pos - start != len) return null; return total; } protected Token readRadixNumber(int radix) { this.pos += 2; // 0x Number val = this.readInt(radix, null); if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix); // check for bigint literal if (options.esnext() && this.fullCharCodeAtPos() == 'n') { ++this.pos; return this.finishToken(TokenType.bigint, val); } if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false)) this.raise(this.pos, "Identifier directly after number"); return this.finishToken(TokenType.num, val); } // Read an integer, octal integer, or floating-point number. protected Token readNumber(boolean startsWithDot) { int start = this.pos; boolean isFloat = false, octal = charAt(this.pos) == 48, isBigInt = false; if (!startsWithDot && this.readInt(10, null) == null) this.raise(start, "Invalid number"); if (octal && this.pos == start + 1) octal = false; if (this.pos < this.input.length()) { int next = this.input.charAt(this.pos); if (next == 46 && !octal) { // '.' ++this.pos; this.readInt(10, null); isFloat = true; next = charAt(this.pos); } if ((next == 69 || next == 101) && !octal) { // 'eE' next = charAt(++this.pos); if (next == 43 || next == 45) ++this.pos; // '+-' if (this.readInt(10, null) == null) this.raise(start, "Invalid number"); isFloat = true; } if (!isFloat && options.esnext() && this.fullCharCodeAtPos() == 'n') isBigInt = true; else if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false)) this.raise(this.pos, "Identifier directly after number"); } String str = inputSubstring(start, this.pos); if (seenUnderscoreNumericSeparator) { str = str.replace("_", ""); seenUnderscoreNumericSeparator = false; } Number val = null; if (isFloat) val = parseFloat(str); else if (!octal || str.length() == 1) val = parseInt(str, 10); else if (str.matches(".*[89].*") || this.strict) this.raise(start, "Invalid number"); else val = parseInt(str, 8); // handle bigints if (isBigInt) { ++this.pos; return this.finishToken(TokenType.bigint, val); } return this.finishToken(TokenType.num, val); } // Read a string value, interpreting backslash-escapes. protected int readCodePoint() { int ch = charAt(this.pos), code; if (ch == 123) { if (this.options.ecmaVersion() < 6) this.unexpected(); int codePos = ++this.pos; code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) this.invalidStringToken(codePos, "Code point out of bounds"); } else { code = this.readHexChar(4); } return code; } protected String codePointToString(int code) { // UTF-16 Decoding if (code <= 0xFFFF) return String.valueOf((char) code); code -= 0x10000; return new String(new char[] {(char) ((code >> 10) + 0xD800), (char) ((code & 1023) + 0xDC00)}); } protected Token readString(char quote) { StringBuilder out = new StringBuilder(); int chunkStart = ++this.pos; for (; ; ) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated string constant"); int ch = this.input.charAt(this.pos); if (ch == quote) break; if (ch == 92) { // '\' out.append(inputSubstring(chunkStart, this.pos)); out.append(this.readEscapedChar(false)); chunkStart = this.pos; } else if (options.ecmaVersion() >= 10 && (ch == 0x2028 || ch == 0x2029)) { // ECMAScript 2019 allows Unicode newlines in string literals ++this.pos; } else { if (Whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant"); ++this.pos; } } out.append(inputSubstring(chunkStart, this.pos++)); return this.finishToken(TokenType.string, out.toString()); } // Reads template string tokens. private static final RuntimeException INVALID_TEMPLATE_ESCAPE_ERROR = new RuntimeException(); private Token tryReadTemplateToken() { this.inTemplateElement = true; try { return this.readTmplToken(); } catch (RuntimeException err) { if (err == INVALID_TEMPLATE_ESCAPE_ERROR) { return this.readInvalidTemplateToken(); } else { throw err; } } finally { this.inTemplateElement = false; } } private void invalidStringToken(int position, String message) { if (this.inTemplateElement && this.options.ecmaVersion() >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR; } else { this.raise(position, message); } } protected Token readTmplToken() { StringBuilder out = new StringBuilder(); int chunkStart = this.pos; for (; ; ) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated template"); int ch = this.input.charAt(this.pos); if (ch == 96 || ch == 36 && charAt(this.pos + 1) == 123) { // '`', '${' if (this.pos == this.start && (this.type == TokenType.template || this.type == TokenType.invalidTemplate)) { if (ch == 36) { this.pos += 2; return this.finishToken(TokenType.dollarBraceL); } else { ++this.pos; return this.finishToken(TokenType.backQuote); } } out.append(inputSubstring(chunkStart, this.pos)); return this.finishToken(TokenType.template, out.toString()); } if (ch == 92) { // '\' out.append(inputSubstring(chunkStart, this.pos)); out.append(this.readEscapedChar(true)); chunkStart = this.pos; } else if (Whitespace.isNewLine(ch)) { out.append(inputSubstring(chunkStart, this.pos)); ++this.pos; switch (ch) { case 13: if (charAt(this.pos) == 10) ++this.pos; case 10: out.append('\n'); break; default: out.append((char) ch); break; } ++this.curLine; this.lineStart = this.pos; chunkStart = this.pos; } else { ++this.pos; } } } // Reads a template token to search for the end, without validating any escape sequences private Token readInvalidTemplateToken() { for (; this.pos < this.input.length(); this.pos++) { switch (this.input.charAt(this.pos)) { case '\\': ++this.pos; break; case '$': if (this.charAt(this.pos + 1) != '{') { break; } // falls through case '`': return this.finishToken( TokenType.invalidTemplate, this.inputSubstring(this.start, this.pos)); // no default } } this.raise(this.start, "Unterminated template"); return null; } // Used to read escaped characters protected String readEscapedChar(boolean inTemplate) { int ch = charAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n"; // 'n' -> '\n' case 114: return "\r"; // 'r' -> '\r' case 120: return String.valueOf((char) this.readHexChar(2)); // 'x' case 117: return codePointToString(this.readCodePoint()); // 'u' case 116: return "\t"; // 't' -> '\t' case 98: return "\b"; // 'b' -> '\b' case 118: return "\u000b"; // 'v' -> '\u000b' case 102: return "\f"; // 'f' -> '\f' case 13: if (charAt(this.pos) == 10) ++this.pos; // '\r\n' case 10: // ' \n' this.lineStart = this.pos; ++this.curLine; return ""; default: if (ch >= 48 && ch <= 55) { String octalStr = inputSubstring(this.pos - 1, this.pos + 2); Matcher m = Pattern.compile("^[0-7]+").matcher(octalStr); m.find(); octalStr = m.group(); int octal = parseInt(octalStr, 8).intValue(); if (octal > 255) { octalStr = octalStr.substring(0, octalStr.length() - 1); octal = parseInt(octalStr, 8).intValue(); } if (!octalStr.equals("0") && (this.strict || inTemplate)) { this.invalidStringToken(this.pos - 2, "Octal literal in strict mode"); } this.pos += octalStr.length() - 1; return String.valueOf((char) octal); } return String.valueOf((char) ch); } } // Used to read character escape sequences ('\x', '\\u', '\U'). protected int readHexChar(int len) { int codePos = this.pos; Number n = this.readInt(16, len); if (n == null) this.invalidStringToken(codePos, "Bad character escape sequence"); return n.intValue(); } // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\\u' escape. // // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. protected String readWord1() { this.containsEsc = false; String word = ""; boolean first = true; int chunkStart = this.pos; boolean astral = this.options.ecmaVersion() >= 6; while (this.pos < this.input.length()) { int ch = this.fullCharCodeAtPos(); if (Identifiers.isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2; } else if (ch == 92) { // "\" this.containsEsc = true; word += inputSubstring(chunkStart, this.pos); int escStart = this.pos; if (charAt(++this.pos) != 117) // "u" this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); ++this.pos; int esc = this.readCodePoint(); if (!(first ? Identifiers.isIdentifierStart(esc, astral) : Identifiers.isIdentifierChar(esc, astral))) this.invalidStringToken(escStart, "Invalid Unicode escape"); word += codePointToString(esc); chunkStart = this.pos; } else { break; } first = false; } return word + inputSubstring(chunkStart, this.pos); } // Read an identifier or keyword token. Will check for reserved // words when necessary. protected Token readWord() { String word = this.readWord1(); TokenType type = TokenType.name; if ((this.options.ecmaVersion() >= 6 || !this.containsEsc) && this.keywords.contains(word)) type = TokenType.keywords.get(word); return this.finishToken(type, word); } /// end tokenize.js /// begin parseutil.js // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. protected boolean isUseStrict(Statement stmt) { if (!(this.options.ecmaVersion() >= 5 && stmt instanceof ExpressionStatement)) return false; Expression e = ((ExpressionStatement) stmt).getExpression(); if (!(e instanceof Literal)) return false; String raw = ((Literal) e).getRaw(); return raw.length() >= 2 && raw.substring(1, raw.length() - 1).equals("use strict"); } // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. protected boolean eat(TokenType type) { if (this.type == type) { this.next(); return true; } else { return false; } } // Tests whether parsed token is a contextual keyword. protected boolean isContextual(String name) { return this.type == TokenType.name && Objects.equals(this.value, name); } // Consumes contextual keyword if possible. protected boolean eatContextual(String name) { return Objects.equals(this.value, name) && this.eat(TokenType.name); } // Asserts that following token is given contextual keyword. protected void expectContextual(String name) { if (!this.eatContextual(name)) this.unexpected(); } private static final Pattern CONTAINS_LINEBREAK = Pattern.compile("(?s).*(?:" + lineBreak + ").*"); // Test whether a semicolon can be inserted at the current position. protected boolean canInsertSemicolon() { return this.type == TokenType.eof || this.type == TokenType.braceR || CONTAINS_LINEBREAK.matcher(inputSubstring(this.lastTokEnd, this.start)).matches(); } protected boolean insertSemicolon() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon() != null) this.options.onInsertedSemicolon().apply(this.lastTokEnd, this.lastTokEndLoc); return true; } return false; } // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. protected void semicolon() { if (!this.eat(TokenType.semi) && !this.insertSemicolon()) this.unexpected(); } protected boolean afterTrailingComma(TokenType tokType, boolean notNext) { if (this.type == tokType) { if (this.options.onTrailingComma() != null) this.options.onTrailingComma().apply(this.lastTokStart, this.lastTokStartLoc); if (!notNext) this.next(); return true; } return false; } // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. protected void expect(TokenType type) { if (!this.eat(type)) this.unexpected(); } // Raise an unexpected token error. protected void unexpected(Integer pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); } protected void unexpected(Position pos) { this.raise(pos, "Unexpected token"); } protected void unexpected() { unexpected((Integer) null); } public static class DestructuringErrors { private int shorthandAssign, trailingComma; public void reset() { this.shorthandAssign = 0; this.trailingComma = 0; } } protected boolean checkPatternErrors( DestructuringErrors refDestructuringErrors, boolean andThrow) { int trailing = refDestructuringErrors != null ? refDestructuringErrors.trailingComma : 0; if (!andThrow) return trailing != 0; if (trailing != 0) this.raise(trailing, "Comma is not permitted after the rest element"); return false; } protected boolean checkExpressionErrors( DestructuringErrors refDestructuringErrors, boolean andThrow) { int pos = refDestructuringErrors != null ? refDestructuringErrors.shorthandAssign : 0; if (!andThrow) return pos != 0; if (pos != 0) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); return false; } private void checkYieldAwaitInDefaultParams() { if (this.yieldPos > 0 && (this.awaitPos == 0 || this.yieldPos < this.awaitPos)) this.raise(this.yieldPos, "Yield expression cannot be a default value"); if (this.awaitPos > 0) this.raise(this.awaitPos, "Await expression cannot be a default value"); } /// end parseutil.js /// begin node.js protected <T extends INode> T finishNode(T node) { return finishNodeAt(node, this.lastTokEndLoc); } protected <T extends INode> T finishNodeAt(T node, Position pos) { SourceLocation loc = node.getLoc(); loc.setSource(inputSubstring(loc.getStart().getOffset(), pos.getOffset())); loc.setEnd(pos); return node; } /// begin expression.js protected static class PropInfo { boolean init, get, set; boolean is(Property.Kind kind) { switch (kind) { case INIT: return init; case GET: return get; case SET: return set; default: throw new CatastrophicError("Unexpected kind " + kind + "."); } } void set(Property.Kind kind) { switch (kind) { case INIT: init = true; break; case GET: get = true; break; case SET: set = true; break; default: throw new CatastrophicError("Unexpected kind " + kind + "."); } } } // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash --- // either with each other or with an init property --- and in // strict mode, init properties are also not allowed to be repeated. private void checkPropClash(Property prop, Map<String, PropInfo> propHash) { if (this.options.ecmaVersion() >= 6 && (prop.isComputed() || prop.isMethod() || prop.isShorthand())) return; Expression key = prop.getKey(); String name; if (key instanceof Identifier) name = ((Identifier) key).getName(); else if (key instanceof Literal) name = ((Literal) key).getStringValue(); else return; Property.Kind kind = prop.getKind(); if (this.options.ecmaVersion() >= 6) { if ("__proto__".equals(name) && kind == Property.Kind.INIT) { if (propHash.containsKey(name)) this.raiseRecoverable(key, "Redefinition of __proto__ property"); PropInfo pi = new PropInfo(); pi.set(Property.Kind.INIT); propHash.put(name, pi); } return; } PropInfo other = propHash.get(name); if (other != null) { boolean isGetSet = kind.isAccessor; if ((this.strict || isGetSet) && other.is(kind) || !(isGetSet ^ other.init)) this.raiseRecoverable(key, "Redefinition of property"); } else { propHash.put(name, other = new PropInfo()); } other.set(kind); } // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). protected Expression parseExpression(boolean noIn, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; Expression expr = this.parseMaybeAssign(noIn, refDestructuringErrors, null); if (this.type == TokenType.comma) { List<Expression> expressions = CollectionUtil.makeList(expr); SequenceExpression node = new SequenceExpression(new SourceLocation(startLoc), expressions); while (this.eat(TokenType.comma)) expressions.add(this.parseMaybeAssign(noIn, refDestructuringErrors, null)); return this.finishNode(node); } return expr; } public interface AfterLeftParse { Expression call(Expression left, int startPos, Position startLoc); } // Parse an assignment expression. This includes applications of // operators like `+=`. protected Expression parseMaybeAssign( boolean noIn, DestructuringErrors refDestructuringErrors, AfterLeftParse afterLeftParse) { if (this.inGenerator && this.isContextual("yield")) return this.parseYield(); boolean ownDestructuringErrors = false; if (refDestructuringErrors == null) { refDestructuringErrors = new DestructuringErrors(); ownDestructuringErrors = true; } int startPos = this.start; Position startLoc = this.startLoc; if (this.type == TokenType.parenL || this.type == TokenType.name) this.potentialArrowAt = this.start; Expression left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse != null) left = afterLeftParse.call(left, startPos, startLoc); if (this.type.isAssign) { this.checkPatternErrors(refDestructuringErrors, true); if (!ownDestructuringErrors) refDestructuringErrors.reset(); Expression l = this.type == TokenType.eq ? (Expression) this.toAssignable(left, false) : left; refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly String operator = String.valueOf(this.value); this.checkLVal(l, false, null); this.next(); Expression r = this.parseMaybeAssign(noIn, null, null); AssignmentExpression node = new AssignmentExpression(new SourceLocation(startLoc), operator, l, r); return this.finishNode(node); } else { if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true); } return left; } // Parse a ternary conditional (`?:`) operator. protected Expression parseMaybeConditional( boolean noIn, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; Expression expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; if (this.eat(TokenType.question)) { return parseConditionalRest(noIn, startLoc, expr); } return expr; } protected Expression parseConditionalRest(boolean noIn, Position start, Expression test) { Expression consequent = this.parseMaybeAssign(false, null, null); this.expect(TokenType.colon); Expression alternate = this.parseMaybeAssign(noIn, null, null); ConditionalExpression node = new ConditionalExpression(new SourceLocation(start), test, consequent, alternate); return this.finishNode(node); } // Start the precedence parser. protected Expression parseExprOps(boolean noIn, DestructuringErrors refDestructuringErrors) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr = this.parseMaybeUnary(refDestructuringErrors, false); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; return this.parseExprOp(expr, startPos, startLoc, -1, noIn); } // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. protected Expression parseExprOp( Expression left, int leftStartPos, Position leftStartLoc, int minPrec, boolean noIn) { int prec = this.type.binop; if (prec != 0 && (!noIn || this.type != TokenType._in)) { if (prec > minPrec) { boolean logical = this.type == TokenType.logicalOR || this.type == TokenType.logicalAND; String op = String.valueOf(this.value); this.next(); int startPos = this.start; Position startLoc = this.startLoc; Expression right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); Expression node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); } } return left; } private Expression buildBinary( int startPos, Position startLoc, Expression left, Expression right, String op, boolean logical) { SourceLocation loc = new SourceLocation(startLoc); Expression node = logical ? new LogicalExpression(loc, op, left, right) : new BinaryExpression(loc, op, left, right); return this.finishNode(node); } // Parse unary operators, both prefix and postfix. protected Expression parseMaybeUnary( DestructuringErrors refDestructuringErrors, boolean sawUnary) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr; if ((this.inAsync || options.esnext() && !this.inFunction) && this.isContextual("await")) { expr = this.parseAwait(); sawUnary = true; } else if (this.type.isPrefix) { String operator = String.valueOf(this.value); boolean update = this.type == TokenType.incDec; this.next(); Expression argument = this.parseMaybeUnary(null, true); SourceLocation loc = new SourceLocation(startLoc); Expression node = update ? new UpdateExpression(loc, operator, argument, true) : new UnaryExpression(loc, operator, argument, true); this.checkExpressionErrors(refDestructuringErrors, true); if (update) this.checkLVal(argument, false, null); else if (this.strict && operator.equals("delete") && argument instanceof Identifier) this.raiseRecoverable(node, "Deleting local variable in strict mode"); else sawUnary = true; expr = this.finishNode(node); } else { expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; while (this.type.isPostfix && !this.canInsertSemicolon()) { UpdateExpression node = new UpdateExpression( new SourceLocation(startLoc), String.valueOf(this.value), expr, false); this.checkLVal(expr, false, null); this.next(); expr = this.finishNode(node); } } if (!sawUnary && this.eat(TokenType.starstar)) return this.buildBinary( startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false); else return expr; } // Parse call, dot, and `[]`-subscript expressions. protected Expression parseExprSubscripts(DestructuringErrors refDestructuringErrors) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr = this.parseExprAtom(refDestructuringErrors); boolean skipArrowSubscripts = expr instanceof ArrowFunctionExpression && !inputSubstring(this.lastTokStart, this.lastTokEnd).equals(")"); if (this.checkExpressionErrors(refDestructuringErrors, false) || skipArrowSubscripts) return expr; return this.parseSubscripts(expr, startPos, startLoc, false); } protected Expression parseSubscripts( Expression base, int startPos, Position startLoc, boolean noCalls) { for (; ; ) { Pair<Expression, Boolean> p = parseSubscript(base, startLoc, noCalls); if (p.snd()) base = p.fst(); else return p.fst(); } } /** * Parse a single subscript {@code s}; if more subscripts could follow, return {@code Pair.make(s, * true}, otherwise return {@code Pair.make(s, false)}. */ protected Pair<Expression, Boolean> parseSubscript( final Expression base, Position startLoc, boolean noCalls) { boolean maybeAsyncArrow = this.options.ecmaVersion() >= 8 && base instanceof Identifier && "async".equals(((Identifier) base).getName()) && !this.canInsertSemicolon(); boolean optional = this.eat(TokenType.questiondot); if (this.eat(TokenType.bracketL)) { MemberExpression node = new MemberExpression( new SourceLocation(startLoc), base, this.parseExpression(false, null), true, optional, Chainable.isOnOptionalChain(optional, base)); this.expect(TokenType.bracketR); return Pair.make(this.finishNode(node), true); } else if (!noCalls && this.eat(TokenType.parenL)) { DestructuringErrors refDestructuringErrors = new DestructuringErrors(); int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.yieldPos = 0; this.awaitPos = 0; List<Expression> exprList = this.parseExprList( TokenType.parenR, this.options.ecmaVersion() >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && shouldParseAsyncArrow()) { this.checkPatternErrors(refDestructuringErrors, true); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return Pair.make(this.parseArrowExpression(startLoc, exprList, true), false); } this.checkExpressionErrors(refDestructuringErrors, true); if (oldYieldPos > 0) this.yieldPos = oldYieldPos; if (oldAwaitPos > 0) this.awaitPos = oldAwaitPos; CallExpression node = new CallExpression( new SourceLocation(startLoc), base, new ArrayList<>(), exprList, optional, Chainable.isOnOptionalChain(optional, base)); return Pair.make(this.finishNode(node), true); } else if (this.type == TokenType.backQuote) { if (Chainable.isOnOptionalChain(optional, base)) { this.raise(base, "An optional chain may not be used in a tagged template expression."); } TaggedTemplateExpression node = new TaggedTemplateExpression( new SourceLocation(startLoc), base, this.parseTemplate(true)); return Pair.make(this.finishNode(node), true); } else if (optional || this.eat(TokenType.dot)) { MemberExpression node = new MemberExpression( new SourceLocation(startLoc), base, this.parseIdent(true), false, optional, Chainable.isOnOptionalChain(optional, base)); return Pair.make(this.finishNode(node), true); } else { return Pair.make(base, false); } } protected boolean shouldParseAsyncArrow() { return !this.canInsertSemicolon() && this.eat(TokenType.arrow); } // Parse an atomic expression --- either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { Expression node; boolean canBeArrow = this.potentialArrowAt == this.start; if (this.type == TokenType._super) { if (!this.inFunction) this.raise(this.start, "'super' outside of function or class"); node = new Super(new SourceLocation(this.startLoc)); this.next(); return this.finishNode(node); } else if (this.type == TokenType._this) { node = new ThisExpression(new SourceLocation(this.startLoc)); this.next(); return this.finishNode(node); } else if (this.type == TokenType.name) { Position startLoc = this.startLoc; Identifier id = this.parseIdent(this.type != TokenType.name); if (this.options.ecmaVersion() >= 8 && "async".equals(id.getName()) && !this.canInsertSemicolon() && this.eat(TokenType._function)) return (Expression) this.parseFunction(startLoc, false, false, true); if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(TokenType.arrow)) return this.parseArrowExpression(startLoc, CollectionUtil.makeList(id), false); if (this.options.ecmaVersion() >= 8 && id.getName().equals("async") && this.type == TokenType.name) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(TokenType.arrow)) this.unexpected(); return this.parseArrowExpression(startLoc, CollectionUtil.makeList(id), true); } } return id; } else if (this.type == TokenType.regexp || this.type == TokenType.num || this.type == TokenType.string || this.type == TokenType.bigint) { return this.parseLiteral(this.type, this.value); } else if (this.type == TokenType._null || this.type == TokenType._true || this.type == TokenType._false) { Object val = this.type == TokenType._null ? null : this.type == TokenType._true; node = new Literal(new SourceLocation(this.type.keyword, startLoc), this.type, val); this.next(); return this.finishNode(node); } else if (this.type == TokenType.parenL) { return this.parseParenAndDistinguishExpression(canBeArrow); } else if (this.type == TokenType.bracketL) { Position startLoc = this.startLoc; this.next(); List<Expression> elements = this.parseExprList(TokenType.bracketR, true, true, refDestructuringErrors); node = new ArrayExpression(new SourceLocation(startLoc), elements); return this.finishNode(node); } else if (this.type == TokenType.braceL) { return this.parseObj(false, refDestructuringErrors); } else if (this.type == TokenType._function) { Position startLoc = this.startLoc; this.next(); return (Expression) this.parseFunction(startLoc, false, false, false); } else if (this.type == TokenType._class) { return (Expression) this.parseClass(this.startLoc, false); } else if (this.type == TokenType._new) { return this.parseNew(); } else if (this.type == TokenType.backQuote) { return this.parseTemplate(false); } else { this.unexpected(); return null; } } protected Literal parseLiteral(TokenType tokenType, Object value) { SourceLocation loc = new SourceLocation(inputSubstring(this.start, this.end), this.startLoc); Literal node = new Literal(loc, tokenType, value); this.next(); return this.finishNode(node); } protected Expression parseParenExpression() { this.expect(TokenType.parenL); Expression val = this.parseExpression(false, null); this.expect(TokenType.parenR); return val; } protected Expression parseParenAndDistinguishExpression(boolean canBeArrow) { Position startLoc = this.startLoc; Expression val; if (this.options.ecmaVersion() >= 6) { this.next(); DestructuringErrors refDestructuringErrors = new DestructuringErrors(); int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; ParenthesisedExpressions parenExprs = parseParenthesisedExpressions(refDestructuringErrors); if (canBeArrow && !this.canInsertSemicolon() && this.eat(TokenType.arrow)) { this.checkPatternErrors(refDestructuringErrors, true); this.checkYieldAwaitInDefaultParams(); if (parenExprs.innerParenStart != 0) this.unexpected(parenExprs.innerParenStart); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startLoc, parenExprs.exprList); } if (parenExprs.exprList.isEmpty() || parenExprs.lastIsComma) this.unexpected(this.lastTokStart); if (parenExprs.spreadStart != 0) this.unexpected(parenExprs.spreadStart); this.checkExpressionErrors(refDestructuringErrors, true); if (oldYieldPos > 0) this.yieldPos = oldYieldPos; if (oldAwaitPos > 0) this.awaitPos = oldAwaitPos; if (parenExprs.exprList.size() > 1) { val = new SequenceExpression(new SourceLocation(parenExprs.startLoc), parenExprs.exprList); this.finishNodeAt(val, parenExprs.endLoc); } else { val = parenExprs.exprList.get(0); } } else { val = this.parseParenExpression(); } if (this.options.preserveParens()) { ParenthesizedExpression par = new ParenthesizedExpression(new SourceLocation(startLoc), val); return this.finishNode(par); } else { return val; } } /** Information about a list of expressions between parentheses. */ protected static class ParenthesisedExpressions { /** If non-zero, indicates the location of a spread expression in the list. */ int spreadStart = 0; /** If non-zero, indicates the location of a parenthesised expression in the list. */ int innerParenStart = 0; /** * The start position (i.e., right after the opening parenthesis) and end location (i.e., before * the closing parenthesis) of the list. */ Position startLoc, endLoc; /** The list itself. */ List<Expression> exprList = new ArrayList<Expression>(); boolean lastIsComma; } protected ParenthesisedExpressions parseParenthesisedExpressions( DestructuringErrors refDestructuringErrors) { boolean allowTrailingComma = this.options.ecmaVersion() >= 8; ParenthesisedExpressions parenExprs = new ParenthesisedExpressions(); parenExprs.startLoc = this.startLoc; boolean first = true; this.yieldPos = 0; this.awaitPos = 0; while (this.type != TokenType.parenR) { if (first) first = false; else this.expect(TokenType.comma); if (!parseParenthesisedExpression( refDestructuringErrors, allowTrailingComma, parenExprs, first)) break; } parenExprs.endLoc = this.startLoc; this.expect(TokenType.parenR); return parenExprs; } /** * Parse an expression that forms part of a comma-separated list of expressions between * parentheses, adding it to `parenExprs`. * * @return true if more expressions may follow this one, false if it must be the last one */ protected boolean parseParenthesisedExpression( DestructuringErrors refDestructuringErrors, boolean allowTrailingComma, ParenthesisedExpressions parenExprs, boolean first) { if (allowTrailingComma && this.afterTrailingComma(TokenType.parenR, true)) { parenExprs.lastIsComma = true; return false; } else if (this.type == TokenType.ellipsis) { parenExprs.spreadStart = this.start; parenExprs.exprList.add(this.parseParenItem(this.parseRest(false), -1, null)); if (this.type == TokenType.comma) this.raise(this.startLoc, "Comma is not permitted after the rest element"); return false; } else { if (this.type == TokenType.parenL && parenExprs.innerParenStart == 0) { parenExprs.innerParenStart = this.start; } parenExprs.exprList.add( this.parseMaybeAssign(false, refDestructuringErrors, this::parseParenItem)); } return true; } protected Expression parseParenItem(Expression left, int startPos, Position startLoc) { return left; } protected Expression parseParenArrowList(Position startLoc, List<Expression> exprList) { return this.parseArrowExpression(startLoc, exprList, false); } // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call --- at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. protected Expression parseNew() { Position startLoc = this.startLoc; Identifier meta = this.parseIdent(true); if (this.options.ecmaVersion() >= 6 && this.eat(TokenType.dot)) { Identifier property = this.parseIdent(true); if (!property.getName().equals("target")) this.raiseRecoverable(property, "The only valid meta property for new is new.target"); if (!this.inFunction) this.raiseRecoverable(meta, "new.target can only be used in functions"); MetaProperty node = new MetaProperty(new SourceLocation(startLoc), meta, property); return this.finishNode(node); } int innerStartPos = this.start; Position innerStartLoc = this.startLoc; Expression callee = this.parseSubscripts(this.parseExprAtom(null), innerStartPos, innerStartLoc, true); if (Chainable.isOnOptionalChain(false, callee)) this.raise(callee, "An optional chain may not be used in a `new` expression."); return parseNewArguments(startLoc, callee); } protected Expression parseNewArguments(Position startLoc, Expression callee) { List<Expression> arguments; if (this.eat(TokenType.parenL)) arguments = this.parseExprList(TokenType.parenR, this.options.ecmaVersion() >= 8, false, null); else arguments = new ArrayList<Expression>(); NewExpression node = new NewExpression(new SourceLocation(startLoc), callee, new ArrayList<>(), arguments); return this.finishNode(node); } // Parse template expression. protected TemplateElement parseTemplateElement(boolean isTagged) { Position startLoc = this.startLoc; String raw, cooked; if (this.type == TokenType.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } raw = String.valueOf(this.value); cooked = null; } else { raw = inputSubstring(this.start, this.end).replaceAll("\r\n?", "\n"); cooked = String.valueOf(this.value); } this.next(); boolean tail = this.type == TokenType.backQuote; TemplateElement elem = new TemplateElement(new SourceLocation(startLoc), cooked, raw, tail); return this.finishNode(elem); } protected TemplateLiteral parseTemplate(boolean isTagged) { Position startLoc = this.startLoc; this.next(); List<Expression> expressions = new ArrayList<Expression>(); TemplateElement curElt = this.parseTemplateElement(isTagged); List<TemplateElement> quasis = CollectionUtil.makeList(curElt); while (!curElt.isTail()) { this.expect(TokenType.dollarBraceL); expressions.add(this.parseExpression(false, null)); this.expect(TokenType.braceR); quasis.add(curElt = this.parseTemplateElement(isTagged)); } this.next(); TemplateLiteral node = new TemplateLiteral(new SourceLocation(startLoc), expressions, quasis); return this.finishNode(node); } /* * Auxiliary class used to collect information about properties during parsing. * * This is needed because parsing properties and methods requires a fair bit of lookahead. */ protected static class PropertyInfo { Expression key, value; String kind = "init"; boolean computed = false, method = false, isPattern, isGenerator, isAsync; Position startLoc; public PropertyInfo(boolean isPattern, boolean isGenerator, Position startLoc) { this.isPattern = isPattern; this.isGenerator = isGenerator; this.startLoc = startLoc; } MethodDefinition.Kind getMethodKind() { return MethodDefinition.Kind.valueOf(StringUtil.uc(kind)); } } // Parse an object literal or binding pattern. protected Expression parseObj(boolean isPattern, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; boolean first = true; Map<String, PropInfo> propHash = new LinkedHashMap<>(); List<Property> properties = new ArrayList<Property>(); this.next(); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } properties.add(this.finishNode(parseProperty(isPattern, refDestructuringErrors, propHash))); } SourceLocation loc = new SourceLocation(startLoc); Expression node = isPattern ? new ObjectPattern(loc, properties) : new ObjectExpression(loc, properties); return this.finishNode(node); } protected Property parseProperty( boolean isPattern, DestructuringErrors refDestructuringErrors, Map<String, PropInfo> propHash) { Position propStartLoc = this.startLoc; boolean isGenerator = false; if (this.options.ecmaVersion() >= 6) { if (!isPattern) isGenerator = this.eat(TokenType.star); } PropertyInfo pi = new PropertyInfo(isPattern, isGenerator, propStartLoc); this.parsePropertyName(pi); if (!isPattern && this.options.ecmaVersion() >= 8 && !isGenerator && this.isAsyncProp(pi)) { pi.isAsync = true; pi.isGenerator = this.eat(TokenType.star); this.parsePropertyName(pi); } else { pi.isAsync = false; } this.parsePropertyValue(pi, refDestructuringErrors); Property prop = new Property( new SourceLocation(pi.startLoc), pi.key, pi.value, pi.kind, pi.computed, pi.method); this.checkPropClash(prop, propHash); return prop; } private boolean isAsyncProp(PropertyInfo pi) { return !pi.computed && pi.key instanceof Identifier && ((Identifier) pi.key).getName().equals("async") && (this.type == TokenType.name || this.type == TokenType.num || this.type == TokenType.string || this.type == TokenType.bracketL || this.type == TokenType.star || this.type.keyword != null) && !this.canInsertSemicolon(); } protected void parsePropertyValue(PropertyInfo pi, DestructuringErrors refDestructuringErrors) { if ((pi.isGenerator || pi.isAsync) && this.type == TokenType.colon) this.unexpected(); if (this.eat(TokenType.colon)) { pi.value = pi.isPattern ? this.parseMaybeDefault(this.startLoc, null) : this.parseMaybeAssign(false, refDestructuringErrors, null); pi.kind = "init"; } else if (this.options.ecmaVersion() >= 6 && this.type == TokenType.parenL) { if (pi.isPattern) this.unexpected(); pi.kind = "init"; pi.method = true; pi.value = this.parseMethod(pi.isGenerator, pi.isAsync); } else if (this.options.ecmaVersion() >= 5 && !pi.computed && pi.key instanceof Identifier && (((Identifier) pi.key).getName().equals("get") || ((Identifier) pi.key).getName().equals("set")) && (this.type != TokenType.comma && this.type != TokenType.braceR)) { if (pi.isGenerator || pi.isAsync || pi.isPattern) this.unexpected(); pi.kind = ((Identifier) pi.key).getName(); PropertyInfo pi2 = new PropertyInfo(false, false, this.startLoc); this.parsePropertyName(pi2); pi.key = pi2.key; pi.computed = pi2.computed; pi.value = this.parseMethod(false, false); int paramCount = pi.kind.equals("get") ? 0 : 1; FunctionExpression fn = (FunctionExpression) pi.value; List<Expression> params = fn.getRawParameters(); if (params.size() != paramCount) { if (pi.kind.equals("get")) this.raiseRecoverable(pi.value, "getter should have no params"); else this.raiseRecoverable(pi.value, "setter should have exactly one param"); } if (pi.kind.equals("set") && fn.hasRest()) this.raiseRecoverable(params.get(params.size() - 1), "Setter cannot use rest params"); } else if (this.options.ecmaVersion() >= 6 && !pi.computed && pi.key instanceof Identifier) { String name = ((Identifier) pi.key).getName(); if (this.keywords.contains(name) || (this.strict ? this.reservedWordsStrict : this.reservedWords).contains(name) || (this.inGenerator && name.equals("yield")) || (this.inAsync && name.equals("await"))) this.raiseRecoverable(pi.key, "'" + name + "' can not be used as shorthand property"); pi.kind = "init"; if (pi.isPattern) { pi.value = this.parseMaybeDefault(pi.startLoc, pi.key); } else if (this.type == TokenType.eq && refDestructuringErrors != null) { if (refDestructuringErrors.shorthandAssign == 0) refDestructuringErrors.shorthandAssign = this.start; pi.value = this.parseMaybeDefault(pi.startLoc, pi.key); } else { pi.value = pi.key; } } else { this.unexpected(); } } protected void parsePropertyName(PropertyInfo result) { if (this.options.ecmaVersion() >= 6) { if (this.eat(TokenType.bracketL)) { result.key = this.parseMaybeAssign(false, null, null); result.computed = true; this.expect(TokenType.bracketR); return; } } if (this.type == TokenType.num || this.type == TokenType.string) result.key = this.parseExprAtom(null); else result.key = this.parseIdent(true); } // Parse object or class method. protected FunctionExpression parseMethod(boolean isGenerator, boolean isAsync) { Position startLoc = this.startLoc; boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.inGenerator = isGenerator; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; this.expect(TokenType.parenL); List<Expression> params = this.parseBindingList(TokenType.parenR, false, this.options.ecmaVersion() >= 8, false); this.checkYieldAwaitInDefaultParams(); boolean generator = this.options.ecmaVersion() >= 6 && isGenerator; Node body = this.parseFunctionBody(null, params, false); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; Identifier id = null; FunctionExpression node = new FunctionExpression(new SourceLocation(startLoc), id, params, body, generator, isAsync); return this.finishNode(node); } // Parse arrow function expression with given parameters. protected ArrowFunctionExpression parseArrowExpression( Position startLoc, List<Expression> rawParams, boolean isAsync) { boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.inGenerator = false; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; List<Expression> params = this.toAssignableList(rawParams, true); Node body = this.parseFunctionBody(null, params, true); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; ArrowFunctionExpression node = new ArrowFunctionExpression(new SourceLocation(startLoc), params, body, false, isAsync); return this.finishNode(node); } // Parse function body and check parameters. protected Node parseFunctionBody( Identifier id, List<Expression> params, boolean isArrowFunction) { boolean isExpression = isArrowFunction && this.type != TokenType.braceL; Node body; if (isExpression) { body = this.parseMaybeAssign(false, null, null); } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). boolean oldInFunc = this.inFunction; Stack<LabelInfo> oldLabels = this.labels; this.inFunction = true; this.labels = new Stack<LabelInfo>(); body = this.parseBlock(true); this.inFunction = oldInFunc; this.labels = oldLabels; } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. Statement useStrict = null; if (!isExpression && body instanceof BlockStatement) { List<Statement> bodyStmts = ((BlockStatement) body).getBody(); if (!bodyStmts.isEmpty() && isUseStrict(bodyStmts.get(0))) useStrict = bodyStmts.get(0); } if (useStrict != null && options.ecmaVersion() >= 7 && !isSimpleParamList(params)) raiseRecoverable( useStrict, "Illegal 'use strict' directive in function with non-simple parameter list"); if (this.strict || useStrict != null) { boolean oldStrict = this.strict; this.strict = true; if (id != null) this.checkLVal(id, true, null); this.checkParams(params); this.strict = oldStrict; } else if (isArrowFunction || !isSimpleParamList(params)) { this.checkParams(params); } return body; } private boolean isSimpleParamList(List<Expression> params) { for (Expression param : params) if (!(param instanceof Identifier)) return false; return true; } // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. protected void checkParams(List<? extends INode> params) { Set<String> nameHash = new LinkedHashSet<>(); for (INode param : params) this.checkLVal(param, true, nameHash); } // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). protected List<Expression> parseExprList( TokenType close, boolean allowTrailingComma, boolean allowEmpty, DestructuringErrors refDestructuringErrors) { List<Expression> elts = new ArrayList<Expression>(); boolean first = true; while (!this.eat(close)) { if (!first) { this.expect(TokenType.comma); if (allowTrailingComma && this.afterTrailingComma(close, false)) break; } else { first = false; } Expression elt; if (allowEmpty && this.type == TokenType.comma) { elt = null; } else if (this.type == TokenType.ellipsis) { elt = this.processExprListItem(this.parseSpread(refDestructuringErrors)); if (this.type == TokenType.comma && refDestructuringErrors != null && refDestructuringErrors.trailingComma == 0) { refDestructuringErrors.trailingComma = this.start; } } else elt = this.processExprListItem(this.parseMaybeAssign(false, refDestructuringErrors, null)); elts.add(elt); } return elts; } protected Expression processExprListItem(Expression e) { return e; } // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. protected Identifier parseIdent(boolean liberal) { Position startLoc = this.startLoc; boolean isPrivateField = liberal && this.eat(TokenType.pound); if (liberal && this.options.allowReserved() == AllowReserved.NEVER) liberal = false; String name = null; if (this.type == TokenType.name) { if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).contains(this.value) && (this.options.ecmaVersion() >= 6 || inputSubstring(this.start, this.end).indexOf("\\") == -1)) this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved"); if (!isPrivateField && this.inGenerator && this.value.equals("yield")) this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator"); if (!isPrivateField && this.inAsync && this.value.equals("await")) this.raiseRecoverable( this.start, "Can not use 'await' as identifier inside an async function"); name = String.valueOf(this.value); } else if (this.type.keyword != null) { name = this.type.keyword; if (!liberal) raiseRecoverable(this.start, "Cannot use keyword '" + name + "' as an identifier."); } else { this.unexpected(); } this.next(); if (isPrivateField) { if (!this.inClass) { this.raiseRecoverable(this.start, "Cannot use private fields outside a class"); } name = "#" + name; } Identifier node = new Identifier(new SourceLocation(startLoc), name); return this.finishNode(node); } // Parses yield expression inside generator. protected YieldExpression parseYield() { if (this.awaitPos == 0) this.awaitPos = this.start; Position startLoc = this.startLoc; this.next(); boolean delegate; Expression argument; if (this.type == TokenType.semi || this.canInsertSemicolon() || (this.type != TokenType.star && !this.type.startsExpr)) { delegate = false; argument = null; } else { delegate = this.eat(TokenType.star); argument = this.parseMaybeAssign(false, null, null); } YieldExpression node = new YieldExpression(new SourceLocation(startLoc), argument, delegate); return this.finishNode(node); } protected AwaitExpression parseAwait() { Position startLoc = this.startLoc; this.next(); Expression argument = this.parseMaybeUnary(null, true); AwaitExpression node = new AwaitExpression(new SourceLocation(startLoc), argument); return this.finishNode(node); } /// end expression.js /// begin lval.js // Convert existing expression atom to assignable pattern // if possible. protected INode toAssignable(INode node, boolean isBinding) { if (this.options.ecmaVersion() >= 6 && node != null) { if (node instanceof Identifier) { if (this.inAsync && ((Identifier) node).getName().equals("await")) this.raise(node, "Can not use 'await' as identifier inside an async function"); return node; } if (node instanceof ObjectPattern || node instanceof ArrayPattern) { return node; } if (node instanceof ObjectExpression) { List<Property> properties = new ArrayList<Property>(); for (Property prop : ((ObjectExpression) node).getProperties()) { if (prop.getKind().isAccessor) this.raise(prop.getKey(), "Object pattern can't contain getter or setter"); Expression val = (Expression) this.toAssignable(prop.getRawValue(), isBinding); properties.add( new Property( prop.getLoc(), prop.getKey(), val, prop.getKind().name(), prop.isComputed(), prop.isMethod())); } return new ObjectPattern(node.getLoc(), properties); } if (node instanceof ArrayExpression) return new ArrayPattern( node.getLoc(), this.toAssignableList(((ArrayExpression) node).getElements(), isBinding)); if (node instanceof AssignmentExpression) { AssignmentExpression assgn = (AssignmentExpression) node; if (assgn.getOperator().equals("=")) { this.toAssignable(assgn.getLeft(), isBinding); return new AssignmentPattern(node.getLoc(), "=", assgn.getLeft(), assgn.getRight()); } else { this.raise( assgn.getLeft().getLoc().getEnd(), "Only '=' operator can be used for specifying default value."); } } if (node instanceof AssignmentPattern) { return node; } if (node instanceof ParenthesizedExpression) { Expression expr = ((ParenthesizedExpression) node).getExpression(); return new ParenthesizedExpression( node.getLoc(), (Expression) this.toAssignable(expr, isBinding)); } if (node instanceof MemberExpression) { if (Chainable.isOnOptionalChain(false, (MemberExpression) node)) this.raise(node, "Invalid left-hand side in assignment"); if (!isBinding) return node; } this.raise(node, "Assigning to rvalue"); } return node; } // Convert list of expression atoms to binding list. protected List<Expression> toAssignableList(List<Expression> exprList, boolean isBinding) { int end = exprList.size(); if (end > 0) { Expression last = exprList.get(end - 1); if (last != null && last instanceof RestElement) { --end; } else if (last != null && last instanceof SpreadElement) { Expression arg = ((SpreadElement) last).getArgument(); arg = (Expression) this.toAssignable(arg, isBinding); if (!(arg instanceof Identifier || arg instanceof MemberExpression || arg instanceof ArrayPattern)) this.unexpected(arg.getLoc().getStart()); exprList.set(end - 1, last = new RestElement(last.getLoc(), arg)); --end; } if (isBinding && last instanceof RestElement && !(((RestElement) last).getArgument() instanceof Identifier)) this.unexpected(((RestElement) last).getArgument().getLoc().getStart()); } for (int i = 0; i < end; ++i) exprList.set(i, (Expression) this.toAssignable(exprList.get(i), isBinding)); return exprList; } // Parses spread element. protected SpreadElement parseSpread(DestructuringErrors refDestructuringErrors) { Position start = this.startLoc; this.next(); SpreadElement node = new SpreadElement( new SourceLocation(start), this.parseMaybeAssign(false, refDestructuringErrors, null)); return this.finishNode(node); } protected RestElement parseRest(boolean allowNonIdent) { Position start = this.startLoc; this.next(); // RestElement inside of a function parameter must be an identifier Expression argument = null; if (allowNonIdent) if (this.type == TokenType.name) argument = this.parseIdent(false); else this.unexpected(); else if (this.type == TokenType.name || this.type == TokenType.bracketL) argument = this.parseBindingAtom(); else this.unexpected(); RestElement node = new RestElement(new SourceLocation(start), argument); return this.finishNode(node); } // Parses lvalue (assignable) atom. protected Expression parseBindingAtom() { if (this.options.ecmaVersion() < 6) return this.parseIdent(false); if (this.type == TokenType.bracketL) { Position start = this.startLoc; this.next(); List<Expression> elements = this.parseBindingList(TokenType.bracketR, true, true, false); ArrayPattern node = new ArrayPattern(new SourceLocation(start), elements); return this.finishNode(node); } if (this.type == TokenType.braceL) return this.parseObj(true, null); return this.parseIdent(false); } protected List<Expression> parseBindingList( TokenType close, boolean allowEmpty, boolean allowTrailingComma, boolean allowNonIdent) { List<Expression> result = new ArrayList<Expression>(); boolean first = true; while (!this.eat(close)) { if (first) first = false; else this.expect(TokenType.comma); if (allowEmpty && this.type == TokenType.comma) { result.add(null); } else if (allowTrailingComma && this.afterTrailingComma(close, false)) { break; } else if (this.type == TokenType.ellipsis) { result.add(this.processBindingListItem(this.parseRest(allowNonIdent))); if (this.type == TokenType.comma) this.raise(this.start, "Comma is not permitted after the rest element"); this.expect(close); break; } else { result.add(this.processBindingListItem(this.parseMaybeDefault(this.startLoc, null))); } } return result; } protected Expression processBindingListItem(Expression e) { return e; } // Parses assignment pattern around given atom if possible. protected Expression parseMaybeDefault(Position startLoc, Expression left) { if (left == null) left = this.parseBindingAtom(); if (this.options.ecmaVersion() < 6 || !this.eat(TokenType.eq)) return left; AssignmentPattern node = new AssignmentPattern( new SourceLocation(startLoc), "=", left, this.parseMaybeAssign(false, null, null)); return this.finishNode(node); } // Verify that a node is an lval --- something that can be assigned // to. protected void checkLVal(INode expr, boolean isBinding, Set<String> checkClashes) { if (expr instanceof Identifier) { String name = ((Identifier) expr).getName(); if (this.strict && this.reservedWordsStrictBind.contains(name)) this.raiseRecoverable( expr, (isBinding ? "Binding " : "Assigning to ") + name + " in strict mode"); if (checkClashes != null) { if (!checkClashes.add(name)) this.raiseRecoverable(expr, "Argument name clash"); } } else if (expr instanceof MemberExpression) { if (isBinding) this.raiseRecoverable( expr, (isBinding ? "Binding" : "Assigning to") + " member expression"); } else if (expr instanceof ObjectPattern) { for (Property prop : ((ObjectPattern) expr).getProperties()) this.checkLVal(prop.getRawValue(), isBinding, checkClashes); } else if (expr instanceof ArrayPattern) { for (Expression elem : ((ArrayPattern) expr).getRawElements()) if (elem != null) this.checkLVal(elem, isBinding, checkClashes); } else if (expr instanceof AssignmentPattern) { this.checkLVal(((AssignmentPattern) expr).getLeft(), isBinding, checkClashes); } else if (expr instanceof RestElement) { this.checkLVal(((RestElement) expr).getArgument(), isBinding, checkClashes); } else if (expr instanceof ParenthesizedExpression) { this.checkLVal(((ParenthesizedExpression) expr).getExpression(), isBinding, checkClashes); } else { this.raise(expr.getLoc().getStart(), (isBinding ? "Binding" : "Assigning to") + " rvalue"); } } /// end lval.js /// begin tokencontext.js public static class TokContext { public static final TokContext b_stat = new TokContext("{", false), b_expr = new TokContext("{", true), b_tmpl = new TokContext("${", true), p_stat = new TokContext("(", false), p_expr = new TokContext("(", true), q_tmpl = new TokContext("`", true, true, p -> p.tryReadTemplateToken()), f_expr = new TokContext("function", true); public final String token; public final boolean isExpr, preserveSpace; public final Function<Parser, Token> override; public TokContext( String token, boolean isExpr, boolean preserveSpace, Function<Parser, Token> override) { this.token = token; this.isExpr = isExpr; this.preserveSpace = preserveSpace; this.override = override; } public TokContext(String token, boolean isExpr) { this(token, isExpr, false, null); } } private Stack<TokContext> initialContext() { Stack<TokContext> s = new Stack<TokContext>(); s.push(TokContext.b_stat); return s; } protected boolean braceIsBlock(TokenType prevType) { if (prevType == TokenType.colon) { TokContext parent = this.curContext(); if (parent == TokContext.b_stat || parent == TokContext.b_expr) return !parent.isExpr; } if (prevType == TokenType._return) return inputSubstring(this.lastTokEnd, this.start).matches("(?s).*(?:" + lineBreak + ").*"); if (prevType == TokenType._else || prevType == TokenType.semi || prevType == TokenType.eof || prevType == TokenType.parenR) return true; if (prevType == TokenType.braceL) return this.curContext() == TokContext.b_stat; return !this.exprAllowed; } protected void updateContext(TokenType prevType) { TokenType type = this.type; if (type.keyword != null && prevType == TokenType.dot) this.exprAllowed = false; else type.updateContext(this, prevType); } /// end tokencontext.js /// begin statement.js // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. protected Program parseTopLevel(Position startLoc, Program node) { boolean first = true; Set<String> exports = new LinkedHashSet<String>(); List<Statement> body = new ArrayList<Statement>(); while (this.type != TokenType.eof) { Statement stmt = this.parseStatement(true, true, exports); if (stmt != null) body.add(stmt); if (first) { if (this.isUseStrict(stmt)) this.setStrict(true); first = false; } } this.next(); if (node == null) { String sourceType = this.options.ecmaVersion() >= 6 ? this.options.sourceType() : null; node = new Program(new SourceLocation(startLoc), body, sourceType); } else { node.getBody().addAll(body); } return this.finishNode(node); } private final LabelInfo loopLabel = new LabelInfo(null, "loop", -1); private final LabelInfo switchLabel = new LabelInfo(null, "switch", -1); protected boolean isLet() { if (this.type != TokenType.name || this.options.ecmaVersion() < 6 || !this.value.equals("let")) return false; Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); m.find(this.pos); int next = m.end(), nextCh = charAt(next); if (mayFollowLet(nextCh)) return true; // '{' and '[' if (Identifiers.isIdentifierStart(nextCh, true)) { int endPos; for (endPos = next + 1; Identifiers.isIdentifierChar(charAt(endPos), true); ++endPos) ; String ident = inputSubstring(next, endPos); if (!this.keywords.contains(ident)) return true; } return false; } protected boolean mayFollowLet(int c) { return c == 91 || c == 123; } protected final Statement parseStatement(boolean declaration, boolean topLevel) { return parseStatement(declaration, topLevel, null); } // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. boolean isAsyncFunction() { if (this.type != TokenType.name || this.options.ecmaVersion() < 8 || !this.value.equals("async")) return false; Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); m.find(this.pos); int next = m.end(); return !Whitespace.lineBreakG.matcher(inputSubstring(this.pos, next)).matches() && inputSubstring(next, next + 8).equals("function") && (next + 8 == this.input.length() || !Identifiers.isIdentifierChar(this.input.codePointAt(next + 8), false)); } /** * Parse a single statement. * * <p>If expecting a statement and finding a slash operator, parse a regular expression literal. * This is to handle cases like <code>if (foo) /blah/.exec(foo)</code>, where looking at the * previous token does not help. * * <p>If {@code declaration} is true, this method may return {@code null}, indicating the parsed * statement was a declaration that has no semantic meaning (such as a Flow interface * declaration). This is never the case in standard ECMAScript. */ protected Statement parseStatement(boolean declaration, boolean topLevel, Set<String> exports) { TokenType starttype = this.type; String kind = null; Position startLoc = this.startLoc; if (this.isLet()) { starttype = TokenType._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. if (starttype == TokenType._break || starttype == TokenType._continue) { return this.parseBreakContinueStatement(startLoc, starttype.keyword); } else if (starttype == TokenType._debugger) { return this.parseDebuggerStatement(startLoc); } else if (starttype == TokenType._do) { return this.parseDoStatement(startLoc); } else if (starttype == TokenType._for) { this.next(); return this.parseForStatement(startLoc); } else if (starttype == TokenType._function) { if (!declaration && this.options.ecmaVersion() >= 6) this.unexpected(); return this.parseFunctionStatement(startLoc, false); } else if (starttype == TokenType._class) { if (!declaration) this.unexpected(); return (Statement) this.parseClass(startLoc, true); } else if (starttype == TokenType._if) { return this.parseIfStatement(startLoc); } else if (starttype == TokenType._return) { return this.parseReturnStatement(startLoc); } else if (starttype == TokenType._switch) { return this.parseSwitchStatement(startLoc); } else if (starttype == TokenType._throw) { return this.parseThrowStatement(startLoc); } else if (starttype == TokenType._try) { return this.parseTryStatement(startLoc); } else if (starttype == TokenType._const || starttype == TokenType._var) { if (kind == null) kind = String.valueOf(this.value); if (!declaration && !kind.equals("var")) this.unexpected(); return this.parseVarStatement(startLoc, kind); } else if (starttype == TokenType._while) { return this.parseWhileStatement(startLoc); } else if (starttype == TokenType._with) { return this.parseWithStatement(startLoc); } else if (starttype == TokenType.braceL) { return this.parseBlock(false); } else if (starttype == TokenType.semi) { return this.parseEmptyStatement(startLoc); } else if (starttype == TokenType._export || starttype == TokenType._import) { if (!this.options.allowImportExportEverywhere()) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level"); if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } return starttype == TokenType._import ? this.parseImport(startLoc) : this.parseExport(startLoc, exports); } else { if (this.isAsyncFunction() && declaration) { this.next(); return this.parseFunctionStatement(startLoc, true); } // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. String maybeName = String.valueOf(this.value); Expression expr = this.parseExpression(false, null); if (starttype == TokenType.name && expr instanceof Identifier && this.eat(TokenType.colon)) return this.parseLabeledStatement(startLoc, maybeName, (Identifier) expr); else return this.parseExpressionStatement(declaration, startLoc, expr); } } protected Statement parseBreakContinueStatement(Position startLoc, String keyword) { SourceLocation loc = new SourceLocation(startLoc); boolean isBreak = keyword.equals("break"); this.next(); Identifier label = null; if (this.eat(TokenType.semi) || this.insertSemicolon()) { label = null; } else if (this.type != TokenType.name) { this.unexpected(); } else { label = this.parseIdent(false); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. int i = 0; for (; i < labels.size(); ++i) { LabelInfo lab = labels.get(i); if (label == null || label.getName().equals(lab.name)) { if (lab.kind != null && (isBreak || lab.kind.equals("loop"))) break; if (label != null && isBreak) break; } } if (i == this.labels.size()) this.raise(startLoc, "Unsyntactic " + keyword); Statement node = isBreak ? new BreakStatement(loc, label) : new ContinueStatement(loc, label); return this.finishNode(node); } protected DebuggerStatement parseDebuggerStatement(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); this.next(); this.semicolon(); return this.finishNode(new DebuggerStatement(loc)); } protected DoWhileStatement parseDoStatement(Position startLoc) { this.next(); this.labels.push(loopLabel); Statement body = this.parseStatement(false, false); this.labels.pop(); this.expect(TokenType._while); Expression test = this.parseParenExpression(); if (this.options.ecmaVersion() >= 6) this.eat(TokenType.semi); else this.semicolon(); return this.finishNode(new DoWhileStatement(new SourceLocation(startLoc), test, body)); } // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. // This method assumes that the initial `for` token has already been consumed. protected Statement parseForStatement(Position startLoc) { this.labels.push(loopLabel); this.expect(TokenType.parenL); if (this.type == TokenType.semi) return this.parseFor(startLoc, null); boolean isLet = this.isLet(); if (this.type == TokenType._var || this.type == TokenType._const || isLet) { Position initStartLoc = this.startLoc; String kind = isLet ? "let" : String.valueOf(this.value); this.next(); VariableDeclaration init = this.finishNode(this.parseVar(initStartLoc, true, kind)); if ((this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of"))) && init.getDeclarations().size() == 1 && !(!kind.equals("var") && init.getDeclarations().get(0).hasInit())) return this.parseForIn(startLoc, init); return this.parseFor(startLoc, init); } DestructuringErrors refDestructuringErrors = new DestructuringErrors(); Expression init = this.parseExpression(true, refDestructuringErrors); if (this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of"))) { this.checkPatternErrors(refDestructuringErrors, true); init = (Expression) this.toAssignable(init, false); this.checkLVal(init, false, null); return this.parseForIn(startLoc, init); } else { this.checkExpressionErrors(refDestructuringErrors, true); } return this.parseFor(startLoc, init); } protected Statement parseFunctionStatement(Position startLoc, boolean isAsync) { this.next(); INode fn = this.parseFunction(startLoc, true, false, isAsync); // if we encountered an anonymous function, wrap it in an expression // statement (we will have logged a syntax error already) if (fn instanceof Expression) return this.finishNode( new ExpressionStatement(new SourceLocation(startLoc), (Expression) fn)); return (Statement) fn; } private boolean isFunction() { return this.type == TokenType._function || this.isAsyncFunction(); } protected Statement parseIfStatement(Position startLoc) { this.next(); Expression test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode Statement consequent = this.parseStatement(!this.strict && this.isFunction(), false); Statement alternate = this.eat(TokenType._else) ? this.parseStatement(!this.strict && this.isFunction(), false) : null; return this.finishNode( new IfStatement(new SourceLocation(startLoc), test, consequent, alternate)); } protected ReturnStatement parseReturnStatement(Position startLoc) { if (!this.inFunction && !this.options.allowReturnOutsideFunction()) this.raise(this.start, "'return' outside of function"); this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. Expression argument; if (this.eat(TokenType.semi) || this.insertSemicolon()) { argument = null; } else { argument = this.parseExpression(false, null); this.semicolon(); } return this.finishNode(new ReturnStatement(new SourceLocation(startLoc), argument)); } protected SwitchStatement parseSwitchStatement(Position startLoc) { this.next(); Expression discriminant = this.parseParenExpression(); List<SwitchCase> cases = new ArrayList<SwitchCase>(); this.expect(TokenType.braceL); this.labels.push(switchLabel); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. boolean sawDefault = false; Position curCaseStart = null; Expression curTest = null; List<Statement> curConsequent = null; while (this.type != TokenType.braceR) { if (this.type == TokenType._case || this.type == TokenType._default) { boolean isCase = this.type == TokenType._case; if (curConsequent != null) cases.add( this.finishNode( new SwitchCase(new SourceLocation(curCaseStart), curTest, curConsequent))); curCaseStart = this.startLoc; curTest = null; curConsequent = new ArrayList<Statement>(); this.next(); if (isCase) { curTest = this.parseExpression(false, null); } else { if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); sawDefault = true; curTest = null; } this.expect(TokenType.colon); } else { if (curConsequent == null) this.unexpected(); Statement stmt = this.parseStatement(true, false); if (stmt != null) curConsequent.add(stmt); } } if (curConsequent != null) cases.add( this.finishNode( new SwitchCase(new SourceLocation(curCaseStart), curTest, curConsequent))); this.next(); // Closing brace this.labels.pop(); return this.finishNode(new SwitchStatement(new SourceLocation(startLoc), discriminant, cases)); } protected ThrowStatement parseThrowStatement(Position startLoc) { this.next(); if (inputSubstring(this.lastTokEnd, this.start).matches("(?s).*(?:" + lineBreak + ").*")) this.raise(this.lastTokEnd, "Illegal newline after throw"); Expression argument = this.parseExpression(false, null); this.semicolon(); return this.finishNode(new ThrowStatement(new SourceLocation(startLoc), argument)); } protected TryStatement parseTryStatement(Position startLoc) { this.next(); BlockStatement block = this.parseBlock(false); CatchClause handler = this.type == TokenType._catch ? this.parseCatchClause(this.startLoc) : null; BlockStatement finalizer = this.eat(TokenType._finally) ? this.parseBlock(false) : null; if (handler == null && finalizer == null) this.raise(startLoc, "Missing catch or finally clause"); return this.finishNode( new TryStatement(new SourceLocation(startLoc), block, handler, null, finalizer)); } protected CatchClause parseCatchClause(Position startLoc) { this.next(); this.expect(TokenType.parenL); Expression param = this.parseBindingAtom(); this.checkLVal(param, true, null); this.expect(TokenType.parenR); BlockStatement catchBody = this.parseBlock(false); return this.finishNode( new CatchClause(new SourceLocation(startLoc), (IPattern) param, null, catchBody)); } protected Statement parseVarStatement(Position startLoc, String kind) { this.next(); VariableDeclaration node = this.parseVar(startLoc, false, kind); this.semicolon(); return this.finishNode(node); } protected WhileStatement parseWhileStatement(Position startLoc) { this.next(); Expression test = this.parseParenExpression(); this.labels.push(loopLabel); Statement body = this.parseStatement(false, false); this.labels.pop(); return this.finishNode(new WhileStatement(new SourceLocation(startLoc), test, body)); } protected WithStatement parseWithStatement(Position startLoc) { if (this.strict) this.raise(startLoc, "'with' in strict mode"); this.next(); Expression object = this.parseParenExpression(); Statement body = this.parseStatement(false, false); return this.finishNode(new WithStatement(new SourceLocation(startLoc), object, body)); } protected EmptyStatement parseEmptyStatement(Position startLoc) { this.next(); return this.finishNode(new EmptyStatement(new SourceLocation(startLoc))); } protected LabeledStatement parseLabeledStatement( Position startLoc, String maybeName, Identifier expr) { for (int i = 0; i < this.labels.size(); ++i) if (maybeName.equals(this.labels.get(i).name)) this.raise(expr, "Label '" + maybeName + "' is already declared"); String kind = this.type.isLoop ? "loop" : this.type == TokenType._switch ? "switch" : null; for (int i = this.labels.size() - 1; i >= 0; i--) { LabelInfo label = this.labels.get(i); if (label.statementStart == startLoc.getOffset()) { label.statementStart = this.start; label.kind = kind; } else { break; } } this.labels.push(new LabelInfo(maybeName, kind, this.start)); Statement body = this.parseStatement(true, false); this.labels.pop(); if (body == null) return null; Identifier label = expr; return this.finishNode(new LabeledStatement(new SourceLocation(startLoc), label, body)); } protected ExpressionStatement parseExpressionStatement( boolean declaration, Position startLoc, Expression expr) { this.semicolon(); return this.finishNode(new ExpressionStatement(new SourceLocation(startLoc), expr)); } // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). protected BlockStatement parseBlock(boolean allowStrict) { Position startLoc = this.startLoc; boolean first = true; Boolean oldStrict = null; List<Statement> body = new ArrayList<Statement>(); this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { Statement stmt = this.parseStatement(true, false); if (stmt != null) body.add(stmt); if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict; this.setStrict(this.strict = true); } first = false; } if (oldStrict == Boolean.FALSE) this.setStrict(false); return this.finishNode(new BlockStatement(new SourceLocation(startLoc), body)); } // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. protected ForStatement parseFor(Position startLoc, Node init) { this.expect(TokenType.semi); Expression test = this.type == TokenType.semi ? null : this.parseExpression(false, null); this.expect(TokenType.semi); Expression update = this.type == TokenType.parenR ? null : this.parseExpression(false, null); this.expect(TokenType.parenR); Statement body = this.parseStatement(false, false); this.labels.pop(); return this.finishNode( new ForStatement(new SourceLocation(startLoc), init, test, update, body)); } // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. protected Statement parseForIn(Position startLoc, Node left) { SourceLocation loc = new SourceLocation(startLoc); boolean isForIn = this.type == TokenType._in; this.next(); Expression right = this.parseExpression(false, null); this.expect(TokenType.parenR); Statement body = this.parseStatement(false, false); this.labels.pop(); EnhancedForStatement node; if (isForIn) node = new ForInStatement(loc, left, right, body, false); else node = new ForOfStatement(loc, left, right, body); return this.finishNode(node); } // Parse a list of variable declarations. protected VariableDeclaration parseVar(Position startLoc, boolean isFor, String kind) { List<VariableDeclarator> declarations = new ArrayList<VariableDeclarator>(); for (; ; ) { Position varDeclStart = this.startLoc; Expression id = this.parseVarId(); Expression init = null; if (this.eat(TokenType.eq)) { init = this.parseMaybeAssign(isFor, null, null); } else if (kind.equals("const") && !(this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of")))) { this.raiseRecoverable( this.lastTokEnd, "Constant declarations require an initialization value"); } else if (!(id instanceof Identifier) && !(isFor && (this.type == TokenType._in || this.isContextual("of")))) { this.raiseRecoverable( this.lastTokEnd, "Complex binding patterns require an initialization value"); } declarations.add( this.finishNode( new VariableDeclarator( new SourceLocation(varDeclStart), (IPattern) id, init, noTypeAnnotation, DeclarationFlags.none))); if (!this.eat(TokenType.comma)) break; } return new VariableDeclaration( new SourceLocation(startLoc), kind, declarations, noDeclareKeyword); } protected Expression parseVarId() { Expression res = this.parseBindingAtom(); this.checkLVal(res, true, null); return res; } /** * If {@code isStatement} is true and the function has a name, the result is a {@linkplain * FunctionDeclaration}, otherwise it is a {@linkplain FunctionExpression}. */ protected INode parseFunction( Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean isAsync) { boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; Pair<Boolean, Identifier> p = parseFunctionName(isStatement, isAsync); return parseFunctionRest( startLoc, isStatement, allowExpressionBody, oldInGen, oldInAsync, oldYieldPos, oldAwaitPos, p.fst(), p.snd()); } protected Pair<Boolean, Identifier> parseFunctionName(boolean isStatement, boolean isAsync) { boolean generator = parseGeneratorMarker(isAsync); Identifier id = null; if (isStatement) if (this.type == TokenType.name) id = this.parseIdent(false); else this.raise(this.start, "Missing function name", true); this.inGenerator = generator; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; if (!isStatement && this.type == TokenType.name) id = this.parseIdent(false); return Pair.make(generator, id); } protected boolean parseGeneratorMarker(boolean isAsync) { boolean generator = false; if (this.options.ecmaVersion() >= 6 && !isAsync) generator = this.eat(TokenType.star); return generator; } protected IFunction parseFunctionRest( Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean oldInGen, boolean oldInAsync, int oldYieldPos, int oldAwaitPos, boolean generator, Identifier id) { boolean async = this.inAsync; List<Expression> params = this.parseFunctionParams(); Node body = this.parseFunctionBody(id, params, allowExpressionBody); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; IFunction node; SourceLocation loc = new SourceLocation(startLoc); if (isStatement && id != null) node = new FunctionDeclaration(loc, id, params, body, generator, async); else node = new FunctionExpression(loc, id, params, body, generator, async); return this.finishNode(node); } protected List<Expression> parseFunctionParams() { this.expect(TokenType.parenL); List<Expression> params = this.parseBindingList(TokenType.parenR, false, this.options.ecmaVersion() >= 8, true); this.checkYieldAwaitInDefaultParams(); return params; } // Parse a class declaration or literal (depending on the // `isStatement` parameter). protected Node parseClass(Position startLoc, boolean isStatement) { boolean oldInClass = this.inClass; this.inClass = true; SourceLocation loc = new SourceLocation(startLoc); this.next(); Identifier id = this.parseClassId(isStatement); Expression superClass = this.parseClassSuper(); Position bodyStartLoc = this.startLoc; boolean hadConstructor = false; List<MemberDefinition<?>> body = new ArrayList<MemberDefinition<?>>(); this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (this.eat(TokenType.semi)) continue; MemberDefinition<?> member = parseClassMember(hadConstructor); body.add(member); hadConstructor = hadConstructor || member.isConstructor(); } ClassBody classBody = this.finishNode(new ClassBody(new SourceLocation(bodyStartLoc), body)); Node node; if (isStatement) node = new ClassDeclaration(loc, id, superClass, classBody); else node = new ClassExpression(loc, id, superClass, classBody); this.inClass = oldInClass; return this.finishNode(node); } /** Parse a member declaration in a class. */ protected MemberDefinition<?> parseClassMember(boolean hadConstructor) { Position methodStartLoc = this.startLoc; boolean isGenerator = this.eat(TokenType.star); boolean isMaybeStatic = this.type == TokenType.name && this.value.equals("static"); PropertyInfo pi = new PropertyInfo(false, isGenerator, methodStartLoc); this.parsePropertyName(pi); boolean isStatic = isMaybeStatic && this.type != TokenType.parenL; if (isStatic) { if (isGenerator) this.unexpected(); isGenerator = this.eat(TokenType.star); pi = new PropertyInfo(false, isGenerator, methodStartLoc); this.parsePropertyName(pi); } if (this.options.ecmaVersion() >= 8 && !isGenerator && this.isAsyncProp(pi)) { pi.isAsync = true; pi.isGenerator = this.eat(TokenType.star); this.parsePropertyName(pi); } return parseClassPropertyBody(pi, hadConstructor, isStatic); } protected boolean atGetterSetterName(PropertyInfo pi) { return !pi.isGenerator && !pi.isAsync && pi.key instanceof Identifier && this.type != TokenType.parenL && (((Identifier) pi.key).getName().equals("get") || ((Identifier) pi.key).getName().equals("set")); } /** Parse a method declaration in a class, assuming that its name has already been consumed. */ protected MemberDefinition<?> parseClassPropertyBody( PropertyInfo pi, boolean hadConstructor, boolean isStatic) { pi.kind = "method"; boolean isGetSet = false; if (!pi.computed) { if (atGetterSetterName(pi)) { isGetSet = true; pi.kind = ((Identifier) pi.key).getName(); this.parsePropertyName(pi); } if (!isStatic && (pi.key instanceof Identifier && ((Identifier) pi.key).getName().equals("constructor") || pi.key instanceof Literal && ((Literal) pi.key).getStringValue().equals("constructor"))) { if (hadConstructor) this.raise(pi.key, "Duplicate constructor in the same class"); if (isGetSet) this.raise(pi.key, "Constructor can't have get/set modifier"); if (pi.isGenerator) this.raise(pi.key, "Constructor can't be a generator"); if (pi.isAsync) this.raise(pi.key, "Constructor can't be an async method"); pi.kind = "constructor"; } } MethodDefinition node = this.parseClassMethod( pi.startLoc, pi.isGenerator, pi.isAsync, isStatic, pi.computed, pi.getMethodKind(), pi.key); if (isGetSet) { int paramCount = pi.kind.equals("get") ? 0 : 1; List<Expression> params = node.getValue().getRawParameters(); if (params.size() != paramCount) { if (pi.kind.equals("get")) this.raiseRecoverable(node.getValue(), "getter should have no params"); else this.raiseRecoverable(node.getValue(), "setter should have exactly one param"); } if (pi.kind.equals("set") && node.getValue().hasRest()) this.raiseRecoverable(params.get(params.size() - 1), "Setter cannot use rest params"); } if (pi.key instanceof Identifier && ((Identifier)pi.key).getName().startsWith("#")) { raiseRecoverable(pi.key, "Only fields, not methods, can be declared private."); } return node; } protected MethodDefinition parseClassMethod( Position startLoc, boolean isGenerator, boolean isAsync, boolean isStatic, boolean isComputed, MethodDefinition.Kind kind, Expression key) { SourceLocation loc = new SourceLocation(startLoc); FunctionExpression body = this.parseMethod(isGenerator, isAsync); int flags = DeclarationFlags.getStatic(isStatic) | DeclarationFlags.getComputed(isComputed); MethodDefinition m = new MethodDefinition(loc, flags, kind, key, body); return this.finishNode(m); } protected Identifier parseClassId(boolean isStatement) { if (this.type == TokenType.name) return this.parseIdent(false); if (isStatement) this.unexpected(); return null; } protected Expression parseClassSuper() { return this.eat(TokenType._extends) ? this.parseExprSubscripts(null) : null; } // Parses module export declaration. protected ExportDeclaration parseExport(Position startLoc, Set<String> exports) { SourceLocation loc = new SourceLocation(startLoc); this.next(); return parseExportRest(loc, exports); } /** * Parse the body of an {@code export} declaration, assuming that the {@code export} keyword * itself has already been consumed. */ protected ExportDeclaration parseExportRest(SourceLocation loc, Set<String> exports) { Position exportRestLoc = startLoc; // export * from '...' if (this.eat(TokenType.star)) { return parseExportAll(loc, exportRestLoc, exports); } if (this.eat(TokenType._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStartLoc); boolean isAsync = false; Node declaration; if (this.type == TokenType._function || (isAsync = this.isAsyncFunction())) { Position startLoc = this.startLoc; this.next(); if (isAsync) this.next(); FunctionExpression fe = (FunctionExpression) this.parseFunction(startLoc, false, false, isAsync); if (fe.hasId()) declaration = new FunctionDeclaration( fe.getLoc(), fe.getId(), fe.getRawParameters(), (BlockStatement) fe.getBody(), fe.isGenerator(), fe.isAsync()); else declaration = fe; } else if (this.type == TokenType._class) { ClassExpression ce = (ClassExpression) parseClass(this.startLoc, false); if (ce.getClassDef().hasId()) declaration = new ClassDeclaration(ce.getLoc(), ce.getClassDef(), noDeclareKeyword, notAbstract); else declaration = ce; } else { declaration = this.parseMaybeAssign(false, null, null); this.semicolon(); } return this.finishNode(new ExportDefaultDeclaration(loc, declaration)); } // export var|const|let|function|class ... Statement declaration; List<ExportSpecifier> specifiers; Expression source = null; if (this.shouldParseExportStatement()) { declaration = this.parseStatement(true, false); if (declaration == null) return null; if (declaration instanceof VariableDeclaration) { checkVariableExport(exports, ((VariableDeclaration) declaration).getDeclarations()); } else { Identifier id = getId(declaration); if (id != null) checkExport(exports, id.getName(), id.getLoc().getStart()); } specifiers = new ArrayList<ExportSpecifier>(); source = null; } else { // export { x, y as z } [from '...'] declaration = null; specifiers = this.parseExportSpecifiers(exports); source = parseExportFrom(specifiers, source, false); } return this.finishNode( new ExportNamedDeclaration(loc, declaration, specifiers, (Literal) source)); } protected Expression parseExportFrom( List<ExportSpecifier> specifiers, Expression source, boolean expectFrom) { if (this.eatContextual("from")) { if (this.type == TokenType.string) source = this.parseExprAtom(null); else this.unexpected(); } else { if (expectFrom) this.unexpected(); // check for keywords used as local names for (ExportSpecifier specifier : specifiers) { String localName = specifier.getLocal().getName(); if (this.keywords.contains(localName) || this.reservedWords.contains(localName)) { this.unexpected(specifier.getLoc().getStart()); } } source = null; } this.semicolon(); return source; } protected ExportDeclaration parseExportAll( SourceLocation loc, Position starLoc, Set<String> exports) { Expression source = parseExportFrom(null, null, true); return this.finishNode(new ExportAllDeclaration(loc, (Literal) source)); } private void checkExport(Set<String> exports, String name, Position pos) { if (exports == null) return; if (exports.contains(name)) raiseRecoverable(pos.getOffset(), "Duplicate export '" + name + "'"); exports.add(name); } private void checkPatternExport(Set<String> exports, Expression pat) { if (pat instanceof Identifier) { checkExport(exports, ((Identifier) pat).getName(), pat.getLoc().getStart()); } else if (pat instanceof ObjectPattern) { for (Property prop : ((ObjectPattern) pat).getProperties()) checkPatternExport(exports, prop.getValue()); } else if (pat instanceof ArrayPattern) { for (Expression elt : ((ArrayPattern) pat).getElements()) if (elt != null) checkPatternExport(exports, elt); } else if (pat instanceof AssignmentPattern) { checkPatternExport(exports, ((AssignmentPattern) pat).getLeft()); } else if (pat instanceof ParenthesizedExpression) { checkPatternExport(exports, ((ParenthesizedExpression) pat).getExpression()); } } private void checkVariableExport(Set<String> exports, List<VariableDeclarator> decls) { if (exports == null) return; for (VariableDeclarator decl : decls) checkPatternExport(exports, (Expression) decl.getId()); } protected boolean shouldParseExportStatement() { return this.type.keyword != null || this.isLet() || this.isAsyncFunction(); } // Parses a comma-separated list of module exports. protected List<ExportSpecifier> parseExportSpecifiers(Set<String> exports) { List<ExportSpecifier> nodes = new ArrayList<ExportSpecifier>(); boolean first = true; // export { x, y as z } [from '...'] this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } SourceLocation loc = new SourceLocation(this.startLoc); Identifier local = this.parseIdent(this.type == TokenType._default); Identifier exported = this.eatContextual("as") ? this.parseIdent(true) : local; checkExport(exports, exported.getName(), exported.getLoc().getStart()); nodes.add(this.finishNode(new ExportSpecifier(loc, local, exported))); } return nodes; } // Parses import declaration. protected Statement parseImport(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); this.next(); return parseImportRest(loc); } protected ImportDeclaration parseImportRest(SourceLocation loc) { List<ImportSpecifier> specifiers; Literal source; // import '...' if (this.type == TokenType.string) { specifiers = new ArrayList<ImportSpecifier>(); source = (Literal) this.parseExprAtom(null); } else { specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); if (this.type != TokenType.string) this.unexpected(); source = (Literal) this.parseExprAtom(null); } this.semicolon(); if (specifiers == null) return null; return this.finishNode(new ImportDeclaration(loc, specifiers, source)); } // Parses a comma-separated list of module imports. protected List<ImportSpecifier> parseImportSpecifiers() { List<ImportSpecifier> nodes = new ArrayList<ImportSpecifier>(); boolean first = true; if (this.type == TokenType.name) { // import defaultObj, { x, y as z } from '...' SourceLocation loc = new SourceLocation(this.startLoc); Identifier local = this.parseIdent(false); this.checkLVal(local, true, null); nodes.add(this.finishNode(new ImportDefaultSpecifier(loc, local))); if (!this.eat(TokenType.comma)) return nodes; } if (this.type == TokenType.star) { SourceLocation loc = new SourceLocation(this.startLoc); this.next(); this.expectContextual("as"); Identifier local = this.parseIdent(false); this.checkLVal(local, true, null); nodes.add(this.finishNode(new ImportNamespaceSpecifier(loc, local))); return nodes; } this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } ImportSpecifier importSpecifier = parseImportSpecifier(); if (importSpecifier != null) nodes.add(importSpecifier); } return nodes; } protected ImportSpecifier parseImportSpecifier() { SourceLocation loc = new SourceLocation(this.startLoc); Identifier imported = this.parseIdent(true), local; if (this.eatContextual("as")) { local = this.parseIdent(false); } else { local = imported; if (this.keywords.contains(local.getName())) this.unexpected(local.getLoc().getStart()); if (this.reservedWordsStrict.contains(local.getName())) this.raiseRecoverable(local, "The keyword '" + local.getName() + "' is reserved"); } this.checkLVal(local, true, null); return this.finishNode(new ImportSpecifier(loc, imported, local)); } /// end statement.js /// helpers protected Number parseInt(String s, int radix) { return stringToNumber(s, 0, radix); } protected Number parseFloat(String s) { try { return Double.valueOf(s); } catch (NumberFormatException nfe) { this.raise(this.start, "Invalid number"); return null; } } protected int charAt(int i) { if (i < input.length()) return input.charAt(i); else return -1; } protected String inputSubstring(int start, int end) { if (start >= input.length()) return ""; if (end > input.length()) end = input.length(); return input.substring(start, end); } protected Identifier getId(Statement s) { if (s instanceof ClassDeclaration) return ((ClassDeclaration) s).getClassDef().getId(); if (s instanceof FunctionDeclaration) return ((FunctionDeclaration) s).getId(); return null; } /* * Helper function for toNumber, parseInt, and TokenStream.getToken. * * Copied from Rhino. */ private static double stringToNumber(String s, int start, int radix) { char digitMax = '9'; char lowerCaseBound = 'a'; char upperCaseBound = 'A'; int len = s.length(); if (radix < 10) { digitMax = (char) ('0' + radix - 1); } if (radix > 10) { lowerCaseBound = (char) ('a' + radix - 10); upperCaseBound = (char) ('A' + radix - 10); } int end; double sum = 0.0; for (end = start; end < len; end++) { char c = s.charAt(end); int newDigit; if ('0' <= c && c <= digitMax) newDigit = c - '0'; else if ('a' <= c && c < lowerCaseBound) newDigit = c - 'a' + 10; else if ('A' <= c && c < upperCaseBound) newDigit = c - 'A' + 10; else break; sum = sum * radix + newDigit; } if (start == end) { return Double.NaN; } if (sum >= 9007199254740992.0) { if (radix == 10) { /* If we're accumulating a decimal number and the number * is >= 2^53, then the result from the repeated multiply-add * above may be inaccurate. Call Java to get the correct * answer. */ try { return Double.parseDouble(s.substring(start, end)); } catch (NumberFormatException nfe) { return Double.NaN; } } else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32) { /* The number may also be inaccurate for one of these bases. * This happens if the addition in value*radix + digit causes * a round-down to an even least significant mantissa bit * when the first dropped bit is a one. If any of the * following digits in the number (which haven't been added * in yet) are nonzero then the correct action would have * been to round up instead of down. An example of this * occurs when reading the number 0x1000000000000081, which * rounds to 0x1000000000000000 instead of 0x1000000000000100. */ int bitShiftInChar = 1; int digit = 0; final int SKIP_LEADING_ZEROS = 0; final int FIRST_EXACT_53_BITS = 1; final int AFTER_BIT_53 = 2; final int ZEROS_AFTER_54 = 3; final int MIXED_AFTER_54 = 4; int state = SKIP_LEADING_ZEROS; int exactBitsLimit = 53; double factor = 0.0; boolean bit53 = false; // bit54 is the 54th bit (the first dropped from the mantissa) boolean bit54 = false; for (; ; ) { if (bitShiftInChar == 1) { if (start == end) break; digit = s.charAt(start++); if ('0' <= digit && digit <= '9') digit -= '0'; else if ('a' <= digit && digit <= 'z') digit -= 'a' - 10; else digit -= 'A' - 10; bitShiftInChar = radix; } bitShiftInChar >>= 1; boolean bit = (digit & bitShiftInChar) != 0; switch (state) { case SKIP_LEADING_ZEROS: if (bit) { --exactBitsLimit; sum = 1.0; state = FIRST_EXACT_53_BITS; } break; case FIRST_EXACT_53_BITS: sum *= 2.0; if (bit) sum += 1.0; --exactBitsLimit; if (exactBitsLimit == 0) { bit53 = bit; state = AFTER_BIT_53; } break; case AFTER_BIT_53: bit54 = bit; factor = 2.0; state = ZEROS_AFTER_54; break; case ZEROS_AFTER_54: if (bit) { state = MIXED_AFTER_54; } // fallthrough case MIXED_AFTER_54: factor *= 2; break; } } switch (state) { case SKIP_LEADING_ZEROS: sum = 0.0; break; case FIRST_EXACT_53_BITS: case AFTER_BIT_53: // do nothing break; case ZEROS_AFTER_54: // x1.1 -> x1 + 1 (round up) // x0.1 -> x0 (round down) if (bit54 & bit53) sum += 1.0; sum *= factor; break; case MIXED_AFTER_54: // x.100...1.. -> x + 1 (round up) // x.0anything -> x (round down) if (bit54) sum += 1.0; sum *= factor; break; } } /* We don't worry about inaccurate numbers for any other base. */ } return sum; } /** * Return the next {@code n} characters of lookahead (or as many as are available), after skipping * over whitespace and comments. */ protected String lookahead(int n, boolean allowNewline) { Matcher m = (allowNewline ? Whitespace.skipWhiteSpace : Whitespace.skipWhiteSpaceNoNewline) .matcher(this.input); m.find(this.pos); return this.inputSubstring(m.end(), m.end() + n); } /** * Is the next input token (after skipping over whitespace and comments) the identifier {@code * name}? */ protected boolean lookaheadIsIdent(String name, boolean allowNewline) { int n = name.length(); String lh = lookahead(n + 1, allowNewline); return lh.startsWith(name) && (lh.length() == n || !Identifiers.isIdentifierChar(lh.codePointAt(n), true)); } // getters and setters public void pushTokenContext(TokContext ctxt) { this.context.push(ctxt); } public TokContext popTokenContext() { return this.context.pop(); } public void exprAllowed(boolean exprAllowed) { this.exprAllowed = exprAllowed; } }
139,605
36.498254
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/TokenType.java
package com.semmle.jcorn; import com.semmle.jcorn.Parser.TokContext; import java.util.LinkedHashMap; import java.util.Map; /// tokentype.js // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. public class TokenType { // Map keyword names to token types. public static final Map<String, TokenType> keywords = new LinkedHashMap<>(); public static final TokenType num = new TokenType(new Properties("num").startsExpr()), bigint = new TokenType(new Properties("bigint").startsExpr()), regexp = new TokenType(new Properties("regexp").startsExpr()), string = new TokenType(new Properties("string").startsExpr()), name = new TokenType(new Properties("name").startsExpr()), eof = new TokenType(new Properties("eof")), // Punctuation token types. bracketL = new TokenType(new Properties("[").beforeExpr().startsExpr()), bracketR = new TokenType(new Properties("]")), braceL = new TokenType(new Properties("{").beforeExpr().startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { parser.context.push( parser.braceIsBlock(prevType) ? TokContext.b_stat : TokContext.b_expr); parser.exprAllowed = true; } }, braceR = new TokenType(new Properties("}")) { @Override public void updateContext(Parser parser, TokenType prevType) { updateParenBraceRContext(parser); } }, parenL = new TokenType(new Properties("(").beforeExpr().startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { boolean statementParens = prevType == TokenType._if || prevType == TokenType._for || prevType == TokenType._with || prevType == TokenType._while; parser.context.push(statementParens ? TokContext.p_stat : TokContext.p_expr); parser.exprAllowed = true; } }, parenR = new TokenType(new Properties(")")) { @Override public void updateContext(Parser parser, TokenType prevType) { updateParenBraceRContext(parser); } }, comma = new TokenType(new Properties(",").beforeExpr()), semi = new TokenType(new Properties(";").beforeExpr()), colon = new TokenType(new Properties(":").beforeExpr()), dot = new TokenType(new Properties(".")), questiondot = new TokenType(new Properties("?.")), question = new TokenType(new Properties("?").beforeExpr()), pound = new TokenType(kw("#")), arrow = new TokenType(new Properties("=>").beforeExpr()), template = new TokenType(new Properties("template")), invalidTemplate = new TokenType(new Properties("invalidTemplate")), ellipsis = new TokenType(new Properties("...").beforeExpr()), backQuote = new TokenType(new Properties("`").startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { if (parser.curContext() == TokContext.q_tmpl) parser.context.pop(); else parser.context.push(TokContext.q_tmpl); parser.exprAllowed = false; } }, dollarBraceL = new TokenType(new Properties("${").beforeExpr().startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { parser.context.push(TokContext.b_tmpl); parser.exprAllowed = true; } }, // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq = new TokenType(new Properties("=").beforeExpr().isAssign()), assign = new TokenType(new Properties("_=").beforeExpr().isAssign()), incDec = new TokenType(new Properties("++/--").prefix().postfix().startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { // exprAllowed stays unchanged } }, prefix = new TokenType(new Properties("prefix").beforeExpr().prefix().startsExpr()), questionquestion = new TokenType(binop("??", 1)), logicalOR = new TokenType(binop("||", 1)), logicalAND = new TokenType(binop("&&", 2)), bitwiseOR = new TokenType(binop("|", 3)), bitwiseXOR = new TokenType(binop("^", 4)), bitwiseAND = new TokenType(binop("&", 5)), equality = new TokenType(binop("==/!=", 6)), relational = new TokenType(binop("</>", 7)), bitShift = new TokenType(binop("<</>>", 8)), plusMin = new TokenType(new Properties("+/-").beforeExpr().binop(9).prefix().startsExpr()), modulo = new TokenType(binop("%", 10)), star = new TokenType(binop("*", 10)), slash = new TokenType(binop("/", 10)), starstar = new TokenType(new Properties("**").beforeExpr()), _break = new TokenType(kw("break")), _case = new TokenType(kw("case").beforeExpr()), _catch = new TokenType(kw("catch")), _continue = new TokenType(kw("continue")), _debugger = new TokenType(kw("debugger")), _default = new TokenType(kw("default").beforeExpr()), _do = new TokenType(kw("do").isLoop().beforeExpr()), _else = new TokenType(kw("else").beforeExpr()), _finally = new TokenType(kw("finally")), _for = new TokenType(kw("for").isLoop()), _function = new TokenType(kw("function").startsExpr()) { @Override public void updateContext(Parser parser, TokenType prevType) { if (prevType.beforeExpr && prevType != TokenType.semi && prevType != TokenType._else && !((prevType == TokenType.colon || prevType == TokenType.braceL) && parser.curContext() == TokContext.b_stat)) parser.context.push(TokContext.f_expr); parser.exprAllowed = false; } }, _if = new TokenType(kw("if")), _return = new TokenType(kw("return").beforeExpr()), _switch = new TokenType(kw("switch")), _throw = new TokenType(kw("throw").beforeExpr()), _try = new TokenType(kw("try")), _var = new TokenType(kw("var")), _const = new TokenType(kw("const")), _while = new TokenType(kw("while").isLoop()), _with = new TokenType(kw("with")), _new = new TokenType(kw("new").beforeExpr().startsExpr()), _this = new TokenType(kw("this").startsExpr()), _super = new TokenType(kw("super").startsExpr()), _class = new TokenType(kw("class")), _extends = new TokenType(kw("extends").beforeExpr()), _export = new TokenType(kw("export")), _import = new TokenType(kw("import").startsExpr()), _null = new TokenType(kw("null").startsExpr()), _true = new TokenType(kw("true").startsExpr()), _false = new TokenType(kw("false").startsExpr()), _in = new TokenType(kw("in").beforeExpr().binop(7)), _instanceof = new TokenType(kw("instanceof").beforeExpr().binop(7)), _typeof = new TokenType(kw("typeof").beforeExpr().prefix().startsExpr()), _void = new TokenType(kw("void").beforeExpr().prefix().startsExpr()), _delete = new TokenType(kw("delete").beforeExpr().prefix().startsExpr()); public final String label, keyword; public final boolean beforeExpr, startsExpr, isLoop, isAssign, isPrefix, isPostfix; public final int binop; public void updateContext(Parser parser, TokenType prevType) { parser.exprAllowed = this.beforeExpr; } // Token-specific context update code protected void updateParenBraceRContext(Parser parser) { if (parser.context.size() == 1) { parser.exprAllowed = true; return; } TokContext out = parser.context.pop(); if (out == TokContext.b_stat && parser.curContext() == TokContext.f_expr) { parser.context.pop(); parser.exprAllowed = false; } else if (out == TokContext.b_tmpl) { parser.exprAllowed = true; } else { parser.exprAllowed = !out.isExpr; } } public TokenType(Properties prop) { this.label = prop.label; this.keyword = prop.keyword; this.beforeExpr = prop.beforeExpr; this.startsExpr = prop.startsExpr; this.isLoop = prop.isLoop; this.isAssign = prop.isAssign; this.isPrefix = prop.prefix; this.isPostfix = prop.postfix; this.binop = prop.binop; if (this.keyword != null) keywords.put(this.keyword, this); } public static class Properties { public String label, keyword; public boolean beforeExpr, startsExpr, isLoop, isAssign, prefix, postfix; public int binop; public Properties(String label, String keyword) { this.label = label; this.keyword = keyword; } public Properties(String label) { this(label, null); } public Properties beforeExpr() { this.beforeExpr = true; return this; } public Properties startsExpr() { this.startsExpr = true; return this; } public Properties isLoop() { this.isLoop = true; return this; } public Properties isAssign() { this.isAssign = true; return this; } public Properties prefix() { this.prefix = true; return this; } public Properties postfix() { this.postfix = true; return this; } public Properties binop(int prec) { this.binop = prec; return this; } } private static Properties binop(String name, int prec) { return new Properties(name, null).binop(prec).beforeExpr(); } // Succinct definitions of keyword token types private static Properties kw(String name) { return new Properties(name, name); } }
11,361
37.778157
97
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/Options.java
package com.semmle.jcorn; import com.semmle.jcorn.Identifiers.Dialect; import com.semmle.js.ast.Comment; import com.semmle.js.ast.Position; import com.semmle.js.ast.Program; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Token; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /// options.js public class Options { public enum AllowReserved { YES(true), NO(false), NEVER(false); private final boolean isTrue; private AllowReserved(boolean isTrue) { this.isTrue = isTrue; } public boolean isTrue() { return isTrue; } } public interface OnCommentCallback { public void call( boolean block, String input, String text, int start, int end, Position startLoc, Position endLoc); } private boolean allowHashBang, allowReturnOutsideFunction, allowImportExportEverywhere; private boolean preserveParens, mozExtensions, jscript, esnext, v8Extensions, e4x; private int ecmaVersion; private AllowReserved allowReserved; private String sourceType; private BiFunction<Integer, Position, Void> onInsertedSemicolon, onTrailingComma; private Function<Token, Void> onToken; private OnCommentCallback onComment; private Program program; private Function<SyntaxError, ?> onRecoverableError; public Options() { this.ecmaVersion = 10; this.sourceType = "script"; this.onInsertedSemicolon = null; this.onTrailingComma = null; this.allowReserved = AllowReserved.YES; this.allowReturnOutsideFunction = false; this.allowImportExportEverywhere = false; this.allowHashBang = false; this.onToken = null; this.onComment = null; this.program = null; this.preserveParens = false; this.mozExtensions = false; this.jscript = false; this.esnext = false; this.v8Extensions = false; this.e4x = false; this.onRecoverableError = null; } public Options(Options that) { this.allowHashBang = that.allowHashBang; this.allowReturnOutsideFunction = that.allowReturnOutsideFunction; this.allowImportExportEverywhere = that.allowImportExportEverywhere; this.preserveParens = that.preserveParens; this.mozExtensions = that.mozExtensions; this.jscript = that.jscript; this.esnext = that.esnext; this.v8Extensions = that.v8Extensions; this.e4x = that.e4x; this.ecmaVersion = that.ecmaVersion; this.allowReserved = that.allowReserved; this.sourceType = that.sourceType; this.onInsertedSemicolon = that.onInsertedSemicolon; this.onTrailingComma = that.onTrailingComma; this.onToken = that.onToken; this.onComment = that.onComment; this.program = that.program; this.onRecoverableError = that.onRecoverableError; } public boolean allowHashBang() { return allowHashBang; } public boolean allowReturnOutsideFunction() { return allowReturnOutsideFunction; } public boolean allowImportExportEverywhere() { return allowImportExportEverywhere; } public boolean preserveParens() { return preserveParens; } public boolean mozExtensions() { return mozExtensions; } public boolean jscript() { return jscript; } public boolean esnext() { return esnext; } public boolean v8Extensions() { return v8Extensions; } public boolean e4x() { return e4x; } public Identifiers.Dialect getDialect() { switch (ecmaVersion) { case 3: return Dialect.ECMA_3; case 5: return Dialect.ECMA_5; case 6: return Dialect.ECMA_6; case 8: return Dialect.ECMA_8; default: return Dialect.ECMA_7; } } public int ecmaVersion() { return ecmaVersion; } public Options ecmaVersion(int ecmaVersion) { if (ecmaVersion >= 2015) ecmaVersion -= 2009; this.ecmaVersion = ecmaVersion; if (ecmaVersion >= 5) this.allowReserved = AllowReserved.NO; return this; } public AllowReserved allowReserved() { return allowReserved; } public Options onComment(List<Comment> comments) { this.onComment = (block, input, text, start, end, startLoc, endLoc) -> { String src = input.substring(start, end); comments.add(new Comment(new SourceLocation(src, startLoc, endLoc), text)); }; return this; } public String sourceType() { return sourceType; } public Options sourceType(String sourceType) { this.sourceType = sourceType; return this; } public Options mozExtensions(boolean mozExtensions) { this.mozExtensions = mozExtensions; return this; } public Options jscript(boolean jscript) { this.jscript = jscript; return this; } public Options esnext(boolean esnext) { this.esnext = esnext; return this; } public void v8Extensions(boolean v8Extensions) { this.v8Extensions = v8Extensions; } public void e4x(boolean e4x) { this.e4x = e4x; } public Options preserveParens(boolean preserveParens) { this.preserveParens = preserveParens; return this; } public Options allowReturnOutsideFunction(boolean allowReturnOutsideFunction) { this.allowReturnOutsideFunction = allowReturnOutsideFunction; return this; } public Options allowImportExportEverywhere(boolean allowImportExportEverywhere) { this.allowImportExportEverywhere = allowImportExportEverywhere; return this; } public BiFunction<Integer, Position, Void> onInsertedSemicolon() { return onInsertedSemicolon; } public BiFunction<Integer, Position, Void> onTrailingComma() { return onTrailingComma; } public Function<Token, Void> onToken() { return onToken; } public Options onToken(List<Token> tokens) { return onToken( (tk) -> { tokens.add(tk); return null; }); } public Options onToken(Function<Token, Void> tmp) { this.onToken = tmp; return this; } public OnCommentCallback onComment() { return onComment; } public Program program() { return program; } public Options onRecoverableError(Function<SyntaxError, ?> onRecoverableError) { this.onRecoverableError = onRecoverableError; return this; } public Function<SyntaxError, ?> onRecoverableError() { return onRecoverableError; } }
6,370
23.503846
89
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/CustomParser.java
package com.semmle.jcorn; import com.semmle.jcorn.TokenType.Properties; import com.semmle.jcorn.flow.FlowParser; import com.semmle.js.ast.ArrayExpression; import com.semmle.js.ast.AssignmentExpression; import com.semmle.js.ast.BlockStatement; import com.semmle.js.ast.CallExpression; import com.semmle.js.ast.CatchClause; import com.semmle.js.ast.Chainable; import com.semmle.js.ast.ClassExpression; import com.semmle.js.ast.ComprehensionBlock; import com.semmle.js.ast.ComprehensionExpression; import com.semmle.js.ast.Decorator; import com.semmle.js.ast.Expression; import com.semmle.js.ast.ExpressionStatement; import com.semmle.js.ast.ForInStatement; import com.semmle.js.ast.FunctionDeclaration; import com.semmle.js.ast.IFunction; import com.semmle.js.ast.INode; import com.semmle.js.ast.IPattern; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.LetExpression; import com.semmle.js.ast.LetStatement; import com.semmle.js.ast.MemberExpression; import com.semmle.js.ast.NewExpression; import com.semmle.js.ast.Node; import com.semmle.js.ast.ParenthesizedExpression; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Token; import com.semmle.js.ast.TryStatement; import com.semmle.js.ast.VariableDeclaration; import com.semmle.js.ast.XMLAnyName; import com.semmle.js.ast.XMLAttributeSelector; import com.semmle.js.ast.XMLDotDotExpression; import com.semmle.js.ast.XMLFilterExpression; import com.semmle.util.data.Either; import com.semmle.util.data.Pair; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; /** * An extension of the standard jcorn parser with support for Mozilla-specific language extension * (most of JavaScript 1.8.5 and E4X) and JScript language extensions. */ public class CustomParser extends FlowParser { public CustomParser(Options options, String input, int startPos) { super(options, input, startPos); // recognise `const` as a keyword, irrespective of options.ecmaVersion this.keywords.add("const"); } // add parsing of guarded `catch` clauses @Override protected TryStatement parseTryStatement(Position startLoc) { if (!options.mozExtensions()) return super.parseTryStatement(startLoc); this.next(); BlockStatement block = this.parseBlock(false); CatchClause handler = null; List<CatchClause> guardedHandlers = new ArrayList<CatchClause>(); while (this.type == TokenType._catch) { Position catchStartLoc = this.startLoc; CatchClause katch = this.parseCatchClause(catchStartLoc); if (handler != null) this.raise(catchStartLoc, "Catch after unconditional catch"); if (katch.getGuard() != null) guardedHandlers.add(katch); else handler = katch; } BlockStatement finalizer = this.eat(TokenType._finally) ? this.parseBlock(false) : null; if (handler == null && finalizer == null && guardedHandlers.isEmpty()) this.raise(startLoc, "Missing catch or finally clause"); return this.finishNode( new TryStatement(new SourceLocation(startLoc), block, handler, guardedHandlers, finalizer)); } /* * Support for guarded `catch` clauses and omitted catch bindings. */ @Override protected CatchClause parseCatchClause(Position startLoc) { if (!options.mozExtensions()) return super.parseCatchClause(startLoc); this.next(); Expression param = null; Expression guard = null; if (this.eat(TokenType.parenL)) { param = this.parseBindingAtom(); this.checkLVal(param, true, null); if (this.eat(TokenType._if)) guard = this.parseExpression(false, null); this.expect(TokenType.parenR); } else if (!options.esnext()) { this.unexpected(); } BlockStatement catchBody = this.parseBlock(false); return this.finishNode( new CatchClause(new SourceLocation(startLoc), (IPattern) param, guard, catchBody)); } // add parsing of `let` statements and expressions @Override protected boolean mayFollowLet(int c) { return options.mozExtensions() && c == '(' || super.mayFollowLet(c); } @Override protected Statement parseVarStatement(Position startLoc, String kind) { if (!options.mozExtensions()) return super.parseVarStatement(startLoc, kind); this.next(); if ("let".equals(kind) && this.eat(TokenType.parenL)) { // this is a `let` statement or expression return (LetStatement) this.parseLetExpression(startLoc, true); } VariableDeclaration node = this.parseVar(startLoc, false, kind); this.semicolon(); return this.finishNode(node); } @Override protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; if (options.mozExtensions() && this.isContextual("let")) { this.next(); this.expect(TokenType.parenL); return (Expression) this.parseLetExpression(startLoc, false); } else if (options.mozExtensions() && this.type == TokenType.bracketL) { this.next(); // check whether this is array comprehension or regular array if (this.type == TokenType._for) { ComprehensionExpression c = this.parseComprehension(startLoc, false, null); this.expect(TokenType.bracketR); return this.finishNode(c); } List<Expression> elements; if (this.type == TokenType.comma || this.type == TokenType.bracketR || this.type == TokenType.ellipsis) { elements = this.parseExprList(TokenType.bracketR, true, true, refDestructuringErrors); } else { Expression firstExpr = this.parseMaybeAssign(false, refDestructuringErrors, null); // check whether this is a postfix array comprehension if (this.type == TokenType._for || this.type == TokenType._if) { ComprehensionExpression c = this.parseComprehension(startLoc, false, firstExpr); this.expect(TokenType.bracketR); return this.finishNode(c); } else { this.eat(TokenType.comma); elements = new ArrayList<Expression>(); elements.add(firstExpr); elements.addAll( this.parseExprList(TokenType.bracketR, true, true, refDestructuringErrors)); } } return this.finishNode(new ArrayExpression(new SourceLocation(startLoc), elements)); } else if (options.v8Extensions() && this.type == TokenType.modulo) { // parse V8 native this.next(); Identifier name = this.parseIdent(true); this.expect(TokenType.parenL); List<Expression> args = this.parseExprList(TokenType.parenR, false, false, null); CallExpression node = new CallExpression( new SourceLocation(startLoc), name, new ArrayList<>(), args, false, false); return this.finishNode(node); } else if (options.e4x() && this.type == at) { // this could be either a decorator or an attribute selector; we first // try parsing it as a decorator, and then convert it to an attribute selector // if the next token turns out not to be `class` List<Decorator> decorators = parseDecorators(); Expression attr = null; if (decorators.size() > 1 || this.type == TokenType._class || ((attr = decoratorToAttributeSelector(decorators.get(0))) == null)) { ClassExpression ce = (ClassExpression) this.parseClass(startLoc, false); ce.addDecorators(decorators); return ce; } return attr; } else { return super.parseExprAtom(refDestructuringErrors); } } protected Node parseLetExpression(Position startLoc, boolean maybeStatement) { // this method assumes that the keyword `let` and the opening parenthesis have already been // consumed VariableDeclaration decl = this.parseVar(startLoc, false, "let"); this.expect(TokenType.parenR); if (this.type == TokenType.braceL) { if (!maybeStatement) { // must be the start of an object literal Expression body = this.parseObj(false, null); return this.finishNode( new LetExpression(new SourceLocation(startLoc), decl.getDeclarations(), body)); } BlockStatement body = this.parseBlock(false); return this.finishNode( new LetStatement(new SourceLocation(startLoc), decl.getDeclarations(), body)); } else if (maybeStatement) { Position pos = startLoc; Statement body = this.parseStatement(true, false); if (body == null) this.unexpected(pos); return this.finishNode( new LetStatement(new SourceLocation(startLoc), decl.getDeclarations(), body)); } else { Expression body = this.parseExpression(false, null); return this.finishNode( new LetExpression(new SourceLocation(startLoc), decl.getDeclarations(), body)); } } // add parsing of expression closures and JScript methods @Override protected INode parseFunction( Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean isAsync) { if (isFunctionSent(isStatement)) return super.parseFunction(startLoc, isStatement, allowExpressionBody, isAsync); allowExpressionBody = allowExpressionBody || options.mozExtensions(); boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; Pair<Boolean, Identifier> p = parseFunctionName(isStatement, isAsync); boolean generator = p.fst(); Identifier id = p.snd(), iface = null; if (options.jscript()) { if (isStatement && this.eatDoubleColon()) { iface = p.snd(); id = this.parseIdent(false); } } IFunction result = parseFunctionRest( startLoc, isStatement, allowExpressionBody, oldInGen, oldInAsync, oldYieldPos, oldAwaitPos, generator, id); if (iface != null) { /* Translate JScript double colon method declarations into normal method definitions: * * function A::f(...) { ... } * * becomes * * A.f = function f(...) { ... }; */ SourceLocation memloc = new SourceLocation( iface.getName() + "::" + id.getName(), iface.getLoc().getStart(), id.getLoc().getEnd()); MemberExpression mem = new MemberExpression( memloc, iface, new Identifier(id.getLoc(), id.getName()), false, false, false); AssignmentExpression assgn = new AssignmentExpression( result.getLoc(), "=", mem, ((FunctionDeclaration) result).asFunctionExpression()); return new ExpressionStatement(result.getLoc(), assgn); } return result; } private boolean eatDoubleColon() { if (this.eat(TokenType.colon)) { this.expect(TokenType.colon); return true; } else { return this.eat(doubleColon); } } // accept `yield` in non-generator functions @Override protected Expression parseMaybeAssign( boolean noIn, DestructuringErrors refDestructuringErrors, AfterLeftParse afterLeftParse) { if (options.mozExtensions() && isContextual("yield")) { if (!this.inFunction) this.raise(this.startLoc, "Yield not in function"); return this.parseYield(); } return super.parseMaybeAssign(noIn, refDestructuringErrors, afterLeftParse); } // add parsing of comprehensions protected ComprehensionExpression parseComprehension( Position startLoc, boolean isGenerator, Expression body) { List<ComprehensionBlock> blocks = new ArrayList<ComprehensionBlock>(); while (this.type == TokenType._for) { SourceLocation blockStart = new SourceLocation(this.startLoc); boolean of = false; this.next(); if (this.eatContextual("each")) of = true; this.expect(TokenType.parenL); Expression left = this.parseBindingAtom(); this.checkLVal(left, true, null); if (this.eatContextual("of")) { of = true; } else { this.expect(TokenType._in); } Expression right = this.parseExpression(false, null); this.expect(TokenType.parenR); blocks.add(this.finishNode(new ComprehensionBlock(blockStart, (IPattern) left, right, of))); } Expression filter = this.eat(TokenType._if) ? this.parseParenExpression() : null; if (body == null) body = this.parseExpression(false, null); return new ComprehensionExpression( new SourceLocation(startLoc), body, blocks, filter, isGenerator); } @Override protected Expression parseParenAndDistinguishExpression(boolean canBeArrow) { if (options.mozExtensions()) { // check whether next token is `for`, suggesting a generator comprehension Position startLoc = this.startLoc; Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); if (m.find(this.pos)) { if (m.end() + 3 < input.length() && "for".equals(input.substring(m.end(), m.end() + 3)) && !Identifiers.isIdentifierChar(input.charAt(m.end() + 3), true)) { next(); ComprehensionExpression c = parseComprehension(startLoc, true, null); this.expect(TokenType.parenR); return this.finishNode(c); } } } Expression res = super.parseParenAndDistinguishExpression(canBeArrow); if (res instanceof ParenthesizedExpression) { ParenthesizedExpression p = (ParenthesizedExpression) res; if (p.getExpression() instanceof ComprehensionExpression) { ComprehensionExpression c = (ComprehensionExpression) p.getExpression(); if (c.isGenerator()) return new ComprehensionExpression( p.getLoc(), c.getBody(), c.getBlocks(), c.getFilter(), c.isGenerator()); } } return res; } @Override protected boolean parseParenthesisedExpression( DestructuringErrors refDestructuringErrors, boolean allowTrailingComma, ParenthesisedExpressions parenExprs, boolean first) { boolean cont = super.parseParenthesisedExpression( refDestructuringErrors, allowTrailingComma, parenExprs, first); if (options.mozExtensions() && parenExprs.exprList.size() == 1 && this.type == TokenType._for) { Expression body = parenExprs.exprList.remove(0); ComprehensionExpression c = parseComprehension(body.getLoc().getStart(), true, body); parenExprs.exprList.add(this.finishNode(c)); return false; } return cont; } // add parsing of for-each loops @Override protected Statement parseForStatement(Position startLoc) { boolean each = false; if (options.mozExtensions() && this.isContextual("each")) { this.next(); each = true; } Position afterEach = this.startLoc; Statement result = super.parseForStatement(startLoc); if (each) { if (result instanceof ForInStatement) { ForInStatement fis = (ForInStatement) result; result = new ForInStatement(fis.getLoc(), fis.getLeft(), fis.getRight(), fis.getBody(), true); } else { raise(afterEach, "Bad for-each statement."); } } return result; } // add parsing of Rhino/Nashorn-style `new` expressions with last argument after `)` @Override protected Expression parseNew() { Expression res = super.parseNew(); if (res instanceof NewExpression && options.mozExtensions() && !canInsertSemicolon() && this.type == TokenType.braceL) { ((NewExpression) res).getArguments().add(this.parseObj(false, null)); res = this.finishNode(res); } return res; } /* * E4X * * PrimaryExpression : * PropertyIdentifier * XMLInitialiser * XMLListInitialiser * * PropertyIdentifier : * AttributeIdentifier * QualifiedIdentifier * WildcardIdent * * AttributeIdentifier : * @ PropertySelector * @ QualifiedIdentifier * @ [ Expression ] * * PropertySelector : * Identifier * WildcardIdentifier * * QualifiedIdentifier : * PropertySelector :: PropertySelector * PropertySelector :: [ Expression ] * * WildcardIdentifier : * * * * MemberExpression : * MemberExpression . PropertyIdentifier * MemberExpression .. Identifier * MemberExpression .. PropertyIdentifier * MemberExpression . ( Expression ) * * DefaultXMLNamespaceStatement : * default xml namespace = Expression */ protected TokenType doubleDot = new TokenType(new Properties(":").beforeExpr()); @Override protected Token getTokenFromCode(int code) { if (options.e4x() && code == '.' && charAt(this.pos + 1) == '.' && charAt(this.pos + 2) != '.') { this.pos += 2; return this.finishToken(doubleDot); } return super.getTokenFromCode(code); } // add parsing of E4X property, attribute and descendant accesses, as well as filter expressions @Override protected Pair<Expression, Boolean> parseSubscript( Expression base, Position startLoc, boolean noCalls) { if (options.e4x() && this.eat(TokenType.dot)) { SourceLocation start = new SourceLocation(startLoc); if (this.eat(TokenType.parenL)) { Expression filter = parseExpression(false, null); this.expect(TokenType.parenR); return Pair.make(this.finishNode(new XMLFilterExpression(start, base, filter)), true); } Expression property = this.parsePropertyIdentifierOrIdentifier(); MemberExpression node = new MemberExpression( start, base, property, false, false, Chainable.isOnOptionalChain(false, base)); return Pair.make(this.finishNode(node), true); } else if (this.eat(doubleDot)) { SourceLocation start = new SourceLocation(startLoc); Expression property = this.parsePropertyIdentifierOrIdentifier(); return Pair.make(this.finishNode(new XMLDotDotExpression(start, base, property)), true); } return super.parseSubscript(base, startLoc, noCalls); } /** * Parse a an attribute identifier, a wildcard identifier, a qualified identifier, or a plain * identifier. */ protected Expression parsePropertyIdentifierOrIdentifier() { Position start = this.startLoc; if (this.eat(at)) { // attribute identifier return parseAttributeIdentifier(new SourceLocation(start)); } else { return parsePropertySelector(new SourceLocation(startLoc)); } } /** Parse a property selector, that is, either a wildcard identifier or a plain identifier. */ protected Expression parsePropertySelector(SourceLocation start) { Expression res; if (this.eat(TokenType.star)) { // wildcard identifier res = this.finishNode(new XMLAnyName(start)); } else { res = this.parseIdent(true); } return res; } /** * Parse an attribute identifier, either computed ({@code [ Expr ]}) or a possibly qualified * identifier. */ protected Expression parseAttributeIdentifier(SourceLocation start) { if (this.eat(TokenType.bracketL)) { Expression idx = parseExpression(false, null); this.expect(TokenType.bracketR); return this.finishNode(new XMLAttributeSelector(start, idx, true)); } else { return this.finishNode( new XMLAttributeSelector( start, parsePropertySelector(new SourceLocation(startLoc)), false)); } } @Override protected Expression parseDecoratorBody() { SourceLocation start = new SourceLocation(startLoc); if (options.e4x() && this.eat(TokenType.bracketL)) { // this must be an attribute selector, so only allow a single expression // followed by a right bracket, which will later be converted by // `decoratorToAttributeSelector` below List<Expression> elements = new ArrayList<>(); elements.add(parseExpression(false, null)); this.expect(TokenType.bracketR); return this.finishNode(new ArrayExpression(start, elements)); } return super.parseDecoratorBody(); } /** * Convert a decorator that resulted from mis-parsing an attribute selector into an attribute * selector. */ protected XMLAttributeSelector decoratorToAttributeSelector(Decorator d) { Expression e = d.getExpression(); if (e instanceof ArrayExpression) { ArrayExpression ae = (ArrayExpression) e; if (ae.getElements().size() == 1) return new XMLAttributeSelector(d.getLoc(), ae.getElements().get(0), true); } else if (e instanceof Identifier) { return new XMLAttributeSelector(d.getLoc(), e, false); } return null; } @Override protected Token readToken(int code) { // skip XML processing instructions (which are allowed in E4X, but not in JSX); // there is a lexical ambiguity between an XML processing instruction starting a // chunk of E4X content and a Flow type annotation (both can start with `<?`) // hence if we can't find the closing `?>` of a putative XML processing instruction // we backtrack and try lexing as something else // to avoid frequent backtracking, we only consider `<?xml ...?>` processing instructions; // while other processing instructions are technically possible, they are unlikely in practice if (this.options.e4x()) { while (code == '<') { if (inputSubstring(this.pos + 1, this.pos + 5).equals("?xml")) { int oldPos = this.pos; this.pos += 5; if (!jsx_readUntil("?>")) { // didn't find a closing `?>`, so backtrack this.pos = oldPos; break; } } else { break; } this.skipSpace(); code = this.fullCharCodeAtPos(); } } return super.readToken(code); } @Override protected Either<Integer, Token> jsx_readChunk(StringBuilder out, int chunkStart, int ch) { // skip XML comments, processing instructions and CDATA (which are allowed in E4X, // but not in JSX) // unlike in `readToken` above, we know that we're inside JSX/E4X code, so there is // no ambiguity with Flow type annotations if (this.options.e4x() && ch == '<') { if (inputSubstring(this.pos + 1, this.pos + 4).equals("!--")) { out.append(inputSubstring(chunkStart, this.pos)); this.pos += 4; jsx_readUntil("-->"); return Either.left(this.pos); } else if (charAt(this.pos + 1) == '?') { out.append(inputSubstring(chunkStart, this.pos)); this.pos += 2; jsx_readUntil("?>"); return Either.left(this.pos); } else if (inputSubstring(this.pos + 1, this.pos + 9).equals("![CDATA[")) { out.append(inputSubstring(chunkStart, this.pos)); this.pos += 9; int cdataStart = this.pos; jsx_readUntil("]]>"); out.append(inputSubstring(cdataStart, this.pos - 3)); return Either.left(this.pos); } } return super.jsx_readChunk(out, chunkStart, ch); } private boolean jsx_readUntil(String terminator) { char fst = terminator.charAt(0); while (this.pos + terminator.length() <= this.input.length()) { if (charAt(this.pos) == fst && inputSubstring(this.pos, this.pos + terminator.length()).equals(terminator)) { this.pos += terminator.length(); return true; } ++this.pos; } return false; } }
23,550
36.323296
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/flow/FlowParser.java
package com.semmle.jcorn.flow; import com.semmle.jcorn.ESNextParser; import com.semmle.jcorn.Identifiers; import com.semmle.jcorn.Options; import com.semmle.jcorn.SyntaxError; import com.semmle.jcorn.TokenType; import com.semmle.jcorn.TokenType.Properties; import com.semmle.jcorn.Whitespace; import com.semmle.js.ast.BinaryExpression; import com.semmle.js.ast.ExportDeclaration; import com.semmle.js.ast.ExportSpecifier; import com.semmle.js.ast.Expression; import com.semmle.js.ast.ExpressionStatement; import com.semmle.js.ast.FieldDefinition; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.ImportSpecifier; import com.semmle.js.ast.Literal; import com.semmle.js.ast.MethodDefinition; import com.semmle.js.ast.Node; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Token; import com.semmle.js.ast.UnaryExpression; import com.semmle.util.data.Pair; import com.semmle.util.exception.Exceptions; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.function.Function; import java.util.regex.Matcher; /** * Java port of the <a href="https://github.com/babel/babylon">Babylon</a> <a * href="https://github.com/babel/babylon/blob/master/src/plugins/flow.js">Flow plugin</a>. All Flow * annotations are simply discarded after parsing. */ public class FlowParser extends ESNextParser { private boolean inType = false, noAnonFunctionType = false; private static final TokenType braceBarL = new TokenType(new Properties("{|").beforeExpr().startsExpr()); private static final TokenType braceBarR = new TokenType(new Properties("|}")); public FlowParser(Options options, String input, int startPos) { super(options, input, startPos); } @Override protected Token getTokenFromCode(int code) { if (code == '{' && charAt(this.pos + 1) == '|') { this.pos += 2; return this.finishToken(braceBarL); } else if (code == '|' && charAt(this.pos + 1) == '}') { this.pos += 2; return this.finishToken(braceBarR); } return super.getTokenFromCode(code); } /** * Utility class for saving the parser state so we can later either restore it by calling method * {@link #reset()}, or commit to the new state by calling method {@link #commit()}. */ private class State { private boolean exprAllowed; private int pos, lineStart, curLine, start, end, potentialArrowAt; private TokenType type; private Object value; private Position startLoc, endLoc, lastTokEndLoc, lastTokStartLoc; private int lastTokStart, lastTokEnd; private Stack<TokContext> context; private Function<Token, Void> onToken; private boolean inType, noAnonFunctionType; private List<Token> tokens = new ArrayList<Token>(); private Function<SyntaxError, ?> onRecoverableError; private List<SyntaxError> errors = new ArrayList<SyntaxError>(); private State() { this.exprAllowed = FlowParser.this.exprAllowed; this.pos = FlowParser.this.pos; this.lineStart = FlowParser.this.lineStart; this.curLine = FlowParser.this.curLine; this.start = FlowParser.this.start; this.end = FlowParser.this.end; this.potentialArrowAt = FlowParser.this.potentialArrowAt; this.type = FlowParser.this.type; this.value = FlowParser.this.value; this.startLoc = FlowParser.this.startLoc; this.endLoc = FlowParser.this.endLoc; this.lastTokEndLoc = FlowParser.this.lastTokEndLoc; this.lastTokStartLoc = FlowParser.this.lastTokStartLoc; this.lastTokStart = FlowParser.this.lastTokStart; this.lastTokEnd = FlowParser.this.lastTokEnd; this.context = new Stack<TokContext>(); this.context.addAll(FlowParser.this.context); this.inType = FlowParser.this.inType; this.noAnonFunctionType = FlowParser.this.noAnonFunctionType; // buffer tokens while we are in speculative mode this.onToken = options.onToken(); options.onToken( (tk) -> { tokens.add(tk); return null; }); // buffer recoverable errors while we are in speculative mode this.onRecoverableError = options.onRecoverableError(); options.onRecoverableError( (err) -> { errors.add(err); return null; }); } private void reset() { FlowParser.this.exprAllowed = this.exprAllowed; FlowParser.this.pos = this.pos; FlowParser.this.lineStart = this.lineStart; FlowParser.this.curLine = this.curLine; FlowParser.this.start = this.start; FlowParser.this.end = this.end; FlowParser.this.potentialArrowAt = this.potentialArrowAt; FlowParser.this.type = this.type; FlowParser.this.value = this.value; FlowParser.this.startLoc = this.startLoc; FlowParser.this.endLoc = this.endLoc; FlowParser.this.lastTokEndLoc = this.lastTokEndLoc; FlowParser.this.lastTokStartLoc = this.lastTokStartLoc; FlowParser.this.lastTokStart = this.lastTokStart; FlowParser.this.lastTokEnd = this.lastTokEnd; FlowParser.this.context = this.context; options.onToken(this.onToken); FlowParser.this.inType = this.inType; FlowParser.this.noAnonFunctionType = this.noAnonFunctionType; options.onRecoverableError(this.onRecoverableError); } private void commit() { // commit buffered tokens options.onToken(this.onToken); if (this.onToken != null) for (Token tk : tokens) this.onToken.apply(tk); // commit buffered syntax errors options.onRecoverableError(this.onRecoverableError); if (this.onRecoverableError != null) for (SyntaxError err : errors) this.onRecoverableError.apply(err); } } private boolean isRelational(String op) { return this.type == TokenType.relational && op.equals(value); } private void expectRelational(String op) { if (isRelational(op)) next(); else unexpected(); } private void flowParseTypeInitialiser(TokenType tok, boolean allowLeadingPipeOrAnd) { boolean oldInType = inType; inType = true; this.expect(tok == null ? TokenType.colon : tok); if (this.type == TokenType.modulo) { // an annotation like '%checks' without a preceeding type inType = oldInType; return; } if (allowLeadingPipeOrAnd) { if (this.type == TokenType.bitwiseAND || this.type == TokenType.bitwiseOR) { this.next(); } } this.flowParseType(); inType = oldInType; } private void flowParseDeclareClass(Position start) { this.next(); this.flowParseInterfaceish(start, true); } private void flowParseDeclareFunction(Position start) { this.next(); Identifier id = this.parseIdent(false); if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } this.expect(TokenType.parenL); this.flowParseFunctionTypeParams(); this.expect(TokenType.parenR); this.flowParseTypeInitialiser(null, false); this.finishNode(id); this.semicolon(); } private void flowParseDeclare(Position start) { if (this.type == TokenType._class) { this.flowParseDeclareClass(start); } else if (this.type == TokenType._function) { this.flowParseDeclareFunction(start); } else if (this.type == TokenType._var) { this.flowParseDeclareVariable(start); } else if (this.isContextual("module")) { if (".".equals(lookahead(1))) this.flowParseDeclareModuleExports(); else this.flowParseDeclareModule(start); } else if (this.isContextual("type")) { this.flowParseDeclareTypeAlias(start); } else if (this.isContextual("opaque")) { this.flowParseDeclareOpaqueType(start); } else if (this.isContextual("interface")) { this.flowParseDeclareInterface(start); } else if (this.type == TokenType._export) { this.flowParseDeclareExportDeclaration(start); } else { this.unexpected(); } } private void flowParseDeclareVariable(Position start) { this.next(); this.flowParseTypeAnnotatableIdentifier(false, false); this.semicolon(); } private void flowParseDeclareModule(Position start) { this.next(); if (this.type == TokenType.string) { this.parseExprAtom(null); } else { this.parseIdent(false); } this.expect(TokenType.braceL); while (this.type != TokenType.braceR) { Position stmtStart = startLoc; if (this.eatContextual("declare")) { this.flowParseDeclare(stmtStart); } else if (this.eat(TokenType._import)) { if (peekAtSpecialFlowImportSpecifier() == null) { this.raise( stmtStart, "Imports within a `declare module` body must always be `import type` or `import typeof`."); } this.parseImportRest(new SourceLocation(stmtStart)); } else { unexpected(); } } this.expect(TokenType.braceR); } private void flowParseDeclareModuleExports() { this.expectContextual("module"); this.expect(TokenType.dot); this.expectContextual("exports"); this.flowParseTypeAnnotation(); this.semicolon(); } private void flowParseDeclareTypeAlias(Position start) { this.next(); this.flowParseTypeAlias(start); } private void flowParseDeclareOpaqueType(Position start) { this.next(); this.flowParseOpaqueType(start, true); } private void flowParseDeclareInterface(Position start) { this.next(); this.flowParseInterfaceish(start, false); } private boolean match(TokenType tt) { return this.type == tt; } private void flowParseDeclareExportDeclaration(Position start) { this.expect(TokenType._export); if (this.eat(TokenType._default)) { if (this.match(TokenType._function) || this.match(TokenType._class)) { // declare export default class ... // declare export default function ... this.flowParseDeclare(this.startLoc); } else { // declare export default [type]; this.flowParseType(); this.semicolon(); } return; } else { if (this.match(TokenType._const) || this.isContextual("let")) { this.unexpected(); } if (this.match(TokenType._var) || // declare export var ... this.match(TokenType._function) || // declare export function ... this.match(TokenType._class) || // declare export class ... this.isContextual("opaque") // declare export opaque .. ) { this.flowParseDeclare(this.startLoc); return; } else if (this.match(TokenType.star) || // declare export * from '' this.match(TokenType.braceL) || // declare export {} ... this.isContextual("interface") || // declare export interface ... this.isContextual("type") || // declare export type ... this.isContextual("opaque") // declare export opaque type ... ) { this.parseExportRest(new SourceLocation(start), new LinkedHashSet<>()); return; } } this.unexpected(); } // Interfaces private void flowParseInterfaceish(Position start, boolean allowStatic) { this.parseIdent(false); if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } if (this.eat(TokenType._extends)) { do { this.flowParseInterfaceExtends(); } while (this.eat(TokenType.comma)); } if (this.isContextual("mixins")) { this.next(); do { this.flowParseInterfaceExtends(); } while (this.eat(TokenType.comma)); } this.flowParseObjectType(allowStatic, false, false); } private void flowParseInterfaceExtends() { this.flowParseQualifiedTypeIdentifier(null); if (this.isRelational("<")) { this.flowParseTypeParameterInstantiation(); } } private void flowParseQualifiedTypeIdentifier(Identifier id) { if (id == null) this.parseIdent(false); while (this.eat(TokenType.dot)) this.parseIdent(false); } private void flowParseInterface(Position start) { this.flowParseInterfaceish(start, false); } // Type aliases private void flowParseTypeAlias(Position start) { this.parseIdent(false); if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } this.flowParseTypeInitialiser(TokenType.eq, /*allowLeadingPipeOrAnd*/ true); this.semicolon(); } private void flowParseOpaqueType(Position start, boolean declare) { this.expectContextual("type"); this.parseIdent(false); if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } // Parse the supertype if (this.type == TokenType.colon) { this.flowParseTypeInitialiser(TokenType.colon, false); } if (!declare) { this.flowParseTypeInitialiser(TokenType.eq, false); } this.semicolon(); } // Type annotations private void flowParseTypeParameter() { this.eat(TokenType.plusMin); this.flowParseTypeAnnotatableIdentifier(false, false); if (this.eat(TokenType.eq)) { this.flowParseType(); } } private void flowParseTypeParameterDeclaration() { if (this.isRelational("<") || this.type == jsxTagStart) { this.next(); } else { this.unexpected(); } do { this.flowParseTypeParameter(); if (!this.isRelational(">")) { this.expect(TokenType.comma); } } while (!this.isRelational(">")); this.expectRelational(">"); } private void flowParseTypeParameterInstantiation() { boolean oldInType = inType; inType = true; this.expectRelational("<"); while (!this.isRelational(">")) { this.flowParseType(); if (!this.isRelational(">")) { this.expect(TokenType.comma); } } this.expectRelational(">"); inType = oldInType; } private void flowParseObjectPropertyKey() { if (this.type == TokenType.num || this.type == TokenType.string) { this.parseExprAtom(null); } else if ("@@iterator".equals(inputSubstring(start, start + 10))) { // allow `@@iterator` as property name; this doesn't appear to be standard Flow syntax, // but is used a few times in react-native this.expect(at); this.expect(at); this.expect(TokenType.name); } else { this.parseIdent(true); } } private void flowParseObjectTypeIndexer(Position start, boolean isStatic) { this.expect(TokenType.bracketL); if (":".equals(lookahead(1))) { this.flowParseObjectPropertyKey(); this.flowParseTypeInitialiser(null, false); } else { this.flowParseType(); } this.expect(TokenType.bracketR); this.flowParseTypeInitialiser(null, false); this.flowObjectTypeSemicolon(); } private void flowParseObjectTypeMethodish(Position start) { if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } this.expect(TokenType.parenL); while (this.type != TokenType.ellipsis && this.type != TokenType.parenR) { this.flowParseFunctionTypeParam(); if (this.type != TokenType.parenR) { this.expect(TokenType.comma); } } if (this.eat(TokenType.ellipsis)) { this.flowParseFunctionTypeParam(); } this.expect(TokenType.parenR); this.flowParseTypeInitialiser(null, false); } private void flowParseObjectTypeMethod(Position start, boolean isStatic) { this.flowParseObjectTypeMethodish(start); this.flowObjectTypeSemicolon(); } private void flowParseObjectTypeCallProperty(Position start, boolean isStatic) { this.flowParseObjectTypeMethodish(start); this.flowObjectTypeSemicolon(); } private void flowParseObjectType(boolean allowStatic, boolean allowExact, boolean allowSpread) { boolean isStatic = false; TokenType endDelim; if (allowExact && this.eat(braceBarL)) { endDelim = braceBarR; } else { this.expect(TokenType.braceL); endDelim = TokenType.braceR; } while (this.type != endDelim) { Position innerStart = startLoc; if (allowStatic && this.isContextual("static")) { this.next(); isStatic = true; } // variance annotation this.eat(TokenType.plusMin); if (this.type == TokenType.bracketL) { this.flowParseObjectTypeIndexer(innerStart, isStatic); } else if (this.type == TokenType.parenL || this.isRelational("<")) { this.flowParseObjectTypeCallProperty(innerStart, allowStatic); } else { if (isStatic && this.type == TokenType.colon) { this.parseIdent(false); } else if (allowSpread && this.eat(TokenType.ellipsis)) { boolean hasType = this.type != endDelim && this.type != TokenType.comma && this.type != TokenType.semi; if (hasType) { flowParseType(); } flowObjectTypeSemicolon(); continue; } else { this.flowParseObjectPropertyKey(); } if (this.isRelational("<") || this.type == TokenType.parenL) { // This is a method property this.flowParseObjectTypeMethod(innerStart, isStatic); } else { if (this.eat(TokenType.question)) { // do something } this.flowParseTypeInitialiser(null, false); this.flowObjectTypeSemicolon(); } } } this.expect(endDelim); } private void flowObjectTypeSemicolon() { if (!this.eat(TokenType.semi) && !this.eat(TokenType.comma) && this.type != TokenType.braceR && this.type != braceBarR) { this.unexpected(); } } private void flowParseGenericType(Position start) { while (this.eat(TokenType.dot)) { this.parseIdent(false); } if (this.isRelational("<")) { this.flowParseTypeParameterInstantiation(); } } private void flowParseTypeofType() { this.expect(TokenType._typeof); this.flowParsePrimaryType(); } private void flowParseTupleType() { this.expect(TokenType.bracketL); // We allow trailing commas while (this.pos < this.input.length() && this.type != TokenType.bracketR) { this.flowParseType(); if (this.type == TokenType.bracketR) break; this.expect(TokenType.comma); } this.expect(TokenType.bracketR); } private void flowParseFunctionTypeParam() { String lh = lookahead(1); if (":".equals(lh) || "?".equals(lh)) { this.parseIdent(false); this.eat(TokenType.question); this.flowParseTypeInitialiser(null, false); } else { flowParseType(); } } private void flowParseFunctionTypeParams() { while (this.type != TokenType.parenR && this.type != TokenType.ellipsis) { this.flowParseFunctionTypeParam(); if (this.type != TokenType.parenR) { this.expect(TokenType.comma); } } if (this.eat(TokenType.ellipsis)) { this.flowParseFunctionTypeParam(); } } private void flowIdentToTypeAnnotation(Position start, Identifier id) { switch (id.getName()) { case "any": return; case "void": return; case "bool": case "boolean": return; case "mixed": return; case "number": return; case "string": return; default: this.flowParseGenericType(start); } } private String lookahead(int n) { Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); if (m.find(this.pos)) return inputSubstring(m.end(), m.end() + n); return ""; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. private void flowParsePrimaryType() { Position start = startLoc; boolean isGroupedType = false; boolean oldNoAnonFunctionType = noAnonFunctionType; if (this.type == TokenType.name) { this.flowIdentToTypeAnnotation(start, this.parseIdent(false)); return; } else if (this.type == TokenType._void) { this.next(); return; } else if (this.type == TokenType.braceL) { this.flowParseObjectType(false, false, true); return; } else if (this.type == braceBarL) { this.flowParseObjectType(false, true, true); return; } else if (this.type == TokenType.bracketL) { this.flowParseTupleType(); return; } else if (this.type == TokenType.relational) { if ("<".equals(this.value)) { this.flowParseTypeParameterDeclaration(); this.expect(TokenType.parenL); this.flowParseFunctionTypeParams(); this.expect(TokenType.parenR); this.expect(TokenType.arrow); this.flowParseType(); return; } else { this.unexpected(); } } else if (this.type == TokenType.parenL) { this.next(); // Check to see if this is actually a grouped type if (this.type != TokenType.parenR && this.type != TokenType.ellipsis) { if (this.type == TokenType.name) { String lh = lookahead(1); if ("?".equals(lh) || ":".equals(lh)) { isGroupedType = false; } else { isGroupedType = true; } } else { isGroupedType = true; } } if (isGroupedType) { this.noAnonFunctionType = false; this.flowParseType(); this.noAnonFunctionType = oldNoAnonFunctionType; if (noAnonFunctionType || !(this.type == TokenType.comma || (this.type == TokenType.parenR && "=>".equals(lookahead(2))))) { this.expect(TokenType.parenR); return; } else { // Eat a comma if there is one this.eat(TokenType.comma); } } this.flowParseFunctionTypeParams(); this.expect(TokenType.parenR); this.expect(TokenType.arrow); this.flowParseType(); return; } else if (this.type == TokenType.string) { this.next(); return; } else if (this.type == TokenType._true || this.type == TokenType._false) { this.next(); return; } else if (this.type == TokenType.plusMin || this.type == TokenType.num) { if ("-".equals(this.value)) { this.next(); if (this.type != TokenType.num) this.unexpected(); this.next(); return; } this.next(); return; } else if (this.type == TokenType._null) { this.next(); return; } else if (this.type == TokenType._this) { this.next(); return; } else if (this.type == TokenType.star) { this.next(); return; } else if ("typeof".equals(this.type.keyword)) { this.flowParseTypeofType(); return; } this.unexpected(); } private void flowParsePostfixType() { this.flowParsePrimaryType(); while (this.type == TokenType.bracketL) { this.expect(TokenType.bracketL); this.expect(TokenType.bracketR); } } private void flowParsePrefixType() { if (this.eat(TokenType.question)) { this.flowParsePrefixType(); } else { this.flowParsePostfixType(); } } private void flowParseIntersectionType() { this.eat(TokenType.bitwiseAND); this.flowParseAnonFunctionWithoutParens(); while (this.eat(TokenType.bitwiseAND)) { this.flowParseAnonFunctionWithoutParens(); } } private void flowParseAnonFunctionWithoutParens() { this.flowParsePrefixType(); if (!noAnonFunctionType && eat(TokenType.arrow)) flowParseType(); } private void flowParseUnionType() { this.eat(TokenType.bitwiseOR); this.flowParseIntersectionType(); while (this.eat(TokenType.bitwiseOR)) { this.flowParseIntersectionType(); } } private void flowParseType() { boolean oldInType = inType; inType = true; this.flowParseUnionType(); inType = oldInType; } private void flowParseTypeAnnotation() { this.flowParseTypeInitialiser(null, false); } private void flowParseTypeAnnotatableIdentifier( boolean requireTypeAnnotation, boolean canBeOptionalParam) { this.parseIdent(false); if (canBeOptionalParam && this.eat(TokenType.question)) { this.expect(TokenType.question); } if (requireTypeAnnotation || this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } } /** Should Flow syntax be allowed? */ private boolean flow() { return options.esnext(); } @Override protected Node parseFunctionBody( Identifier id, List<Expression> params, boolean isArrowFunction) { // plain function return types: `function name(): string {}` if (flow() && this.type == TokenType.colon) { // if allowExpression is true then we're parsing an arrow function and if // there's a return type then it's been handled elsewhere this.flowParseTypeAnnotation(); this.flowParseChecksAnnotation(); } return super.parseFunctionBody(id, params, isArrowFunction); } private void flowParseChecksAnnotation() { // predicate functions with the special '%checks' annotation if (this.type == TokenType.modulo && lookaheadIsIdent("checks", true)) { this.next(); this.next(); } } // interfaces @Override protected Statement parseStatement(boolean declaration, boolean topLevel, Set<String> exports) { // strict mode handling of `interface` since it's a reserved word if (flow() && declaration && this.strict && this.type == TokenType.name && "interface".equals(this.value)) { Position start = startLoc; this.next(); this.flowParseInterface(start); return null; } else { return super.parseStatement(declaration, topLevel, exports); } }; // declares, interfaces and type aliases @Override protected ExpressionStatement parseExpressionStatement( boolean declaration, Position start, Expression expr) { if (flow() && declaration && expr instanceof Identifier) { String name = ((Identifier) expr).getName(); if ("declare".equals(name)) { if (this.type == TokenType._class || this.type == TokenType.name || this.type == TokenType._function || this.type == TokenType._var || this.type == TokenType._export) { this.flowParseDeclare(start); return null; } } else if (this.type == TokenType.name) { if ("interface".equals(name)) { this.flowParseInterface(start); return null; } else if ("type".equals(name)) { this.flowParseTypeAlias(start); return null; } else if ("opaque".equals(name)) { this.flowParseOpaqueType(start, false); return null; } } } return super.parseExpressionStatement(declaration, start, expr); } // export type @Override protected boolean shouldParseExportStatement() { return flow() && (this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque")) || super.shouldParseExportStatement(); } @Override protected Expression parseParenItem(Expression left, int startPos, Position startLoc) { Expression node = super.parseParenItem(left, startPos, startLoc); if (flow()) { if (this.eat(TokenType.question)) { // do something with the information } if (this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } } return node; }; @Override protected ExportDeclaration parseExportRest(SourceLocation loc, Set<String> exports) { if (flow() && (this.type.keyword != null || shouldParseExportStatement())) { Position start = startLoc; if (this.isContextual("type")) { this.next(); if (this.type == TokenType.braceL) { // `export type { foo, bar };` List<ExportSpecifier> specifiers = this.parseExportSpecifiers(exports); this.parseExportFrom(specifiers, null, false); return null; } else if (this.eat(TokenType.star)) { if (this.eatContextual("as")) this.parseIdent(true); this.parseExportFrom(null, null, true); return null; } else { // `export type Foo = Bar;` this.flowParseTypeAlias(startLoc); return null; } } else if (this.isContextual("opaque")) { this.next(); this.flowParseOpaqueType(start, false); return null; } else if (this.isContextual("interface")) { this.next(); this.flowParseInterface(start); return null; } } return super.parseExportRest(loc, exports); } @Override protected Identifier parseClassId(boolean isStatement) { Identifier id = super.parseClassId(isStatement); if (flow() && this.isRelational("<")) this.flowParseTypeParameterDeclaration(); return id; } // don't consider `void` to be a keyword as then it'll use the void token type // and set startExpr @Override protected boolean isKeyword(String src) { if (inType && "void".equals(src)) return false; return super.isKeyword(src); } // ensure that inside flow types, we bypass the jsx parser plugin @Override protected Token readToken(int code) { if (this.inType && (code == 62 || code == 60)) { return this.finishOp(TokenType.relational, 1); } else { return super.readToken(code); } } @Override protected MethodDefinition parseClassMethod( Position startLoc, boolean isGenerator, boolean isAsync, boolean isStatic, boolean isComputed, MethodDefinition.Kind kind, Expression key) { if (flow() && this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } return super.parseClassMethod(startLoc, isGenerator, isAsync, isStatic, isComputed, kind, key); } // parse a the super class type parameters and implements @Override protected Expression parseClassSuper() { Expression ext = super.parseClassSuper(); if (flow() && ext != null && this.isRelational("<")) this.flowParseTypeParameterInstantiation(); if (flow() && this.isContextual("implements")) { this.next(); do { this.parseIdent(false); if (this.isRelational("<")) this.flowParseTypeParameterInstantiation(); } while (this.eat(TokenType.comma)); } return ext; } @Override protected Expression processBindingListItem(Expression param) { if (flow()) { if (this.eat(TokenType.question)) { // do something } if (this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } this.finishNode(param); } return param; } private String flowParseImportSpecifiers() { String kind = peekAtSpecialFlowImportSpecifier(); if (kind != null) { String lh = lookahead(4); if (!lh.isEmpty()) { int c = lh.codePointAt(0); if ((Identifiers.isIdentifierStart(c, true) && !"from".equals(lh)) || c == '{' || c == '*') { this.next(); } } } return kind; } private String peekAtSpecialFlowImportSpecifier() { String kind = null; if (this.type == TokenType._typeof) { kind = "typeof"; } else if (this.isContextual("type")) { kind = "type"; } return kind; } @Override protected List<ImportSpecifier> parseImportSpecifiers() { String kind = null; if (flow()) { kind = flowParseImportSpecifiers(); } List<ImportSpecifier> specs = super.parseImportSpecifiers(); if (kind != null || specs.isEmpty()) return null; return specs; } @Override protected ImportSpecifier parseImportSpecifier() { if (peekAtSpecialFlowImportSpecifier() != null) { String lh = lookahead(2); if (lh.charAt(0) == ',' || lh.charAt(0) == '}' || lh.equals("as")) return super.parseImportSpecifier(); this.next(); super.parseImportSpecifier(); return null; } else { return super.parseImportSpecifier(); } } @Override protected List<Expression> parseFunctionParams() { if (flow()) { boolean oldInType = this.inType; this.inType = true; if (this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); } this.inType = oldInType; } return super.parseFunctionParams(); } // parse flow type annotations on variable declarator heads - let foo: string = bar @Override protected Expression parseVarId() { Expression varId = super.parseVarId(); if (flow() && this.type == TokenType.colon) { this.flowParseTypeAnnotation(); this.finishNode(varId); } return varId; } @Override protected Expression parseBindingAtom() { Expression bindingAtom = super.parseBindingAtom(); if (flow()) { if (this.eat(TokenType.question)) { // do something } if (this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } this.finishNode(bindingAtom); } return bindingAtom; } @Override protected Expression processExprListItem(Expression item) { if (flow()) { if (this.eat(TokenType.question)) { // do something } if (this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } this.finishNode(item); } return item; } @Override protected Expression parseConditionalRest(boolean noIn, Position start, Expression test) { if (flow()) { if (this.type == TokenType.colon) { this.flowParseTypeAnnotation(); return test; } else if (this.type == TokenType.comma || this.type == TokenType.parenR) { return test; } } return super.parseConditionalRest(noIn, start, test); } @Override protected ParenthesisedExpressions parseParenthesisedExpressions( DestructuringErrors refDestructuringErrors) { ParenthesisedExpressions pe = super.parseParenthesisedExpressions(refDestructuringErrors); // handle return types for arrow functions if (flow() && this.type == TokenType.colon) { // This is a tricky case: we have parsed `c ? (e) :` // We could be in the middle of parsing an arrow expression with a declared // return type (that is, we are expecting to see `t => b : f`, with `t` the // declared return type, `b` the body of the arrow expression, and `f` the // "else" branch of the conditional expression), or we could be done parsing // the "then" branch of the conditional (that is, we are expecting to see the // "else" branch `f`). // We model the behaviour of Babel and Flow by trying to parse the following // tokens as a type annotation followed by an arrow token. If this fails, we // backtrack. State backup = new State(); try { boolean oldNoAnonFunctionType = noAnonFunctionType; noAnonFunctionType = true; flowParseTypeAnnotation(); flowParseChecksAnnotation(); noAnonFunctionType = oldNoAnonFunctionType; if (this.type != TokenType.arrow) unexpected(); backup.commit(); } catch (SyntaxError e) { Exceptions.ignore(e, "Backtracking parser."); backup.reset(); } } return pe; } @Override protected boolean shouldParseAsyncArrow() { if (flow() && this.type == TokenType.colon) { boolean oldNoAnonFunctionType = noAnonFunctionType; noAnonFunctionType = true; this.flowParseTypeAnnotation(); noAnonFunctionType = oldNoAnonFunctionType; } return super.shouldParseAsyncArrow(); } @Override protected boolean isClassProperty() { return flow() && this.type == TokenType.colon || super.isClassProperty(); } @Override protected FieldDefinition parseFieldDefinition(PropertyInfo pi, boolean isStatic) { if (flow() && this.type == TokenType.colon) { this.flowParseTypeAnnotation(); } return super.parseFieldDefinition(pi, isStatic); } // parse type parameters for object method shorthand @Override protected void parsePropertyValue(PropertyInfo pi, DestructuringErrors refDestructuringErrors) { // method shorthand if (flow() && this.isRelational("<")) { this.flowParseTypeParameterDeclaration(); if (this.type != TokenType.parenL) this.unexpected(); } super.parsePropertyValue(pi, refDestructuringErrors); } @Override protected void parsePropertyName(PropertyInfo result) { if (flow()) this.eat(TokenType.plusMin); super.parsePropertyName(result); } @Override protected boolean atGetterSetterName(PropertyInfo pi) { if (flow() && this.isRelational("<")) return false; return super.atGetterSetterName(pi); } @Override protected Pair<Expression, Boolean> parseSubscript( final Expression base, Position startLoc, boolean noCalls) { if (!noCalls) { maybeFlowParseTypeParameterInstantiation(base, true); } return super.parseSubscript(base, startLoc, noCalls); } private void maybeFlowParseTypeParameterInstantiation(Expression left, boolean requireParenL) { if (flow() && this.isRelational("<")) { // Ambiguous case: `e1<e2>(e3)` is parsed differently as JS and Flow code: // JS: two relational comparisons: `e1 < e2 > e3` // Flow: a call `e1(e3)` with explicit type parameter `e2` // Heuristic: if the left operand of the `<` token is a primitive from a literal or // unary/binary expression, then it probably isn't a call, as that would always crash left = left.stripParens(); if (left instanceof Literal || left instanceof UnaryExpression || left instanceof BinaryExpression) return; // If it can be parsed as Flow, we use that, otherwise we parse it as JS State backup = new State(); try { this.flowParseTypeParameterInstantiation(); if (requireParenL && this.type != TokenType.parenL) { unexpected(); } backup.commit(); } catch (SyntaxError e) { Exceptions.ignore(e, "Backtracking parser."); backup.reset(); } } } @Override protected Expression parseNewArguments(Position startLoc, Expression callee) { maybeFlowParseTypeParameterInstantiation(callee, false /* case: new e1<e2>e3 */); return super.parseNewArguments(startLoc, callee); } }
38,797
29.263651
105
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/jsx/JSXParser.java
package com.semmle.jcorn.jsx; import static com.semmle.jcorn.Parser.TokContext.b_expr; import static com.semmle.jcorn.Parser.TokContext.b_tmpl; import static com.semmle.jcorn.TokenType.braceL; import static com.semmle.jcorn.TokenType.braceR; import static com.semmle.jcorn.TokenType.colon; import static com.semmle.jcorn.TokenType.dot; import static com.semmle.jcorn.TokenType.ellipsis; import static com.semmle.jcorn.TokenType.eq; import static com.semmle.jcorn.TokenType.relational; import static com.semmle.jcorn.TokenType.slash; import static com.semmle.jcorn.TokenType.string; import static com.semmle.jcorn.Whitespace.isNewLine; import com.semmle.jcorn.Identifiers; import com.semmle.jcorn.Options; import com.semmle.jcorn.Parser; import com.semmle.jcorn.TokenType; import com.semmle.jcorn.TokenType.Properties; import com.semmle.js.ast.Expression; import com.semmle.js.ast.INode; import com.semmle.js.ast.Position; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Token; import com.semmle.js.ast.jsx.IJSXAttribute; import com.semmle.js.ast.jsx.IJSXName; import com.semmle.js.ast.jsx.JSXAttribute; import com.semmle.js.ast.jsx.JSXClosingElement; import com.semmle.js.ast.jsx.JSXElement; import com.semmle.js.ast.jsx.JSXEmptyExpression; import com.semmle.js.ast.jsx.JSXExpressionContainer; import com.semmle.js.ast.jsx.JSXIdentifier; import com.semmle.js.ast.jsx.JSXMemberExpression; import com.semmle.js.ast.jsx.JSXNamespacedName; import com.semmle.js.ast.jsx.JSXOpeningElement; import com.semmle.js.ast.jsx.JSXSpreadAttribute; import com.semmle.util.data.Either; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; /** * Java port of <a href="https://github.com/RReverser/acorn-jsx">Acorn-JSX</a> as of version <a * href="https://github.com/RReverser/acorn-jsx/commit/05852d8ae9476b7f8a25e417665e2265528d5fb9">3.0.1</a>. * * <p>Like the plain JavaScript {@link Parser}, the JSX parser is parameterized by an {@link * Options} object. To enable JSX parsing, pass in a {@link JSXOptions} object. */ public class JSXParser extends Parser { private static final Pattern hexNumber = Pattern.compile("^[\\da-fA-F]+$"); private static final Pattern decimalNumber = Pattern.compile("^\\d+$"); public JSXParser(Options options, String input, int startPos) { super(options, input, startPos); } private static final TokContext j_oTag = new TokContext("<tag", false); private static final TokContext j_cTag = new TokContext("</tag", false); private static final TokContext j_expr = new TokContext("<tag>..</tag>", true, true, null); private static final TokenType jsxName = new TokenType(new Properties("jsxName")); public static final TokenType jsxText = new TokenType(new Properties("jsxText").beforeExpr()); protected static final TokenType jsxTagStart = new TokenType(new Properties("jsxTagStart")) { @Override public void updateContext(Parser parser, TokenType prevType) { parser.pushTokenContext(j_expr); // treat as beginning of JSX expression parser.pushTokenContext(j_oTag); // start opening tag context parser.exprAllowed(false); } }; private static final TokenType jsxTagEnd = new TokenType(new Properties("jsxTagEnd")) { @Override public void updateContext(Parser parser, TokenType prevType) { TokContext out = parser.popTokenContext(); if (out == j_oTag && prevType == slash || out == j_cTag) { parser.popTokenContext(); parser.exprAllowed(parser.curContext() == j_expr); } else { parser.exprAllowed(true); } } }; /** Reads inline JSX contents token. */ private Token jsx_readToken() { StringBuilder out = new StringBuilder(); int chunkStart = this.pos; for (; ; ) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated JSX contents"); Either<Integer, Token> chunk = jsx_readChunk(out, chunkStart, this.charAt(this.pos)); if (chunk.isRight()) return chunk.getRight(); chunkStart = chunk.getLeft(); } } /** * Reads a chunk of inline JSX content, returning either the start of the next chunk or the * completed content token. */ protected Either<Integer, Token> jsx_readChunk(StringBuilder out, int chunkStart, int ch) { switch (ch) { case 60: // '<' case 123: // '{' if (this.pos == this.start) { if (ch == 60 && this.exprAllowed) { ++this.pos; return Either.right(this.finishToken(jsxTagStart)); } return Either.right(this.getTokenFromCode(ch)); } out.append(inputSubstring(chunkStart, this.pos)); return Either.right(this.finishToken(jsxText, out.toString())); case 38: // '&' out.append(inputSubstring(chunkStart, this.pos)); out.append(this.jsx_readEntity()); chunkStart = this.pos; break; default: if (isNewLine(ch)) { out.append(inputSubstring(chunkStart, this.pos)); out.append(this.jsx_readNewLine(true)); chunkStart = this.pos; } else { ++this.pos; } } return Either.left(chunkStart); } private String jsx_readNewLine(boolean normalizeCRLF) { int ch = this.charAt(this.pos); String out; ++this.pos; if (ch == 13 && this.charAt(this.pos) == 10) { ++this.pos; out = normalizeCRLF ? "\n" : "\r\n"; } else { out = String.valueOf((char) ch); } ++this.curLine; this.lineStart = this.pos; return out; } private Token jsx_readString(char quote) { StringBuilder out = new StringBuilder(); int chunkStart = ++this.pos; for (; ; ) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated string constant"); int ch = this.charAt(this.pos); if (ch == quote) break; if (ch == 38) { // '&' out.append(inputSubstring(chunkStart, this.pos)); out.append(this.jsx_readEntity()); chunkStart = this.pos; } else if (isNewLine(ch)) { out.append(inputSubstring(chunkStart, this.pos)); out.append(this.jsx_readNewLine(false)); chunkStart = this.pos; } else { ++this.pos; } } out.append(inputSubstring(chunkStart, this.pos++)); return this.finishToken(string, out.toString()); } private String jsx_readEntity() { int ch = this.charAt(this.pos); if (ch != '&') this.raise(this.pos, "Entity must start with an ampersand"); int startPos = ++this.pos; String entity = null; int semi = this.input.indexOf(';', startPos); if (semi != -1) { String entityName = inputSubstring(startPos, semi); if (entityName.startsWith("#x")) { entityName = entityName.substring(2); if (hexNumber.matcher(entityName).matches()) entity = codePointToString(parseInt(entityName, 16).intValue()); } else if (entityName.startsWith("#")) { entityName = entityName.substring(1); if (decimalNumber.matcher(entityName).matches()) entity = codePointToString(parseInt(entityName, 10).intValue()); } else { Character entityChar = XHTMLEntities.ENTITIES.get(entityName); if (entityChar != null) entity = String.valueOf(entityChar); } } if (entity == null) { this.pos = startPos; return "&"; } else { this.pos = semi + 1; return entity; } } /** * Read a JSX identifier (valid tag or attribute name). * * <p>Optimized version since JSX identifiers can't contain escape characters and so can be read * as single slice. Also assumes that first character was already checked by isIdentifierStart in * readToken. */ private Token jsx_readWord() { int ch, start = this.pos; do { ch = this.charAt(++this.pos); } while (Identifiers.isIdentifierChar(ch, true) || ch == 45); // '-' return this.finishToken(jsxName, inputSubstring(start, this.pos)); } /** Transforms JSX element name to string; {@code null} is transformed to {@code null}. */ private String getQualifiedJSXName(Object object) { if (object == null) return null; return ((IJSXName) object).getQualifiedName(); } /** Parse next token as JSX identifier */ private JSXIdentifier jsx_parseIdentifier() { SourceLocation loc = new SourceLocation(this.startLoc); String name = null; if (this.type == jsxName) name = String.valueOf(this.value); else if (this.type.keyword != null) name = this.type.keyword; else this.unexpected(); this.next(); return this.finishNode(new JSXIdentifier(loc, name)); } /** Parse namespaced identifier. */ private IJSXName jsx_parseNamespacedName() { SourceLocation loc = new SourceLocation(this.startLoc); JSXIdentifier namespace = this.jsx_parseIdentifier(); if (!((JSXOptions) options).allowNamespaces || !this.eat(colon)) return namespace; return this.finishNode(new JSXNamespacedName(loc, namespace, this.jsx_parseIdentifier())); } /** * Parses element name in any form - namespaced, member or single identifier. If the next token is * a tag-end token, {@code null} is returned; this happens with fragments. */ private IJSXName jsx_parseElementName() { if (this.type == jsxTagEnd) return null; Position startPos = this.startLoc; IJSXName node = this.jsx_parseNamespacedName(); if (this.type == dot && node instanceof JSXNamespacedName && !((JSXOptions) options).allowNamespacedObjects) { this.unexpected(); } while (this.eat(dot)) { SourceLocation loc = new SourceLocation(startPos); node = this.finishNode(new JSXMemberExpression(loc, node, this.jsx_parseIdentifier())); } return node; } /** Parses any type of JSX attribute value. */ private INode jsx_parseAttributeValue() { if (type == braceL) { JSXExpressionContainer node = this.jsx_parseExpressionContainer(); if (node.getExpression() instanceof JSXEmptyExpression) this.raise(node, "JSX attributes must only be assigned a non-empty expression"); return node; } else if (type == jsxTagStart || type == string) { return this.parseExprAtom(null); } else { this.raise(this.start, "JSX value should be either an expression or a quoted JSX text"); return null; } } /** * JSXEmptyExpression is unique type since it doesn't actually parse anything, and so it should * start at the end of last read token (left brace) and finish at the beginning of the next one * (right brace). */ private JSXEmptyExpression jsx_parseEmptyExpression() { return new JSXEmptyExpression(new SourceLocation("", lastTokEndLoc, startLoc)); } /** Parses JSX expression enclosed into curly brackets. */ private JSXExpressionContainer jsx_parseExpressionContainer() { SourceLocation loc = new SourceLocation(this.startLoc); this.next(); INode expression; if (this.type == braceR) expression = this.jsx_parseEmptyExpression(); else expression = this.parseExpression(false, null); this.expect(braceR); return this.finishNode(new JSXExpressionContainer(loc, expression)); } /** Parses following JSX attribute name-value pair. */ private IJSXAttribute jsx_parseAttribute() { SourceLocation loc = new SourceLocation(this.startLoc); if (this.eat(braceL)) { this.expect(ellipsis); Expression argument = this.parseMaybeAssign(false, null, null); this.expect(braceR); return this.finishNode(new JSXSpreadAttribute(loc, argument)); } IJSXName name = this.jsx_parseNamespacedName(); INode value = this.eat(eq) ? this.jsx_parseAttributeValue() : null; return this.finishNode(new JSXAttribute(loc, name, value)); } /** Parses JSX opening tag starting after '&lt;'. */ private JSXOpeningElement jsx_parseOpeningElementAt(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); List<IJSXAttribute> attributes = new ArrayList<>(); IJSXName name = this.jsx_parseElementName(); while (this.type != slash && this.type != jsxTagEnd) attributes.add(this.jsx_parseAttribute()); boolean selfClosing = this.eat(slash); this.expect(jsxTagEnd); return this.finishNode(new JSXOpeningElement(loc, name, attributes, selfClosing)); } /** Parses JSX closing tag starting after '&lt;/'. */ private JSXClosingElement jsx_parseClosingElementAt(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); IJSXName name = this.jsx_parseElementName(); this.expect(jsxTagEnd); return this.finishNode(new JSXClosingElement(loc, name)); } /** * Parses entire JSX element, including its opening tag (starting after '&lt;'), attributes, * contents and closing tag. */ private JSXElement jsx_parseElementAt(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); List<INode> children = new ArrayList<INode>(); JSXOpeningElement openingElement = this.jsx_parseOpeningElementAt(startLoc); JSXClosingElement closingElement = null; if (!openingElement.isSelfClosing()) { contents: for (; ; ) { if (type == jsxTagStart) { startLoc = this.startLoc; this.next(); if (this.eat(slash)) { closingElement = this.jsx_parseClosingElementAt(startLoc); break contents; } children.add(this.jsx_parseElementAt(startLoc)); } else if (type == jsxText) { children.add(this.parseExprAtom(null)); } else if (type == braceL) { children.add(this.jsx_parseExpressionContainer()); } else { this.unexpected(); } } String closingQualName = getQualifiedJSXName(openingElement.getName()); if (!Objects.equals(getQualifiedJSXName(closingElement.getName()), closingQualName)) { // prettify for error message if (closingQualName == null) closingQualName = ""; this.raise( closingElement, "Expected corresponding JSX closing tag for <" + closingQualName + ">"); } } if (this.type == relational && "<".equals(this.value)) { this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); } return this.finishNode(new JSXElement(loc, openingElement, children, closingElement)); } /** Parses entire JSX element from current position. */ private JSXElement jsx_parseElement() { Position startLoc = this.startLoc; this.next(); return this.jsx_parseElementAt(startLoc); } @Override protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { if (this.type == jsxText) { return this.parseLiteral(this.type, this.value); } else if (this.type == jsxTagStart) { return this.jsx_parseElement(); } else { return super.parseExprAtom(refDestructuringErrors); } } @Override protected Token readToken(int code) { TokContext context = this.curContext(); if (context == j_expr) return this.jsx_readToken(); if (context == j_oTag || context == j_cTag) { if (Identifiers.isIdentifierStart(code, true)) return this.jsx_readWord(); if (code == 62) { ++this.pos; return this.finishToken(jsxTagEnd); } if ((code == 34 || code == 39) && context == j_oTag) return this.jsx_readString((char) code); } if (options instanceof JSXOptions && code == 60 && this.exprAllowed && // avoid getting confused on HTML comments this.charAt(this.pos + 1) != '!') { ++this.pos; return this.finishToken(jsxTagStart); } return super.readToken(code); } @Override protected void updateContext(TokenType prevType) { if (options instanceof JSXOptions) { if (type == braceL) { TokContext curContext = this.curContext(); if (curContext == j_oTag) { this.context.push(b_expr); } else if (curContext == j_expr) { this.context.push(b_tmpl); } else { type.updateContext(this, prevType); } this.exprAllowed = true; return; } else if (type == slash && prevType == jsxTagStart) { this.context.pop(); this.context.pop(); // do not consider JSX expr -> JSX open tag -> ... anymore this.context.push(j_cTag); this.exprAllowed = false; return; } } super.updateContext(prevType); } }
16,629
35.792035
107
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/jsx/JSXOptions.java
package com.semmle.jcorn.jsx; import com.semmle.jcorn.Options; public class JSXOptions extends Options { public boolean allowNamespacedObjects = true, allowNamespaces = true; public JSXOptions() {} public JSXOptions(Options options) { super(options); } public JSXOptions allowNamespacedObjects(boolean allowNamespacedObjects) { this.allowNamespacedObjects = allowNamespacedObjects; return this; } public JSXOptions allowNamespaces(boolean allowNamespaces) { this.allowNamespaces = allowNamespaces; return this; } }
557
22.25
76
java
codeql
codeql-master/javascript/extractor/src/com/semmle/jcorn/jsx/XHTMLEntities.java
package com.semmle.jcorn.jsx; import java.util.LinkedHashMap; import java.util.Map; public class XHTMLEntities { public static final Map<String, Character> ENTITIES = new LinkedHashMap<>(); static { ENTITIES.put("quot", '\u0022'); ENTITIES.put("amp", '&'); ENTITIES.put("apos", '\''); ENTITIES.put("lt", '<'); ENTITIES.put("gt", '>'); ENTITIES.put("nbsp", '\u00A0'); ENTITIES.put("iexcl", '\u00A1'); ENTITIES.put("cent", '\u00A2'); ENTITIES.put("pound", '\u00A3'); ENTITIES.put("curren", '\u00A4'); ENTITIES.put("yen", '\u00A5'); ENTITIES.put("brvbar", '\u00A6'); ENTITIES.put("sect", '\u00A7'); ENTITIES.put("uml", '\u00A8'); ENTITIES.put("copy", '\u00A9'); ENTITIES.put("ordf", '\u00AA'); ENTITIES.put("laquo", '\u00AB'); ENTITIES.put("not", '\u00AC'); ENTITIES.put("shy", '\u00AD'); ENTITIES.put("reg", '\u00AE'); ENTITIES.put("macr", '\u00AF'); ENTITIES.put("deg", '\u00B0'); ENTITIES.put("plusmn", '\u00B1'); ENTITIES.put("sup2", '\u00B2'); ENTITIES.put("sup3", '\u00B3'); ENTITIES.put("acute", '\u00B4'); ENTITIES.put("micro", '\u00B5'); ENTITIES.put("para", '\u00B6'); ENTITIES.put("middot", '\u00B7'); ENTITIES.put("cedil", '\u00B8'); ENTITIES.put("sup1", '\u00B9'); ENTITIES.put("ordm", '\u00BA'); ENTITIES.put("raquo", '\u00BB'); ENTITIES.put("frac14", '\u00BC'); ENTITIES.put("frac12", '\u00BD'); ENTITIES.put("frac34", '\u00BE'); ENTITIES.put("iquest", '\u00BF'); ENTITIES.put("Agrave", '\u00C0'); ENTITIES.put("Aacute", '\u00C1'); ENTITIES.put("Acirc", '\u00C2'); ENTITIES.put("Atilde", '\u00C3'); ENTITIES.put("Auml", '\u00C4'); ENTITIES.put("Aring", '\u00C5'); ENTITIES.put("AElig", '\u00C6'); ENTITIES.put("Ccedil", '\u00C7'); ENTITIES.put("Egrave", '\u00C8'); ENTITIES.put("Eacute", '\u00C9'); ENTITIES.put("Ecirc", '\u00CA'); ENTITIES.put("Euml", '\u00CB'); ENTITIES.put("Igrave", '\u00CC'); ENTITIES.put("Iacute", '\u00CD'); ENTITIES.put("Icirc", '\u00CE'); ENTITIES.put("Iuml", '\u00CF'); ENTITIES.put("ETH", '\u00D0'); ENTITIES.put("Ntilde", '\u00D1'); ENTITIES.put("Ograve", '\u00D2'); ENTITIES.put("Oacute", '\u00D3'); ENTITIES.put("Ocirc", '\u00D4'); ENTITIES.put("Otilde", '\u00D5'); ENTITIES.put("Ouml", '\u00D6'); ENTITIES.put("times", '\u00D7'); ENTITIES.put("Oslash", '\u00D8'); ENTITIES.put("Ugrave", '\u00D9'); ENTITIES.put("Uacute", '\u00DA'); ENTITIES.put("Ucirc", '\u00DB'); ENTITIES.put("Uuml", '\u00DC'); ENTITIES.put("Yacute", '\u00DD'); ENTITIES.put("THORN", '\u00DE'); ENTITIES.put("szlig", '\u00DF'); ENTITIES.put("agrave", '\u00E0'); ENTITIES.put("aacute", '\u00E1'); ENTITIES.put("acirc", '\u00E2'); ENTITIES.put("atilde", '\u00E3'); ENTITIES.put("auml", '\u00E4'); ENTITIES.put("aring", '\u00E5'); ENTITIES.put("aelig", '\u00E6'); ENTITIES.put("ccedil", '\u00E7'); ENTITIES.put("egrave", '\u00E8'); ENTITIES.put("eacute", '\u00E9'); ENTITIES.put("ecirc", '\u00EA'); ENTITIES.put("euml", '\u00EB'); ENTITIES.put("igrave", '\u00EC'); ENTITIES.put("iacute", '\u00ED'); ENTITIES.put("icirc", '\u00EE'); ENTITIES.put("iuml", '\u00EF'); ENTITIES.put("eth", '\u00F0'); ENTITIES.put("ntilde", '\u00F1'); ENTITIES.put("ograve", '\u00F2'); ENTITIES.put("oacute", '\u00F3'); ENTITIES.put("ocirc", '\u00F4'); ENTITIES.put("otilde", '\u00F5'); ENTITIES.put("ouml", '\u00F6'); ENTITIES.put("divide", '\u00F7'); ENTITIES.put("oslash", '\u00F8'); ENTITIES.put("ugrave", '\u00F9'); ENTITIES.put("uacute", '\u00FA'); ENTITIES.put("ucirc", '\u00FB'); ENTITIES.put("uuml", '\u00FC'); ENTITIES.put("yacute", '\u00FD'); ENTITIES.put("thorn", '\u00FE'); ENTITIES.put("yuml", '\u00FF'); ENTITIES.put("OElig", '\u0152'); ENTITIES.put("oelig", '\u0153'); ENTITIES.put("Scaron", '\u0160'); ENTITIES.put("scaron", '\u0161'); ENTITIES.put("Yuml", '\u0178'); ENTITIES.put("fnof", '\u0192'); ENTITIES.put("circ", '\u02C6'); ENTITIES.put("tilde", '\u02DC'); ENTITIES.put("Alpha", '\u0391'); ENTITIES.put("Beta", '\u0392'); ENTITIES.put("Gamma", '\u0393'); ENTITIES.put("Delta", '\u0394'); ENTITIES.put("Epsilon", '\u0395'); ENTITIES.put("Zeta", '\u0396'); ENTITIES.put("Eta", '\u0397'); ENTITIES.put("Theta", '\u0398'); ENTITIES.put("Iota", '\u0399'); ENTITIES.put("Kappa", '\u039A'); ENTITIES.put("Lambda", '\u039B'); ENTITIES.put("Mu", '\u039C'); ENTITIES.put("Nu", '\u039D'); ENTITIES.put("Xi", '\u039E'); ENTITIES.put("Omicron", '\u039F'); ENTITIES.put("Pi", '\u03A0'); ENTITIES.put("Rho", '\u03A1'); ENTITIES.put("Sigma", '\u03A3'); ENTITIES.put("Tau", '\u03A4'); ENTITIES.put("Upsilon", '\u03A5'); ENTITIES.put("Phi", '\u03A6'); ENTITIES.put("Chi", '\u03A7'); ENTITIES.put("Psi", '\u03A8'); ENTITIES.put("Omega", '\u03A9'); ENTITIES.put("alpha", '\u03B1'); ENTITIES.put("beta", '\u03B2'); ENTITIES.put("gamma", '\u03B3'); ENTITIES.put("delta", '\u03B4'); ENTITIES.put("epsilon", '\u03B5'); ENTITIES.put("zeta", '\u03B6'); ENTITIES.put("eta", '\u03B7'); ENTITIES.put("theta", '\u03B8'); ENTITIES.put("iota", '\u03B9'); ENTITIES.put("kappa", '\u03BA'); ENTITIES.put("lambda", '\u03BB'); ENTITIES.put("mu", '\u03BC'); ENTITIES.put("nu", '\u03BD'); ENTITIES.put("xi", '\u03BE'); ENTITIES.put("omicron", '\u03BF'); ENTITIES.put("pi", '\u03C0'); ENTITIES.put("rho", '\u03C1'); ENTITIES.put("sigmaf", '\u03C2'); ENTITIES.put("sigma", '\u03C3'); ENTITIES.put("tau", '\u03C4'); ENTITIES.put("upsilon", '\u03C5'); ENTITIES.put("phi", '\u03C6'); ENTITIES.put("chi", '\u03C7'); ENTITIES.put("psi", '\u03C8'); ENTITIES.put("omega", '\u03C9'); ENTITIES.put("thetasym", '\u03D1'); ENTITIES.put("upsih", '\u03D2'); ENTITIES.put("piv", '\u03D6'); ENTITIES.put("ensp", '\u2002'); ENTITIES.put("emsp", '\u2003'); ENTITIES.put("thinsp", '\u2009'); ENTITIES.put("zwnj", '\u200C'); ENTITIES.put("zwj", '\u200D'); ENTITIES.put("lrm", '\u200E'); ENTITIES.put("rlm", '\u200F'); ENTITIES.put("ndash", '\u2013'); ENTITIES.put("mdash", '\u2014'); ENTITIES.put("lsquo", '\u2018'); ENTITIES.put("rsquo", '\u2019'); ENTITIES.put("sbquo", '\u201A'); ENTITIES.put("ldquo", '\u201C'); ENTITIES.put("rdquo", '\u201D'); ENTITIES.put("bdquo", '\u201E'); ENTITIES.put("dagger", '\u2020'); ENTITIES.put("Dagger", '\u2021'); ENTITIES.put("bull", '\u2022'); ENTITIES.put("hellip", '\u2026'); ENTITIES.put("permil", '\u2030'); ENTITIES.put("prime", '\u2032'); ENTITIES.put("Prime", '\u2033'); ENTITIES.put("lsaquo", '\u2039'); ENTITIES.put("rsaquo", '\u203A'); ENTITIES.put("oline", '\u203E'); ENTITIES.put("frasl", '\u2044'); ENTITIES.put("euro", '\u20AC'); ENTITIES.put("image", '\u2111'); ENTITIES.put("weierp", '\u2118'); ENTITIES.put("real", '\u211C'); ENTITIES.put("trade", '\u2122'); ENTITIES.put("alefsym", '\u2135'); ENTITIES.put("larr", '\u2190'); ENTITIES.put("uarr", '\u2191'); ENTITIES.put("rarr", '\u2192'); ENTITIES.put("darr", '\u2193'); ENTITIES.put("harr", '\u2194'); ENTITIES.put("crarr", '\u21B5'); ENTITIES.put("lArr", '\u21D0'); ENTITIES.put("uArr", '\u21D1'); ENTITIES.put("rArr", '\u21D2'); ENTITIES.put("dArr", '\u21D3'); ENTITIES.put("hArr", '\u21D4'); ENTITIES.put("forall", '\u2200'); ENTITIES.put("part", '\u2202'); ENTITIES.put("exist", '\u2203'); ENTITIES.put("empty", '\u2205'); ENTITIES.put("nabla", '\u2207'); ENTITIES.put("isin", '\u2208'); ENTITIES.put("notin", '\u2209'); ENTITIES.put("ni", '\u220B'); ENTITIES.put("prod", '\u220F'); ENTITIES.put("sum", '\u2211'); ENTITIES.put("minus", '\u2212'); ENTITIES.put("lowast", '\u2217'); ENTITIES.put("radic", '\u221A'); ENTITIES.put("prop", '\u221D'); ENTITIES.put("infin", '\u221E'); ENTITIES.put("ang", '\u2220'); ENTITIES.put("and", '\u2227'); ENTITIES.put("or", '\u2228'); ENTITIES.put("cap", '\u2229'); ENTITIES.put("cup", '\u222A'); ENTITIES.put("'int'", '\u222B'); ENTITIES.put("there4", '\u2234'); ENTITIES.put("sim", '\u223C'); ENTITIES.put("cong", '\u2245'); ENTITIES.put("asymp", '\u2248'); ENTITIES.put("ne", '\u2260'); ENTITIES.put("equiv", '\u2261'); ENTITIES.put("le", '\u2264'); ENTITIES.put("ge", '\u2265'); ENTITIES.put("sub", '\u2282'); ENTITIES.put("sup", '\u2283'); ENTITIES.put("nsub", '\u2284'); ENTITIES.put("sube", '\u2286'); ENTITIES.put("supe", '\u2287'); ENTITIES.put("oplus", '\u2295'); ENTITIES.put("otimes", '\u2297'); ENTITIES.put("perp", '\u22A5'); ENTITIES.put("sdot", '\u22C5'); ENTITIES.put("lceil", '\u2308'); ENTITIES.put("rceil", '\u2309'); ENTITIES.put("lfloor", '\u230A'); ENTITIES.put("rfloor", '\u230B'); ENTITIES.put("lang", '\u2329'); ENTITIES.put("rang", '\u232A'); ENTITIES.put("loz", '\u25CA'); ENTITIES.put("spades", '\u2660'); ENTITIES.put("clubs", '\u2663'); ENTITIES.put("hearts", '\u2665'); ENTITIES.put("diams", '\u2666'); } }
9,459
34.698113
78
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/GenericTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** An instantiation of a named type, such as <tt>Array&lt;number&gt;</tt> */ public class GenericTypeExpr extends TypeExpression { private final ITypeExpression typeName; // Always Identifier or MemberExpression private final List<ITypeExpression> typeArguments; public GenericTypeExpr( SourceLocation loc, ITypeExpression typeName, List<ITypeExpression> typeArguments) { super("GenericTypeExpr", loc); this.typeName = typeName; this.typeArguments = typeArguments; } public ITypeExpression getTypeName() { return typeName; } public List<ITypeExpression> getTypeArguments() { return typeArguments; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
869
26.1875
90
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/FunctionTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.FunctionExpression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class FunctionTypeExpr extends TypeExpression { private final FunctionExpression function; private final boolean isConstructor; public FunctionTypeExpr(SourceLocation loc, FunctionExpression function, boolean isConstructor) { super("FunctionTypeExpr", loc); this.function = function; this.isConstructor = isConstructor; } public FunctionExpression getFunction() { return function; } public boolean isConstructor() { return isConstructor; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
732
23.433333
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ImportWholeDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; /** An import of form <tt>import a = E</tt>. */ public class ImportWholeDeclaration extends Statement { private final Identifier lhs; private final Expression rhs; public ImportWholeDeclaration(SourceLocation loc, Identifier lhs, Expression rhs) { super("ImportWholeDeclaration", loc); this.lhs = lhs; this.rhs = rhs; } public Identifier getLhs() { return lhs; } public Expression getRhs() { return rhs; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
756
21.939394
85
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TypeofTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * A type of form <tt>typeof E</tt> where <tt>E</tt> is an expression that takes the form of a * qualified name. */ public class TypeofTypeExpr extends TypeExpression { private final ITypeExpression expression; // Always Identifier or MemberExpression. public TypeofTypeExpr(SourceLocation loc, ITypeExpression expression) { super("TypeofTypeExpr", loc); this.expression = expression; } public ITypeExpression getExpression() { return expression; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
680
24.222222
94
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ParenthesizedTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A type expression in parentheses, such as <tt>("foo" | "bar")</tt>. */ public class ParenthesizedTypeExpr extends TypeExpression { private final ITypeExpression elementType; public ParenthesizedTypeExpr(SourceLocation loc, ITypeExpression elementType) { super("ParenthesizedTypeExpr", loc); this.elementType = elementType; } public ITypeExpression getElementType() { return elementType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
618
24.791667
81
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/IndexedAccessTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A type of form <tt>T[K]</tt> where <tt>T</tt> and <tt>K</tt> are types. */ public class IndexedAccessTypeExpr extends TypeExpression { private final ITypeExpression objectType; private final ITypeExpression indexType; public IndexedAccessTypeExpr( SourceLocation loc, ITypeExpression objectType, ITypeExpression indexType) { super("IndexedAccessTypeExpr", loc); this.objectType = objectType; this.indexType = indexType; } public ITypeExpression getObjectType() { return objectType; } public ITypeExpression getIndexType() { return indexType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
794
24.645161
82
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ITypeExpression.java
package com.semmle.ts.ast; import com.semmle.js.ast.INode; import com.semmle.js.ast.Literal; /** * An AST node that may occur as part of a TypeScript type annotation. * * <p>At the QL level, expressions and type annotations are completely separate. In the extractor, * however, some expressions such as {@link Literal} type may occur in a type annotation because the * TypeScript AST does not distinguish <tt>null</tt> literals from the <tt>null</tt> type. */ public interface ITypeExpression extends INode, ITypedAstNode {}
533
37.142857
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/IntersectionTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** * An intersection type such as <tt>T&amp;S</tt>, denoting the intersection of type <tt>T</tt> and * type <tt>S</tt>. */ public class IntersectionTypeExpr extends TypeExpression { private final List<ITypeExpression> elementTypes; public IntersectionTypeExpr(SourceLocation loc, List<ITypeExpression> elementTypes) { super("IntersectionTypeExpr", loc); this.elementTypes = elementTypes; } /** The members of the intersection type; always contains at least two types. */ public List<ITypeExpression> getElementTypes() { return elementTypes; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
797
26.517241
98
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ImportTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** An import type such as in <tt>import("http").ServerRequest</tt>. */ public class ImportTypeExpr extends Expression implements ITypeExpression { private final ITypeExpression path; public ImportTypeExpr(SourceLocation loc, ITypeExpression path) { super("ImportTypeExpr", loc); this.path = path; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public ITypeExpression getPath() { return path; } }
612
23.52
75
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ConditionalTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A conditional type annotation, such as <tt>T extends any[] ? A : B</tt>. */ public class ConditionalTypeExpr extends TypeExpression { private ITypeExpression checkType; private ITypeExpression extendsType; private ITypeExpression trueType; private ITypeExpression falseType; public ConditionalTypeExpr( SourceLocation loc, ITypeExpression checkType, ITypeExpression extendsType, ITypeExpression trueType, ITypeExpression falseType) { super("ConditionalTypeExpr", loc); this.checkType = checkType; this.extendsType = extendsType; this.trueType = trueType; this.falseType = falseType; } public ITypeExpression getCheckType() { return checkType; } public ITypeExpression getExtendsType() { return extendsType; } public ITypeExpression getTrueType() { return trueType; } public ITypeExpression getFalseType() { return falseType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
1,131
23.085106
79
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ExternalModuleDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Literal; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; /** A statement of form <tt>declare module "X" {...}</tt>. */ public class ExternalModuleDeclaration extends Statement { private final Literal name; private final List<Statement> body; public ExternalModuleDeclaration(SourceLocation loc, Literal name, List<Statement> body) { super("ExternalModuleDeclaration", loc); this.name = name; this.body = body; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public Literal getName() { return name; } public List<Statement> getBody() { return body; } }
780
22.666667
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TypeAliasDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; public class TypeAliasDeclaration extends Statement implements INodeWithSymbol { private final Identifier name; private final List<TypeParameter> typeParameters; private final ITypeExpression definition; private int typeSymbol = -1; public TypeAliasDeclaration( SourceLocation loc, Identifier name, List<TypeParameter> typeParameters, ITypeExpression definition) { super("TypeAliasDeclaration", loc); this.name = name; this.typeParameters = typeParameters; this.definition = definition; } public Identifier getId() { return name; } public List<TypeParameter> getTypeParameters() { return typeParameters; } public boolean hasTypeParameters() { return !typeParameters.isEmpty(); } public ITypeExpression getDefinition() { return definition; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public int getSymbol() { return typeSymbol; } @Override public void setSymbol(int symbol) { this.typeSymbol = symbol; } }
1,279
21.45614
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/InterfaceTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** An inline interface type, such as <tt>{x: number; y: number}</tt>. */ public class InterfaceTypeExpr extends TypeExpression { private final List<MemberDefinition<?>> body; public InterfaceTypeExpr(SourceLocation loc, List<MemberDefinition<?>> body) { super("InterfaceTypeExpr", loc); this.body = body; } public List<MemberDefinition<?>> getBody() { return body; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
659
24.384615
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/PredicateTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * A type of form <tt>E is T</tt>, <tt>asserts E is T</tt> or <tt>asserts E</tt> where <tt>E</tt> is * a parameter name or <tt>this</tt> and <tt>T</tt> is a type. */ public class PredicateTypeExpr extends TypeExpression { private final ITypeExpression expression; private final ITypeExpression type; private final boolean hasAssertsKeyword; public PredicateTypeExpr( SourceLocation loc, ITypeExpression expression, ITypeExpression type, boolean hasAssertsKeyword) { super("PredicateTypeExpr", loc); this.expression = expression; this.type = type; this.hasAssertsKeyword = hasAssertsKeyword; } /** Returns the <tt>E</tt> in <tt>E is T</tt>. */ public ITypeExpression getExpression() { return expression; } /** Returns the <tt>T</tt> in <tt>E is T</tt>. */ public ITypeExpression getTypeExpr() { return type; } public boolean hasAssertsKeyword() { return hasAssertsKeyword; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
1,163
24.866667
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ExpressionWithTypeArguments.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** * An expression with type arguments, occurring as the super-class expression of a class. For * example: * * <pre> * class StringList extends List&lt;string&gt; {} * </pre> * * Above, <tt>List</tt> is a concrete expression whereas its type argument is a type. */ public class ExpressionWithTypeArguments extends Expression { private final Expression expression; private final List<ITypeExpression> typeArguments; public ExpressionWithTypeArguments( SourceLocation loc, Expression expression, List<ITypeExpression> typeArguments) { super("ExpressionWithTypeArguments", loc); this.expression = expression; this.typeArguments = typeArguments; } public Expression getExpression() { return expression; } public List<ITypeExpression> getTypeArguments() { return typeArguments; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
1,091
25
93
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/EnumDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Decorator; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; public class EnumDeclaration extends Statement implements INodeWithSymbol { private final boolean isConst; private final boolean hasDeclareKeyword; private final List<Decorator> decorators; private final Identifier id; private List<EnumMember> members; private int typeSymbol = -1; public EnumDeclaration( SourceLocation loc, boolean isConst, boolean hasDeclareKeyword, List<Decorator> decorators, Identifier id, List<EnumMember> members) { super("EnumDeclaration", loc); this.isConst = isConst; this.hasDeclareKeyword = hasDeclareKeyword; this.decorators = decorators; this.id = id; this.members = members; } public boolean isConst() { return isConst; } public boolean hasDeclareKeyword() { return hasDeclareKeyword; } public List<Decorator> getDecorators() { return decorators; } public Identifier getId() { return id; } public List<EnumMember> getMembers() { return members; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public int getSymbol() { return typeSymbol; } @Override public void setSymbol(int symbol) { this.typeSymbol = symbol; } }
1,487
20.882353
75
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/KeywordTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * One of the TypeScript keyword types, such as <tt>string</tt> or <tt>any</tt>. * * <p>This includes the type <tt>unique symbol</tt> which consists of two keywords but is * represented as a keyword single type expression. * * <p>At the QL level, the <tt>null</tt> type is also a keyword type. In the extractor, however, * this is represented by a Literal, because the TypeScript AST does not distinguish those two uses * of <tt>null</tt>. */ public class KeywordTypeExpr extends TypeExpression { private final String keyword; public KeywordTypeExpr(SourceLocation loc, String keyword) { super("KeywordTypeExpr", loc); this.keyword = keyword; } public String getKeyword() { return keyword; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
929
27.181818
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ITypedAstNode.java
package com.semmle.ts.ast; /** An AST node with an associated static type. */ public interface ITypedAstNode { /** * Gets the static type of this node as determined by the TypeScript compiler, or -1 if no type * was determined. * * <p>The ID refers to a type in a table that is extracted on a per-project basis, and the meaning * of this type ID is not available at the AST level. */ int getStaticTypeId(); void setStaticTypeId(int id); }
465
28.125
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/NonNullAssertion.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A TypeScript expression of form <tt>E!</tt>, asserting that <tt>E</tt> is not null. */ public class NonNullAssertion extends Expression { private final Expression expression; public NonNullAssertion(SourceLocation loc, Expression expression) { super("NonNullAssertion", loc); this.expression = expression; } public Expression getExpression() { return expression; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
631
24.28
90
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ArrayTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * An array type, such as <tt>number[]</tt>, or in general <tt>T[]</tt> where <tt>T</tt> is a type. */ public class ArrayTypeExpr extends TypeExpression { private final ITypeExpression elementType; public ArrayTypeExpr(SourceLocation loc, ITypeExpression elementType) { super("ArrayTypeExpr", loc); this.elementType = elementType; } public ITypeExpression getElementType() { return elementType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
627
23.153846
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/UnaryTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * A unary operator applied to a type. * * <p>This can be <tt>keyof T</tt> or <tt>readonly T</tt>. */ public class UnaryTypeExpr extends TypeExpression { private final ITypeExpression elementType; private final Kind kind; public enum Kind { Keyof, Readonly } public UnaryTypeExpr(SourceLocation loc, Kind kind, ITypeExpression elementType) { super("UnaryTypeExpr", loc); this.kind = kind; this.elementType = elementType; } public ITypeExpression getElementType() { return elementType; } public Kind getKind() { return kind; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
786
19.179487
84
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/GlobalAugmentationDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; /** A statement of form: <tt>declare global { ... }</tt> */ public class GlobalAugmentationDeclaration extends Statement { private final List<Statement> body; public GlobalAugmentationDeclaration(SourceLocation loc, List<Statement> body) { super("GlobalAugmentationDeclaration", loc); this.body = body; } public List<Statement> getBody() { return body; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
639
23.615385
82
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/INodeWithSymbol.java
package com.semmle.ts.ast; /** * An AST node that is associated with a TypeScript compiler symbol. * * <p>This can be the symbol for the type defined by this node, of it this is a module top-level, * the symbol for that module. */ public interface INodeWithSymbol { /** * Gets a number identifying the symbol associated with this AST node, or <tt>-1</tt> if there is * no such symbol. */ int getSymbol(); void setSymbol(int symbol); }
457
24.444444
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/InferTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A type annotation of form <tt>infer R</tt> */ public class InferTypeExpr extends TypeExpression { private TypeParameter typeParameter; public InferTypeExpr(SourceLocation loc, TypeParameter typeParameter) { super("InferTypeExpr", loc); this.typeParameter = typeParameter; } public TypeParameter getTypeParameter() { return typeParameter; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
569
22.75
73
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/OptionalTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** An optional type in a tuple type, such as <tt>number?</tt> in <tt>[string, number?]</tt>. */ public class OptionalTypeExpr extends TypeExpression { private final ITypeExpression elementType; public OptionalTypeExpr(SourceLocation loc, ITypeExpression elementType) { super("OptionalTypeExpr", loc); this.elementType = elementType; } public ITypeExpression getElementType() { return elementType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
625
25.083333
96
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ExportAsNamespaceDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; /** A statement of form <tt>export as namespace X</tt> where <tt>X</tt> is an identifier. */ public class ExportAsNamespaceDeclaration extends Statement { private Identifier id; public ExportAsNamespaceDeclaration(SourceLocation loc, Identifier id) { super("ExportAsNamespaceDeclaration", loc); this.id = id; } public Identifier getId() { return id; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
650
24.038462
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/RestTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** A rest type in a tuple type, such as <tt>number[]</tt> in <tt>[string, ...number[]]</tt>. */ public class RestTypeExpr extends TypeExpression { private final ITypeExpression arrayType; public RestTypeExpr(SourceLocation loc, ITypeExpression arrayType) { super("RestTypeExpr", loc); this.arrayType = arrayType; } public ITypeExpression getArrayType() { return arrayType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
601
24.083333
96
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TupleTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** A tuple type, such as <tt>[number, string]</tt>. */ public class TupleTypeExpr extends TypeExpression { private final List<ITypeExpression> elementTypes; public TupleTypeExpr(SourceLocation loc, List<ITypeExpression> elementTypes) { super("TupleTypeExpr", loc); this.elementTypes = elementTypes; } public List<ITypeExpression> getElementTypes() { return elementTypes; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
622
23.92
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TypeExpression.java
package com.semmle.ts.ast; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; /** * An AST node that may occur as part of a TypeScript type annotation and is not also an expression. */ public abstract class TypeExpression extends Node implements ITypeExpression { private int staticTypeId = -1; public TypeExpression(String type, SourceLocation loc) { super(type, loc); } @Override public int getStaticTypeId() { return staticTypeId; } @Override public void setStaticTypeId(int staticTypeId) { this.staticTypeId = staticTypeId; } }
590
21.730769
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ExportWholeDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; public class ExportWholeDeclaration extends Statement { private final Expression rhs; public ExportWholeDeclaration(SourceLocation loc, Expression rhs) { super("ExportWholeDeclaration", loc); this.rhs = rhs; } public Expression getRhs() { return rhs; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
551
21.08
69
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/UnionTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; /** A union type such as <tt>number | string | boolean</tt>. */ public class UnionTypeExpr extends TypeExpression { private final List<ITypeExpression> elementTypes; public UnionTypeExpr(SourceLocation loc, List<ITypeExpression> elementTypes) { super("UnionTypeExpr", loc); this.elementTypes = elementTypes; } /** The members of the union; always contains at least two types. */ public List<ITypeExpression> getElementTypes() { return elementTypes; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
701
26
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/DecoratorList.java
package com.semmle.ts.ast; import com.semmle.js.ast.Decorator; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; import java.util.List; public class DecoratorList extends Expression { private final List<Decorator> decorators; public DecoratorList(SourceLocation loc, List<Decorator> decorators) { super("DecoratorList", loc); this.decorators = decorators; } public List<Decorator> getDecorators() { return decorators; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
605
22.307692
72
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/EnumMember.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.Node; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class EnumMember extends Node implements INodeWithSymbol { private final Identifier id; private final Expression initializer; private int typeSymbol = -1; public EnumMember(SourceLocation loc, Identifier id, Expression initializer) { super("EnumMember", loc); this.id = id; this.initializer = initializer; } public Identifier getId() { return id; } /** * Returns the initializer expression, or {@code null} if this enum member has no explicit * initializer. */ public Expression getInitializer() { return initializer; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public int getSymbol() { return typeSymbol; } @Override public void setSymbol(int symbol) { this.typeSymbol = symbol; } }
1,037
21.085106
92
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/NamespaceDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; public class NamespaceDeclaration extends Statement implements INodeWithSymbol { private final Identifier name; private final List<Statement> body; private final boolean isInstantiated; private final boolean hasDeclareKeyword; private int symbol = -1; public NamespaceDeclaration( SourceLocation loc, Identifier name, List<Statement> body, boolean isInstantiated, boolean hasDeclareKeyword) { super("NamespaceDeclaration", loc); this.name = name; this.body = body; this.isInstantiated = isInstantiated; this.hasDeclareKeyword = hasDeclareKeyword; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public Identifier getName() { return name; } public List<Statement> getBody() { return body; } /** * Returns whether this is an instantiated namespace. * * <p>Non-instantiated namespaces only contain interface types, type aliases, and other * non-instantiated namespaces. The TypeScript compiler does not emit code for non-instantiated * namespaces. */ public boolean isInstantiated() { return isInstantiated; } public boolean hasDeclareKeyword() { return hasDeclareKeyword; } @Override public int getSymbol() { return this.symbol; } @Override public void setSymbol(int symbol) { this.symbol = symbol; } }
1,593
22.791045
97
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/InterfaceDeclaration.java
package com.semmle.ts.ast; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; import java.util.List; /** A TypeScript interface declaration. */ public class InterfaceDeclaration extends Statement implements INodeWithSymbol { private final Identifier name; private final List<TypeParameter> typeParameters; private final List<ITypeExpression> superInterfaces; private final List<MemberDefinition<?>> body; private int typeSymbol = -1; public InterfaceDeclaration( SourceLocation loc, Identifier name, List<TypeParameter> typeParameters, List<ITypeExpression> superInterfaces, List<MemberDefinition<?>> body) { super("InterfaceDeclaration", loc); this.name = name; this.typeParameters = typeParameters; this.superInterfaces = superInterfaces; this.body = body; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public Identifier getName() { return name; } public List<TypeParameter> getTypeParameters() { return typeParameters; } public boolean hasTypeParameters() { return !typeParameters.isEmpty(); } public List<MemberDefinition<?>> getBody() { return body; } public List<ITypeExpression> getSuperInterfaces() { return superInterfaces; } @Override public int getSymbol() { return typeSymbol; } @Override public void setSymbol(int symbol) { this.typeSymbol = symbol; } }
1,592
23.136364
80
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TypeParameter.java
package com.semmle.ts.ast; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * A type parameter declared on a class, interface, function, or type alias. * * <p>The general form of a type parameter is: <tt>S extends T = U</tt>. */ public class TypeParameter extends TypeExpression { private final Identifier id; private final ITypeExpression bound; private final ITypeExpression default_; public TypeParameter( SourceLocation loc, Identifier id, ITypeExpression bound, ITypeExpression default_) { super("TypeParameter", loc); this.id = id; this.bound = bound; this.default_ = default_; } public Identifier getId() { return id; } /** * Returns the bound on the type parameter, or {@code null} if there is no bound. * * <p>For example, in <tt>T extends Array = number[]</tt> the bound is <tt>Array</tt>. */ public ITypeExpression getBound() { return bound; } /** * Returns the type parameter default, or {@code null} if there is no default, * * <p>For example, in <tt>T extends Array = number[]</tt> the default is <tt>number[]</tt>. */ public ITypeExpression getDefault() { return default_; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
1,348
24.942308
93
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/MappedTypeExpr.java
package com.semmle.ts.ast; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** * A type of form <tt>{ [K in C]: T }</tt>, where <tt>T</tt> is a type that may refer to <tt>K</tt>. * * <p>As with the TypeScript AST, the <tt>K in C</tt> part is represented as a type parameter with * <tt>C</tt> as its upper bound. */ public class MappedTypeExpr extends TypeExpression { private final TypeParameter typeParameter; private final ITypeExpression elementType; public MappedTypeExpr( SourceLocation loc, TypeParameter typeParameter, ITypeExpression elementType) { super("MappedTypeExpr", loc); this.typeParameter = typeParameter; this.elementType = elementType; } public TypeParameter getTypeParameter() { return typeParameter; } public ITypeExpression getElementType() { return elementType; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
963
25.777778
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/ExternalModuleReference.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; public class ExternalModuleReference extends Expression implements INodeWithSymbol { private final Expression expression; private int symbol = -1; public ExternalModuleReference(SourceLocation loc, Expression expression) { super("ExternalModuleReference", loc); this.expression = expression; } public Expression getExpression() { return expression; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } @Override public int getSymbol() { return this.symbol; } @Override public void setSymbol(int symbol) { this.symbol = symbol; } }
766
20.914286
84
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/ast/TypeAssertion.java
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Visitor; /** An expression of form <code>E as T</code> or <code>&lt;T&gt; E</code>. */ public class TypeAssertion extends Expression { private final Expression expression; private final ITypeExpression typeAnnotation; private final boolean isAsExpression; public TypeAssertion( SourceLocation loc, Expression expression, ITypeExpression typeAnnotation, boolean isAsExpression) { super("TypeAssertion", loc); this.expression = expression; this.typeAnnotation = typeAnnotation; this.isAsExpression = isAsExpression; } public Expression getExpression() { return expression; } public ITypeExpression getTypeAnnotation() { return typeAnnotation; } /** * True if this is an assertion of form <tt>E as T</tt>, as opposed to the old syntax <code> * &lt;T&gt; E</code>. */ public boolean isAsExpression() { return isAsExpression; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
1,141
24.377778
94
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/extractor/TypeTable.java
package com.semmle.ts.extractor; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * Holds the output of the <tt>get-type-table</tt> command. * * <p>See documentation in <tt>parser-wrapper/src/type_table.ts</tt>. */ public class TypeTable { private final JsonArray typeStrings; private final JsonArray typeToStringValues; private final JsonObject propertyLookups; private final JsonObject typeAliases; private final JsonArray symbolStrings; private final JsonObject moduleMappings; private final JsonObject globalMappings; private final JsonArray signatureStrings; private final JsonObject signatureMappings; private final JsonArray signatureToStringValues; private final JsonObject stringIndexTypes; private final JsonObject numberIndexTypes; private final JsonObject baseTypes; private final JsonObject selfTypes; public TypeTable(JsonObject typeTable) { this.typeStrings = typeTable.get("typeStrings").getAsJsonArray(); this.typeToStringValues = typeTable.get("typeToStringValues").getAsJsonArray(); this.propertyLookups = typeTable.get("propertyLookups").getAsJsonObject(); this.typeAliases = typeTable.get("typeAliases").getAsJsonObject(); this.symbolStrings = typeTable.get("symbolStrings").getAsJsonArray(); this.moduleMappings = typeTable.get("moduleMappings").getAsJsonObject(); this.globalMappings = typeTable.get("globalMappings").getAsJsonObject(); this.signatureStrings = typeTable.get("signatureStrings").getAsJsonArray(); this.signatureMappings = typeTable.get("signatureMappings").getAsJsonObject(); this.signatureToStringValues = typeTable.get("signatureToStringValues").getAsJsonArray(); this.numberIndexTypes = typeTable.get("numberIndexTypes").getAsJsonObject(); this.stringIndexTypes = typeTable.get("stringIndexTypes").getAsJsonObject(); this.baseTypes = typeTable.get("baseTypes").getAsJsonObject(); this.selfTypes = typeTable.get("selfTypes").getAsJsonObject(); } public String getTypeString(int index) { return typeStrings.get(index).getAsString(); } public String getTypeToStringValue(int index) { return typeToStringValues.get(index).getAsString(); } public JsonObject getPropertyLookups() { return propertyLookups; } public JsonObject getTypeAliases() { return typeAliases; } public int getNumberOfTypes() { return typeStrings.size(); } public String getSymbolString(int index) { return symbolStrings.get(index).getAsString(); } public int getNumberOfSymbols() { return symbolStrings.size(); } public JsonObject getModuleMappings() { return moduleMappings; } public JsonObject getGlobalMappings() { return globalMappings; } public JsonArray getSignatureStrings() { return signatureStrings; } public int getNumberOfSignatures() { return signatureStrings.size(); } public String getSignatureString(int i) { return signatureStrings.get(i).getAsString(); } public JsonObject getSignatureMappings() { return signatureMappings; } public JsonArray getSignatureToStringValues() { return signatureToStringValues; } public String getSignatureToStringValue(int i) { return signatureToStringValues.get(i).getAsString(); } public JsonObject getNumberIndexTypes() { return numberIndexTypes; } public JsonObject getStringIndexTypes() { return stringIndexTypes; } public JsonObject getBaseTypes() { return baseTypes; } public JsonObject getSelfTypes() { return selfTypes; } }
3,577
28.816667
93
java
codeql
codeql-master/javascript/extractor/src/com/semmle/ts/extractor/TypeExtractor.java
package com.semmle.ts.extractor; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.semmle.util.trap.TrapWriter; import com.semmle.util.trap.TrapWriter.Label; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Extracts type and symbol information into TRAP files. * * <p>This is closely coupled with the <tt>type_table.ts</tt> file in the parser-wrapper. Type * strings and symbol strings generated in that file are parsed here. See that file for reference * and documentation. */ public class TypeExtractor { private final TrapWriter trapWriter; private final TypeTable table; private static final Map<String, Integer> tagToKind = new LinkedHashMap<String, Integer>(); private static final int referenceKind = 6; private static final int objectKind = 7; private static final int typevarKind = 8; private static final int typeofKind = 9; private static final int uniqueSymbolKind = 15; private static final int tupleKind = 18; private static final int lexicalTypevarKind = 19; private static final int thisKind = 20; private static final int numberLiteralTypeKind = 21; private static final int stringLiteralTypeKind = 22; private static final int bigintLiteralTypeKind = 25; static { tagToKind.put("any", 0); tagToKind.put("string", 1); tagToKind.put("number", 2); tagToKind.put("union", 3); tagToKind.put("true", 4); tagToKind.put("false", 5); tagToKind.put("reference", referenceKind); tagToKind.put("object", objectKind); tagToKind.put("typevar", typevarKind); tagToKind.put("typeof", typeofKind); tagToKind.put("void", 10); tagToKind.put("undefined", 11); tagToKind.put("null", 12); tagToKind.put("never", 13); tagToKind.put("plainsymbol", 14); tagToKind.put("uniquesymbol", uniqueSymbolKind); tagToKind.put("objectkeyword", 16); tagToKind.put("intersection", 17); tagToKind.put("tuple", tupleKind); tagToKind.put("lextypevar", lexicalTypevarKind); tagToKind.put("this", thisKind); tagToKind.put("numlit", numberLiteralTypeKind); tagToKind.put("strlit", stringLiteralTypeKind); tagToKind.put("unknown", 23); tagToKind.put("bigint", 24); tagToKind.put("bigintlit", bigintLiteralTypeKind); } private static final Map<String, Integer> symbolKind = new LinkedHashMap<String, Integer>(); static { symbolKind.put("root", 0); symbolKind.put("member", 1); symbolKind.put("other", 2); } public TypeExtractor(TrapWriter trapWriter, TypeTable table) { this.trapWriter = trapWriter; this.table = table; } public void extract() { for (int i = 0; i < table.getNumberOfTypes(); ++i) { extractType(i); } extractPropertyLookups(table.getPropertyLookups()); extractTypeAliases(table.getTypeAliases()); for (int i = 0; i < table.getNumberOfSymbols(); ++i) { extractSymbol(i); } extractSymbolNameMapping("symbol_module", table.getModuleMappings()); extractSymbolNameMapping("symbol_global", table.getGlobalMappings()); extractSignatureMappings(table.getSignatureMappings()); for (int i = 0; i < table.getNumberOfSignatures(); ++i) { extractSignature(i); } extractIndexTypeTable(table.getNumberIndexTypes(), "number_index_type"); extractIndexTypeTable(table.getStringIndexTypes(), "string_index_type"); extractBaseTypes(table.getBaseTypes()); extractSelfTypes(table.getSelfTypes()); } private void extractType(int id) { Label lbl = trapWriter.globalID("type;" + id); String contents = table.getTypeString(id); String[] parts = split(contents); int kind = tagToKind.get(parts[0]); trapWriter.addTuple("types", lbl, kind, table.getTypeToStringValue(id)); int firstChild = 1; switch (kind) { case referenceKind: case typevarKind: case typeofKind: case uniqueSymbolKind: { // The first part of a reference is the symbol for name binding. Label symbol = trapWriter.globalID("symbol;" + parts[1]); trapWriter.addTuple("type_symbol", lbl, symbol); ++firstChild; break; } case tupleKind: { // The first two parts denote minimum length and presence of rest element. trapWriter.addTuple("tuple_type_min_length", lbl, Integer.parseInt(parts[1])); if (parts[2].equals("t")) { trapWriter.addTuple("tuple_type_rest", lbl); } firstChild += 2; break; } case objectKind: case lexicalTypevarKind: firstChild = parts.length; // No children. break; case numberLiteralTypeKind: case stringLiteralTypeKind: case bigintLiteralTypeKind: firstChild = parts.length; // No children. // The string value may contain `;` so don't use the split(). String value = contents.substring(parts[0].length() + 1); trapWriter.addTuple("type_literal_value", lbl, value); break; } for (int i = firstChild; i < parts.length; ++i) { Label childLabel = trapWriter.globalID("type;" + parts[i]); trapWriter.addTuple("type_child", childLabel, lbl, i - firstChild); } } private void extractPropertyLookups(JsonObject lookups) { JsonArray baseTypes = lookups.get("baseTypes").getAsJsonArray(); JsonArray names = lookups.get("names").getAsJsonArray(); JsonArray propertyTypes = lookups.get("propertyTypes").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); String name = names.get(i).getAsString(); int propertyType = propertyTypes.get(i).getAsInt(); trapWriter.addTuple( "type_property", trapWriter.globalID("type;" + baseType), name, trapWriter.globalID("type;" + propertyType)); } } private void extractTypeAliases(JsonObject aliases) { JsonArray aliasTypes = aliases.get("aliasTypes").getAsJsonArray(); JsonArray underlyingTypes = aliases.get("underlyingTypes").getAsJsonArray(); for (int i = 0; i < aliasTypes.size(); ++i) { int aliasType = aliasTypes.get(i).getAsInt(); int underlyingType = underlyingTypes.get(i).getAsInt(); trapWriter.addTuple( "type_alias", trapWriter.globalID("type;" + aliasType), trapWriter.globalID("type;" + underlyingType)); } } private void extractSymbol(int index) { // Format is: kind;decl;parent;name String[] parts = split(table.getSymbolString(index), 4); int kind = symbolKind.get(parts[0]); String name = parts[3]; Label label = trapWriter.globalID("symbol;" + index); trapWriter.addTuple("symbols", label, kind, name); String parentStr = parts[2]; if (parentStr.length() > 0) { Label parentLabel = trapWriter.globalID("symbol;" + parentStr); trapWriter.addTuple("symbol_parent", label, parentLabel); } } private void extractSymbolNameMapping(String relationName, JsonObject mappings) { JsonArray symbols = mappings.get("symbols").getAsJsonArray(); JsonArray names = mappings.get("names").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { Label symbol = trapWriter.globalID("symbol;" + symbols.get(i).getAsInt()); String moduleName = names.get(i).getAsString(); trapWriter.addTuple(relationName, symbol, moduleName); } } private void extractSignature(int index) { // Format is: // kind;numTypeParams;requiredParams;restParamType;returnType(;paramName;paramType)* String[] parts = split(table.getSignatureString(index)); Label label = trapWriter.globalID("signature;" + index); int kind = Integer.parseInt(parts[0]); int numberOfTypeParameters = Integer.parseInt(parts[1]); int requiredParameters = Integer.parseInt(parts[2]); String restParamTypeTag = parts[3]; if (!restParamTypeTag.isEmpty()) { trapWriter.addTuple( "signature_rest_parameter", label, trapWriter.globalID("type;" + restParamTypeTag)); } Label returnType = trapWriter.globalID("type;" + parts[4]); trapWriter.addTuple( "signature_types", label, kind, table.getSignatureToStringValue(index), numberOfTypeParameters, requiredParameters); trapWriter.addTuple("signature_contains_type", returnType, label, -1); int numberOfParameters = (parts.length - 5) / 2; // includes type parameters for (int i = 0; i < numberOfParameters; ++i) { int partIndex = 5 + (2 * i); String paramName = parts[partIndex]; String paramTypeId = parts[partIndex + 1]; if (paramTypeId.length() > 0) { // Unconstrained type parameters have an empty type ID. Label paramType = trapWriter.globalID("type;" + parts[partIndex + 1]); trapWriter.addTuple("signature_contains_type", paramType, label, i); } trapWriter.addTuple("signature_parameter_name", label, i, paramName); } } private void extractSignatureMappings(JsonObject mappings) { JsonArray baseTypes = mappings.get("baseTypes").getAsJsonArray(); JsonArray kinds = mappings.get("kinds").getAsJsonArray(); JsonArray indices = mappings.get("indices").getAsJsonArray(); JsonArray signatures = mappings.get("signatures").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); int kind = kinds.get(i).getAsInt(); int index = indices.get(i).getAsInt(); int signatureId = signatures.get(i).getAsInt(); trapWriter.addTuple( "type_contains_signature", trapWriter.globalID("type;" + baseType), kind, index, trapWriter.globalID("signature;" + signatureId)); } } private void extractIndexTypeTable(JsonObject table, String relationName) { JsonArray baseTypes = table.get("baseTypes").getAsJsonArray(); JsonArray propertyTypes = table.get("propertyTypes").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); int propertyType = propertyTypes.get(i).getAsInt(); trapWriter.addTuple( relationName, trapWriter.globalID("type;" + baseType), trapWriter.globalID("type;" + propertyType)); } } private void extractBaseTypes(JsonObject table) { JsonArray symbols = table.get("symbols").getAsJsonArray(); JsonArray baseTypeSymbols = table.get("baseTypeSymbols").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { int symbolId = symbols.get(i).getAsInt(); int baseTypeSymbolId = baseTypeSymbols.get(i).getAsInt(); trapWriter.addTuple( "base_type_names", trapWriter.globalID("symbol;" + symbolId), trapWriter.globalID("symbol;" + baseTypeSymbolId)); } } private void extractSelfTypes(JsonObject table) { JsonArray symbols = table.get("symbols").getAsJsonArray(); JsonArray selfTypes = table.get("selfTypes").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { int symbolId = symbols.get(i).getAsInt(); int typeId = selfTypes.get(i).getAsInt(); trapWriter.addTuple( "self_types", trapWriter.globalID("symbol;" + symbolId), trapWriter.globalID("type;" + typeId)); } } /** Like {@link #split(String)} without a limit. */ private static String[] split(String input) { return split(input, -1); } /** * Splits the input around the semicolon (<code>;</code>) character, preserving all empty * substrings. * * <p>At most <code>limit</code> substrings will be extracted. If the limit is reached, the last * substring will extend to the end of the string, possibly itself containing semicolons. * * <p>Note that the {@link String#split(String)} method does not preserve empty substrings at the * end of the string in case the string ends with a semicolon. */ private static String[] split(String input, int limit) { List<String> result = new ArrayList<String>(); int lastPos = 0; for (int i = 0; i < input.length(); ++i) { if (input.charAt(i) == ';') { result.add(input.substring(lastPos, i)); lastPos = i + 1; if (result.size() == limit - 1) break; } } result.add(input.substring(lastPos)); return result.toArray(EMPTY_STRING_ARRAY); } private static final String[] EMPTY_STRING_ARRAY = new String[0]; }
12,568
37.555215
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/ObjectPattern.java
package com.semmle.js.ast; import java.util.ArrayList; import java.util.List; /** An object pattern. */ public class ObjectPattern extends Expression implements DestructuringPattern { private final List<Property> rawProperties, properties; private final Expression restPattern; public ObjectPattern(SourceLocation loc, List<Property> properties) { super("ObjectPattern", loc); this.rawProperties = properties; this.properties = new ArrayList<Property>(properties.size()); Expression rest = null; for (Property prop : properties) { Expression val = prop.getValue(); if (val instanceof RestElement) { rest = ((RestElement) val).getArgument(); } else { this.properties.add(prop); } } this.restPattern = rest; } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } /** The property patterns in this literal. */ public List<Property> getProperties() { return properties; } /** Does this object pattern have a rest pattern? */ public boolean hasRest() { return restPattern != null; } /** The rest pattern of this literal, if any. */ public Expression getRest() { return restPattern; } /** * The raw property patterns in this literal; the rest pattern (if any) is represented as a {@link * RestElement}. */ public List<Property> getRawProperties() { return rawProperties; } }
1,443
25.254545
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/Property.java
package com.semmle.js.ast; import com.semmle.util.data.StringUtil; import java.util.ArrayList; import java.util.List; /** * A property in an object literal or an object pattern. * * <p>This includes both regular properties as well as accessor properties, method properties, * properties with computed names, and spread/rest properties. */ public class Property extends Node { public static enum Kind { /** Either a normal property or a spread/rest property. */ INIT(false), /** Getter property. */ GET(true), /** Setter property. */ SET(true); public final boolean isAccessor; private Kind(boolean isAccessor) { this.isAccessor = isAccessor; } }; private final Expression key; private final Expression value, rawValue; private final Expression defaultValue; // only applies to property patterns private final Kind kind; private final boolean computed, method; private final List<Decorator> decorators; public Property( SourceLocation loc, Expression key, Expression rawValue, String kind, Boolean computed, Boolean method) { super("Property", loc); this.key = key; if (rawValue instanceof AssignmentPattern) { AssignmentPattern ap = (AssignmentPattern) rawValue; if (ap.getLeft() == key) rawValue = ap = new AssignmentPattern( ap.getLoc(), ap.getOperator(), new NodeCopier().copy(key), ap.getRight()); this.value = ap.getLeft(); this.defaultValue = ap.getRight(); } else { this.value = rawValue == key ? new NodeCopier().copy(rawValue) : rawValue; this.defaultValue = null; } this.rawValue = rawValue; this.kind = Kind.valueOf(StringUtil.uc(kind)); this.computed = computed == Boolean.TRUE; this.method = method == Boolean.TRUE; this.decorators = new ArrayList<Decorator>(); } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } /** * The key of this property; usually a {@link Literal} or an {@link Identifier}, but may be an * arbitrary expression for properties with computed names. For spread/rest properties this method * returns {@code null}. */ public Expression getKey() { return key; } /** The value expression of this property. */ public Expression getValue() { return value; } /** The default value of this property pattern. */ public Expression getDefaultValue() { return defaultValue; } /** Is this a property pattern with a default value? */ public boolean hasDefaultValue() { return defaultValue != null; } /** The kind of this property. */ public Kind getKind() { return kind; } /** Is the name of this property computed? */ public boolean isComputed() { return computed; } /** Is this property declared using method syntax? */ public boolean isMethod() { return method; } /** Is this property declared using shorthand syntax? */ public boolean isShorthand() { return key != null && key.getLoc().equals(value.getLoc()); } /** * The raw value expression of this property; if this property is a property pattern with a * default value, this method returns an {@link AssignmentPattern}. */ public Expression getRawValue() { return rawValue; } public void addDecorators(List<Decorator> decorators) { this.decorators.addAll(decorators); } public List<Decorator> getDecorators() { return this.decorators; } }
3,543
25.848485
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/TemplateElement.java
package com.semmle.js.ast; /** An element in a template literal. */ public class TemplateElement extends Expression { private final Object cooked; private final String raw; private final boolean tail; public TemplateElement(SourceLocation loc, Object cooked, String raw, Boolean tail) { super("TemplateElement", loc); this.cooked = cooked; this.raw = raw; this.tail = tail == Boolean.TRUE; } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } /** The "cooked" value of the template element. */ public Object getCooked() { return cooked; } /** The raw value of the template element. */ public String getRaw() { return raw; } /** Is this the tail element? */ public boolean isTail() { return tail; } }
805
21.388889
87
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/BinaryExpression.java
package com.semmle.js.ast; /** A binary expression such as <code>x + y</code>. */ public class BinaryExpression extends ABinaryExpression { public BinaryExpression(SourceLocation loc, String operator, Expression left, Expression right) { super(loc, "BinaryExpression", operator, left, right); } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } }
401
27.714286
99
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/ClassDeclaration.java
package com.semmle.js.ast; import com.semmle.ts.ast.ITypeExpression; import com.semmle.ts.ast.TypeParameter; import java.util.Collections; import java.util.List; /** * A class declaration such as * * <pre> * class ColouredPoint extends Point { * constructor(x, y, colour) { * super(x, y); * this.colour = colour; * } * } * </pre> */ public class ClassDeclaration extends Statement { private final AClass klass; private final boolean hasDeclareKeyword; private final boolean hasAbstractKeyword; public ClassDeclaration( SourceLocation loc, Identifier id, Expression superClass, ClassBody body) { this(loc, id, Collections.emptyList(), superClass, Collections.emptyList(), body, false, false); } public ClassDeclaration( SourceLocation loc, Identifier id, List<TypeParameter> typeParameters, Expression superClass, List<ITypeExpression> superInterfaces, ClassBody body, boolean hasDeclareKeyword, boolean hasAbstractKeyword) { this( loc, new AClass(id, typeParameters, superClass, superInterfaces, body), hasDeclareKeyword, hasAbstractKeyword); } public ClassDeclaration( SourceLocation loc, AClass klass, boolean hasDeclareKeyword, boolean hasAbstractKeyword) { super("ClassDeclaration", loc); this.klass = klass; this.hasDeclareKeyword = hasDeclareKeyword; this.hasAbstractKeyword = hasAbstractKeyword; } public AClass getClassDef() { return klass; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } public void addDecorators(List<Decorator> decorators) { klass.addDecorators(decorators); } public List<Decorator> getDecorators() { return klass.getDecorators(); } public boolean hasDeclareKeyword() { return hasDeclareKeyword; } public boolean hasAbstractKeyword() { return hasAbstractKeyword; } }
1,951
23.708861
100
java
codeql
codeql-master/javascript/extractor/src/com/semmle/js/ast/TryStatement.java
package com.semmle.js.ast; import java.util.ArrayList; import java.util.List; /** A try statement. */ public class TryStatement extends Statement { private final BlockStatement block; private final CatchClause handler; private final List<CatchClause> guardedHandlers, allHandlers; private final BlockStatement finalizer; public TryStatement( SourceLocation loc, BlockStatement block, CatchClause handler, List<CatchClause> guardedHandlers, BlockStatement finalizer) { super("TryStatement", loc); this.block = block; this.handler = handler; this.guardedHandlers = guardedHandlers; this.finalizer = finalizer; this.allHandlers = new ArrayList<CatchClause>(); if (guardedHandlers != null) this.allHandlers.addAll(guardedHandlers); if (handler != null) this.allHandlers.add(handler); } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } /** The body of this try statement. */ public BlockStatement getBlock() { return block; } /** The (single unguarded) catch clause of this try statement; may be null. */ public CatchClause getHandler() { return handler; } /** The guarded catch clauses of this try statement. */ public List<CatchClause> getGuardedHandlers() { return guardedHandlers; } /** The finally block of this try statement; may be null. */ public BlockStatement getFinalizer() { return finalizer; } /** All catch clauses (both guarded and unguarded) of this try statement in lexical order. */ public List<CatchClause> getAllHandlers() { return allHandlers; } /** Does this try statement have a finally block? */ public boolean hasFinalizer() { return finalizer != null; } /** Does this try statement have an unguarded catch block? */ public boolean hasHandler() { return handler != null; } }
1,895
26.478261
95
java