/** * Performs unit analysis of a given infix operation. The first unit (non-scalar token) * encountered is returned, except with division. In that case, scalar is returned if both units * are the same and points is returned when dividing inches and points. * * @param u1 left-hand unit * @param u2 right-hand unit * @param op operator * @return Token containing resultant unit. */ public static ValueType evaluateUnits(ValueType u1, ValueType u2, Token op) { String unit = "SCALAR"; // default ValueType final String left = u1.toString(); final String right = u2.toString(); switch (op.text) { case "/": // In the case of division, we need only to be concerned in situations where // the final unit is not scalar if (!u1.toString().equals(right)) { if (left.equals("SCALAR")) { unit = right; break; } if (right.equals("SCALAR")) { unit = left; break; } } break; default: if (left.equals("SCALAR")) { unit = right; break; } if (right.equals("SCALAR")) { unit = left; break; } unit = left; break; } return ValueType.valueOf(unit); }
private void checkStyleConflicts(ValueType type, Protoclass protoclass) { if (protoclass.features().prehash() && protoclass.styles().style().privateNoargConstructor()) { protoclass .report() .annotationNamed(ImmutableMirror.simpleName()) .warning( "'prehash' feature is automatically disabled when 'privateNoargConstructor' style is turned on"); } if (type.isUseConstructor() && protoclass.constitution().factoryOf().isNew()) { if (type.isUseValidation()) { protoclass .report() .annotationNamed(ImmutableMirror.simpleName()) .error( "interning, singleton and validation will not work correctly with 'new' constructor configured in style"); } else if (type.constitution.isImplementationHidden() && (type.kind().isEnclosing() || type.kind().isNested())) { protoclass .report() .annotationNamed(ImmutableMirror.simpleName()) .error( "Enclosing with hidden implementation do not mix with 'new' constructor configured in style"); } } }
public void newValueType(String domainName, ValueType valueType) { if (domainName == null) { domainName = valueType.getFullname(); } valueType.getBaseType().setDomainName(domainName); checkValueTypeName(domainName); valueTypes.put(domainName, valueType); }
@Override public String getValue() { StringBuilder sb = new StringBuilder(); for (ValueType s : this.strings) { sb.append(s.getValue()).append(this.separator); } return sb.toString(); }
private static ValueType valueTypeOf(final String className) { for (ValueType t : ValueType.values()) { if (t.name().equals(className)) { return t; } } return null; }
private void setgup(double g) { DataType dt = new DataType(); ValueType val = new ValueType(); val.setValue(g); val.setUnits("unitless"); dt.setValue(val); andtup.setLandeFactor(dt); }
private void setEup(double Ep) { DataType dt = new DataType(); ValueType val = new ValueType(); val.setValue(Ep); val.setUnits("cm-1"); dt.setValue(val); andtup.setStateEnergy(dt); }
private void setProbability(double loggf) { DataType dt = new DataType(); ValueType val = new ValueType(); val.setValue(loggf); val.setUnits("unitless"); dt.setValue(val); rtp.setLog10WeightedOscillatorStregnth(dt); }
public static ValueType getTypeCode(byte opbyte) { if ((opbyte < 0) || (opbyte > ValueType.values().length - 1)) { logger.error("Unknown op value: {}", opbyte); throw new IllegalValueException("Unknown op value: " + opbyte); } ValueType code = ValueType.values()[opbyte]; return code; }
private void setWavelength(double lam) { EnergyWavelengthType ewl = new EnergyWavelengthType(); WavelengthWavenumberType wl = new WavelengthWavenumberType(); DataType dt = new DataType(); ValueType val = new ValueType(); val.setValue(lam); val.setUnits("A"); dt.setValue(val); wl.setRitz(dt); ewl.setWavelength(wl); rt.setEnergyWavelength(ewl); }
void collapse(ECR e1, ECR e2) { ECR root = join(e1, e2); // Parent is stored at the points-to loc of Parent parent = getType(root).getParent(); Collection<ECR> parentECRs = ImmutableList.copyOf(parent.getECRs()); for (ECR ecr : parentECRs) { ValueType ecrType = getType(ecr); if (ecrType.isStruct()) collapseStruct(ecr, ecrType.asStruct()); } enableOp(root); }
@Override public void saveTo(XMLNode node) { XMLNode n = new XMLNode(XMLTypeName); n.setString("name", name); data.saveTo(n); node.addChild(n); }
public Attribute(String s, String s1, String s2, ValueType valuetype) { attributeValue = new JSONObject(); sessionId = s; attributeName = s1; attributeType = s2; attributeValue = valuetype.toJSON(); }
JsonObject build() { entryMap.forEach( (name, value) -> { ValueType type = ValueType.valueOf(value.getClass()); switch (type) { case JsonObjectBuilder: jsonObjectBuilder.add(name, ((JsonObjectBuilder) value).build()); break; case JsonArrayBuilder: jsonObjectBuilder.add(name, ((JsonArrayBuilder) value).build()); break; case BigDecimal: jsonObjectBuilder.add(name, (BigDecimal) value); break; case Integer: jsonObjectBuilder.add(name, (Integer) value); break; case JsonObject: jsonObjectBuilder.add(name, (JsonObject) value); break; case Boolean: jsonObjectBuilder.add(name, (Boolean) value); break; default: jsonObjectBuilder.add(name, String.valueOf(value)); } }); return jsonObjectBuilder.build(); }
@Override public void setValueUnchecked(Object t) { if (getType().isInstance(t)) { data.setValue(getType().cast(t)); return; } throw new RuntimeException("WRONG TYPE!!"); }
void ensureSimple(ECR e) { ValueType type = getType(e); switch (type.getKind()) { case BOTTOM: { ValueType simType = ValueType.simple(createBottomLocFunc(), Size.getBot(), Parent.getBottom()); setType(e, simType); return; } case BLANK: { BlankType blankType = type.asBlank(); ValueType simType = ValueType.simple(createBottomLocFunc(), blankType.getSize(), blankType.getParent()); setType(e, simType); return; } case SIMPLE: { return; } case STRUCT: { collapseStruct(e, type.asStruct()); return; } default: // lambda throw new IllegalArgumentException("Invalid type " + type.getKind()); } }
@Override public void loadFrom(XMLNode node) { XMLNode[] children = node.getChildByName(XMLTypeName); for (XMLNode child : children) { if (child.getString("name").equalsIgnoreCase(name)) continue; data.loadFrom(child); return; } }
public static boolean isNullableType(ValueType vt) { String vtFullName = vt.getFullname(); for (String nonNullableType : NON_NULLABLE_TYPES) { if (nonNullableType.equals(vtFullName)) { return false; } } return true; }
@Override public void visit(CloneArrayInstruction insn) { MethodDescriptor cloneMethodDesc = new MethodDescriptor("clone", ValueType.object("java.lang.Object")); MethodReference cloneMethod = new MethodReference("java.lang.Object", cloneMethodDesc); assign( Expr.invoke(cloneMethod, Expr.var(insn.getArray().getIndex()), new Expr[0]), insn.getReceiver()); }
// array: the array of unknown class to write as XML private void writeArray(Object array) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, SecurityException { final int length = Array.getLength(array); this.driver.startElement(DTD.ELEMENT_ARRAY); this.driver.setAttribute(DTD.ATTRIBUTE_LENGTH, Integer.toString(length)); final ValueType pvt = ValueType.ofPrimitive(array.getClass().getComponentType()); if (pvt != null) { // primitives array: for (int i = 0; i < length; i++) { pvt.getWriteArrayItem(this.driver, array, i, false); } } else { // objects array: final Object[] objArray = (Object[]) array; for (int i = 0; i < length; i++) { this.write0(objArray[i]); } } this.driver.endElement(); }
/** * Swap <code>t1</code> and <code>t2</code> if <code> kind(t1) > kind(t2) * </code> * * @param t1 * @param t2 * @return the pair of value types <code>(t1', t2')</code> that <code>kind(t1') <= kind(t2') * </code> */ private Pair<ValueType, ValueType> swap(ValueType t1, ValueType t2) { if (t1.isBottom()) return Pair.of(t1, t2); if (t2.isBottom()) return Pair.of(t2, t1); if (t1.isLambda()) { assert t2.isLambda(); return Pair.of(t1, t2); } if (t2.isLambda()) { assert t1.isLambda(); return Pair.of(t1, t2); } ValueTypeKind kind1 = t1.getKind(); ValueTypeKind kind2 = t2.getKind(); switch (kind1) { case BOTTOM: return Pair.of(t1, t2); case BLANK: switch (kind2) { case BOTTOM: case BLANK: return Pair.of(t2, t1); default: return Pair.of(t1, t2); } case SIMPLE: switch (kind2) { case BLANK: case BOTTOM: case SIMPLE: return Pair.of(t2, t1); default: return Pair.of(t1, t2); } default: // case STRUCT: switch (kind2) { case BLANK: case BOTTOM: case SIMPLE: case STRUCT: return Pair.of(t2, t1); default: return Pair.of(t1, t2); } } }
/** * Check if one of <code>e1</code> or <code>e2</code> is a struct, and the other is either object * or simple, collapse the one with struct type * * @param e1 * @param e2 */ private void checkStructCollapse(ECR e1, ECR e2) { ValueType t1 = getType(e1); ValueType t2 = getType(e2); if (t2.isStruct() && t1.isSimple()) { collapseStruct(e2, t2.asStruct()); return; } if (t1.isStruct() && t2.isSimple()) { collapseStruct(e1, t1.asStruct()); return; } return; }
private List<Variable> parseArguments( SimpleDartWithArraysParser.FunctionDeclarationContext function) { List<Variable> args = new ArrayList<>(); SimpleDartWithArraysParser.VariableListContext variableListContext = function.functionParameters().variableList(); if (variableListContext != null) { for (SimpleDartWithArraysParser.VariableContext argContext : variableListContext.variable()) { String argName = argContext.IDENT().getText(); ValueType argValueType = ValueType.fromString(argContext.variableType().getText()); Variable arg = new VariableImpl(argName, argValueType); args.add(arg); } } return args; }
private List<Instruction> transformInvoke(InvokeInstruction insn) { if (insn.getType() != InvocationType.VIRTUAL) { return null; } MethodReference method = insn.getMethod(); if (method.getClassName().equals(ResourceArray.class.getName()) || method.getClassName().equals(ResourceMap.class.getName())) { if (method.getName().equals("keys")) { return transformKeys(insn); } InvokeInstruction accessInsn = new InvokeInstruction(); accessInsn.setType(InvocationType.SPECIAL); ValueType[] types = new ValueType[method.getDescriptor().parameterCount() + 2]; types[0] = ValueType.object("java.lang.Object"); System.arraycopy( method.getDescriptor().getSignature(), 0, types, 1, method.getDescriptor().parameterCount() + 1); accessInsn.setMethod( new MethodReference(ResourceAccessor.class.getName(), method.getName(), types)); accessInsn.getArguments().add(insn.getInstance()); accessInsn.getArguments().addAll(insn.getArguments()); accessInsn.setReceiver(insn.getReceiver()); return Arrays.asList(accessInsn); } ClassReader iface = innerSource.get(method.getClassName()); if (iface == null || !innerSource.isSuperType(Resource.class.getName(), iface.getName()).orElse(false)) { return null; } if (method.getName().startsWith("get")) { if (method.getName().length() > 3) { return transformGetterInvocation(insn, getPropertyName(method.getName().substring(3))); } } else if (method.getName().startsWith("is")) { if (method.getName().length() > 2) { return transformGetterInvocation(insn, getPropertyName(method.getName().substring(2))); } } else if (method.getName().startsWith("set")) { if (method.getName().length() > 3) { return transformSetterInvocation(insn, getPropertyName(method.getName().substring(3))); } } return null; }
private void checkConstructability(ValueType type) { if (!type.isUseBuilder() || type.isUseConstructor()) { for (ValueAttribute a : type.getConstructorExcluded()) { if (a.isMandatory()) { a.report() .error( "Attribute '%s' is mandatory and should be a constructor" + " @Value.Parameter when builder is disabled or" + " there are other constructor parameters", a.name()); } } } if (!type.isUseBuilder() && !type.isUseCopyMethods()) { for (ValueAttribute a : type.getConstructorExcluded()) { if (!a.isMandatory()) { a.report() .warning( "There is no way to initialize '%s' attribute to non-default value." + " Enable builder=true or copy=true or add it as a constructor @Value.Parameter", a.name()); } } } if (type.isUseSingleton() && !type.getMandatoryAttributes().isEmpty()) { for (ValueAttribute a : type.getMandatoryAttributes()) { if (a.isMandatory()) { a.report() .error( "Attribute '%s' is mandatory and cannot be used with singleton enabled." + " Singleton instance require all attributes to have default value, otherwise" + " default instance could not be created", a.name()); } } } }
void clearPointerArithmetic() { if (ptrAriJoins.isEmpty()) return; for (Entry<Pair<ECR, Long>, Pair<ECR, Long>> cell : ptrAriJoins.entrySet()) { ECR resECR = findRoot(cell.getKey().fst()); final ECR origECR = findRoot(cell.getValue().fst()); long shift = cell.getValue().snd(); if (shift >= 0) { // TODO: could do more precise analysis here. collapse(origECR, resECR); continue; } ValueType origType = getType(origECR); Parent parent = origType.getParent(); if (parent.getECRs().isEmpty()) { // TODO: could do more precise analysis here. collapse(origECR, resECR); continue; } for (ECR parentECR : parent.getECRs()) { ValueType parentType = getType(parentECR); if (!parentType.isStruct()) { IOUtils.errPrinter().pln("WARNING: non-struct parent"); join(parentECR, origECR); continue; } Map<Range<Long>, ECR> fieldMap = parentType.asStruct().getFieldMap().asMapOfRanges(); Entry<Range<Long>, ECR> fieldRange = Iterables.find( fieldMap.entrySet(), new Predicate<Entry<Range<Long>, ECR>>() { @Override public boolean apply(Entry<Range<Long>, ECR> input) { return origECR.equals(getLoc(input.getValue())); } }); long low = fieldRange.getKey().lowerEndpoint() + shift; Size parentSize = parentType.getSize(); long size = cell.getKey().snd(); if (low == 0 && (parentSize.isBottom() || parentSize.isNumber() && parentSize.getValue() == size)) { join(parentECR, resECR); continue; } collapse(origECR, resECR); } } }
public <V> V parseContent(ValueType<V> valueType) throws IllegalStateException, NullPointerException, StaxNavException { if (valueType == null) { throw new NullPointerException(); } Entry element = current; String content = element.getElement().getContent(true); if (content == null) { throw new IllegalStateException("No content available for parsing"); } try { return valueType.parse(content); } catch (Exception e) { if (e instanceof TypeConversionException) { throw (TypeConversionException) e; } else { throw new TypeConversionException( element.getElement().getLocation(), e, "Could not parse string value " + content); } } }
static TypeInfo of(FieldValueMetaData fieldValueMetaData, Map<String, String> docStrings) { if (fieldValueMetaData instanceof StructMetaData) { return StructInfo.of((StructMetaData) fieldValueMetaData, docStrings); } if (fieldValueMetaData instanceof EnumMetaData) { return EnumInfo.of((EnumMetaData) fieldValueMetaData, docStrings); } if (fieldValueMetaData instanceof ListMetaData) { return ListInfo.of((ListMetaData) fieldValueMetaData, docStrings); } if (fieldValueMetaData instanceof SetMetaData) { return SetInfo.of((SetMetaData) fieldValueMetaData, docStrings); } if (fieldValueMetaData instanceof MapMetaData) { return MapInfo.of((MapMetaData) fieldValueMetaData, docStrings); } return new TypeInfo(ValueType.of(fieldValueMetaData.type), fieldValueMetaData.isBinary()); }
ValueType compose(Protoclass protoclass) { ValueType type = new ValueType(); type.round = round; type.typeMoreObjects = typeMoreObjects; type.element = protoclass.sourceElement(); type.immutableFeatures = protoclass.features(); type.constitution = protoclass.constitution(); if (protoclass.kind().isFactory()) { new FactoryMethodAttributesCollector(protoclass, type).collect(); } else if (protoclass.kind().isValue() || protoclass.kind().isModifiable()) { Collection<String> violations = Lists.newArrayList(); // This check is legacy, most such checks should have been done on a higher level? if (checkAbstractValueType(type.element, violations)) { if (protoclass.kind().isValue()) { // essentially skip checks if only kind().isModifiable() and not kind().isValue() checkForMutableFields(protoclass, (TypeElement) type.element); checkForTypeHierarchy(protoclass, type); } new AccessorAttributesCollector(protoclass, type).collect(); } else { protoclass .report() .error( "Value type '%s' %s", protoclass.sourceElement().getSimpleName(), Joiner.on(", ").join(violations)); // Do nothing now. kind of way to less blow things up when it happens. } type.detectSerialization(); } checkAttributeNamesIllegalCharacters(type); checkAttributeNamesForDuplicates(type, protoclass); checkConstructability(type); checkStyleConflicts(type, protoclass); return type; }
/** * Collapse <code>structECR</code> by merge it with all its element ECRs, and set its type as the * cell type (simple type might with top size) * * @param structECR * @param structT * @param ECRCache avoid structure cycle * @return */ private ValueType collapseStruct(ECR structECR, StructType structT, Collection<ECR> ECRCache) { // Ensure collapsed type to be simple ValueType unionType = null; // join components Collection<ECR> elems = structT.getFieldMap().asMapOfRanges().values(); Collection<ECR> cjoins = Sets.newHashSet(); Collection<Pair<Size, ECR>> ccjoins = Sets.newHashSet(); for (ECR elem : elems) { ECR elemLoc = getLoc(elem); ValueType elemLocType = getType(elemLoc); Parent parent = elemLocType.getParent().removeECR(structECR); elemLocType.setParent(parent); if (!ECRCache.add(elemLoc)) continue; // ECRCache has elemLoc cjoins.addAll(getCjoins(elemLoc)); elemLoc.clearCCjoins(ccjoins); ccjoins.addAll(getCCjoins(elemLoc)); elemLoc.clearCCjoins(ccjoins); if (elemLocType.isStruct()) { elemLocType = collapseStruct(elemLoc, elemLocType.asStruct(), ECRCache); } union(structECR, elemLoc); unionType = unionType == null ? elemLocType : unify(unionType, elemLocType); } unionType = unionType == null ? ValueType.bottom() : unionType; setType(structECR, unionType); ECR root = findRoot(structECR); for (Pair<Size, ECR> cjoinPair : ccjoins) ccjoin(cjoinPair.fst(), root, cjoinPair.snd()); for (ECR joinECR : cjoins) cjoin(root, joinECR); return unionType; }