From 4f1362364f79c5c4ddae623de15062e31f096105 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 4 Oct 2023 18:48:16 +0200 Subject: [PATCH 001/174] WIP: startet changing types for stainless (option, none, some from stainless instead of scala types) --- .../src/main/scala/asn1scala/asn1jvm.scala | 2 +- .../scala/asn1scala/asn1jvm_encoding.scala | 118 ++++----- .../asn1scala/asn1jvm_encoding_acn.scala | 244 +++++++++--------- .../asn1scala/asn1jvm_encoding_uper.scala | 22 +- 4 files changed, 194 insertions(+), 192 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 26b5179ca..84c946a3e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -1,6 +1,6 @@ package asn1scala -import stainless.lang.{None, Option => _, _} +import stainless.lang.{None => None, Option => Option, _} // type used in ErrorCases type ErrorCode = Int diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 6e45e0ac9..1fda417e1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1,6 +1,6 @@ package asn1scala -import stainless.lang.{None => _, Option => _, Some => _, _} +import stainless.lang.{None => None, Option => Option, Some => Some, _} val masks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 @@ -61,7 +61,7 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), 0, 0, None, None) + BitStream(Array.fill(count)(0), 0, 0, None(), None()) } def BitStream_Init2(count: Int, fetchDataPrm: Option[Any], pushDataPrm: Option[Any]): BitStream = { @@ -73,8 +73,8 @@ def BitStream_AttachBuffer(pBitStrm: BitStream, buf: Array[UByte]): Unit = { pBitStrm.buf = buf // TODO: fix illegal aliasing pBitStrm.currentByte = 0 pBitStrm.currentBit = 0 - pBitStrm.pushDataPrm = None - pBitStrm.fetchDataPrm = None + pBitStrm.pushDataPrm = None() + pBitStrm.fetchDataPrm = None() } def BitStream_AttachBuffer2(pBitStrm: BitStream, buf: Array[UByte], fetchDataPrm: Option[Any], pushDataPrm: Option[Any]): Unit = { @@ -222,7 +222,7 @@ def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then Some(ret) else - None + None() } def BitStream_PeekBit(pBitStrm: BitStream): Boolean = { @@ -359,7 +359,7 @@ def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then Some(v) else - None + None() } def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): Option[Array[UByte]] = { @@ -369,7 +369,7 @@ def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): Option[Array[UBy val ncb: UByte = (8 - cb).toByte if (pBitStrm.currentByte+arr_len).toLong*8 + cb.toInt > pBitStrm.buf.length.toLong*8 then - return None + return None() var i: Int = 0 while i < arr_len do @@ -389,11 +389,11 @@ def BitStream_ReadBits(pBitStrm: BitStream, nbits: Int): Option[Array[UByte]] = var ret: Boolean = false BitStream_DecodeOctetString_no_length(pBitStrm, bytesToRead) match - case None => return None + case None() => return None() case Some(arr) => if remainingBits > 0 then BitStream_ReadPartialByte(pBitStrm, remainingBits) match - case None => None + case None() => None() case Some(ub) => arr(bytesToRead) = ub arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte Some(arr) @@ -475,7 +475,7 @@ def BitStream_ReadPartialByte(pBitStrm: BitStream, nbits: UByte): Option[UByte] if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then Some(v) else - None + None() } @@ -535,7 +535,7 @@ def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): v = v << 8 BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) // will be casted to an Int -1 (1111 ... 1111) @@ -546,7 +546,7 @@ def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): if nBits != 0 then v = v << nBits BitStream_ReadPartialByte(pBitStrm, nBits.toByte) match - case None => return None + case None() => return None() case Some(ub) => v = v | (ub & 0xFF) Some(v) @@ -573,7 +573,7 @@ def BitStream_DecodeNonNegativeInteger(pBitStrm: BitStream, nBits: Int): Option[ // if WORD_SIZE == 8 then if nBits <= 32 then BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, nBits) match - case None => return None + case None() => return None() case Some(lo) => return Some(lo & 0xFFFFFFFFL) @@ -586,7 +586,7 @@ def BitStream_DecodeNonNegativeInteger(pBitStrm: BitStream, nBits: Int): Option[ v = v << nBits - 32L v |= lo & 0xFFFFFFFFL return Some(v) - case _ => return None + case _ => return None() //else // return BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, v, nBits) } @@ -744,7 +744,7 @@ def BitStream_DecodeConstraintWholeNumber(pBitStrm: BitStream, min: Long, max: L val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None => return None + case None() => return None() case Some(ul) => return Some(ul + min) } @@ -752,7 +752,7 @@ def BitStream_DecodeConstraintWholeNumber(pBitStrm: BitStream, min: Long, max: L def BitStream_DecodeConstraintWholeNumberByte(pBitStrm: BitStream, min: Byte, max: Byte): Option[Byte] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toByte) } @@ -760,7 +760,7 @@ def BitStream_DecodeConstraintWholeNumberByte(pBitStrm: BitStream, min: Byte, ma def BitStream_DecodeConstraintWholeNumberShort(pBitStrm: BitStream, min: Short, max: Short): Option[Short] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toShort) } @@ -768,7 +768,7 @@ def BitStream_DecodeConstraintWholeNumberShort(pBitStrm: BitStream, min: Short, def BitStream_DecodeConstraintWholeNumberInt(pBitStrm: BitStream, min: Int, max: Int): Option[Int] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toInt) } @@ -776,7 +776,7 @@ def BitStream_DecodeConstraintWholeNumberInt(pBitStrm: BitStream, min: Int, max: def BitStream_DecodeConstraintWholeNumberUByte(pBitStrm: BitStream, min: UByte, max: UByte): Option[UByte] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toByte) } @@ -784,7 +784,7 @@ def BitStream_DecodeConstraintWholeNumberUByte(pBitStrm: BitStream, min: UByte, def BitStream_DecodeConstraintWholeNumberUShort(pBitStrm: BitStream, min: UShort, max: UShort): Option[UShort] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toShort) } @@ -792,7 +792,7 @@ def BitStream_DecodeConstraintWholeNumberUShort(pBitStrm: BitStream, min: UShort def BitStream_DecodeConstraintWholeNumberUInt(pBitStrm: BitStream, min: UInt, max: UInt): Option[UInt] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None => None + case None() => None() case Some(l) => Some(l.toInt) } @@ -810,7 +810,7 @@ def BitStream_DecodeConstraintPosWholeNumber(pBitStrm: BitStream, min: ULong, ma val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None => None + case None() => None() case Some(uv) => Some(uv + min) else val max_b = scala.math.BigInt(max.toBinaryString, 2) @@ -825,7 +825,7 @@ def BitStream_DecodeConstraintPosWholeNumber(pBitStrm: BitStream, min: ULong, ma val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range_b.toLong) BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None => None + case None() => None() case Some(uv) => Some(uv + min_b.toLong) } @@ -862,7 +862,7 @@ def BitStream_DecodeSemiConstraintWholeNumber(pBitStrm:BitStream, min: Long): Op var v: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None => return None + case None() => return None() case Some(l) => nBytes = l var i: Long = 0 @@ -870,7 +870,7 @@ def BitStream_DecodeSemiConstraintWholeNumber(pBitStrm:BitStream, min: Long): Op decreases(nBytes - i) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong i += 1 @@ -886,7 +886,7 @@ def BitStream_DecodeSemiConstraintPosWholeNumber(pBitStrm:BitStream, min: ULong) var nBytes: Long = 0 var v: ULong = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None => return None + case None() => return None() case Some(l) => nBytes = l var i: Long = 0 @@ -894,7 +894,7 @@ def BitStream_DecodeSemiConstraintPosWholeNumber(pBitStrm:BitStream, min: ULong) decreases(nBytes - i) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong i += 1 @@ -923,7 +923,7 @@ def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = var nBytes: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None => return None + case None() => return None() case Some(l) => nBytes = l val valIsNegative: Boolean = BitStream_PeekBit(pBitStrm) @@ -935,7 +935,7 @@ def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = decreases(nBytes - i) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong i += 1 @@ -1060,13 +1060,13 @@ def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { def BitStream_DecodeReal(pBitStrm: BitStream): Option[Double] = { BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(length) => if length == 0 then return Some(0.0) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(header) => if header == 0x40 then return Some(Double.PositiveInfinity) @@ -1102,7 +1102,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt val expLen: Int = ((header & 0x03) + 1).toInt if expLen > length then - return None + return None() val expIsNegative = BitStream_PeekBit(pBitStrm) var exponent: Int = if expIsNegative then 0xFFFFFFFF else 0 @@ -1112,7 +1112,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt decreases(expLen - i) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) i += 1 @@ -1124,7 +1124,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt decreases(length - j) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => N = N << 8 | (ub.toInt & 0xFF) j += 1 @@ -1152,7 +1152,7 @@ def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern decreases(bit_terminated_pattern_size_in_bits) BitStream_ReadByte(pBitStrm) match - case None => return 0 + case None() => return 0 case Some(ub) => tmp_byte = ub bit_terminated_pattern_size_in_bits = 8 @@ -1164,7 +1164,7 @@ def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern if bit_terminated_pattern_size_in_bits > 0 then BitStream_ReadPartialByte(pBitStrm, bit_terminated_pattern_size_in_bits) match - case None => return 0 + case None() => return 0 case Some(ub) => tmp_byte = ub tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte @@ -1189,7 +1189,7 @@ def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_patter while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do decreases(nMaxReadBits - bitsRead) BitStream_ReadBit(pBitStrm) match - case None => return None + case None() => return None() case Some(bitVal) => BitStream_AppendBit(tmpStrm, bitVal) bitsRead += 1 @@ -1201,7 +1201,7 @@ def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_patter checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) if checkBitPatternPresentResult != 2 then - return None + return None() return Some((tmpStrm.buf, bitsRead)) } @@ -1269,7 +1269,7 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt // //#else if pBitStrm.currentByte + nCount > pBitStrm.buf.length then - return None + return None() //memcpy(arr, pBitStrm.buf(pBitStrm.currentByte), nCount) pBitStrm.buf.slice(pBitStrm.currentByte, pBitStrm.currentByte+nCount).copyToArray(arr) @@ -1278,7 +1278,7 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt else BitStream_ReadByteArray(pBitStrm, nCount) match - case None => return None + case None() => return None() case Some(a) => a.copyToArray(arr) return Some(arr) @@ -1342,7 +1342,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: var nCurOffset1: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 = l while (nRemainingItemsVar1 & 0xC0) == 0xC0 do @@ -1356,27 +1356,27 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: else if nRemainingItemsVar1 == 0xC1 then nCurBlockSize1 = 0x4000 else - return None + return None() var i1: Int = nCurOffset1.toInt while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => arr(i1) = ub i1 += 1 nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 |= l nRemainingItemsVar1 &= 0x7FFF @@ -1386,7 +1386,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => arr(i1) = ub i1 += 1 @@ -1395,9 +1395,9 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then return Some(arr.take(nLengthTmp1.toInt)) else - return None + return None() - return None + return None() } @@ -1423,7 +1423,7 @@ def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1Size var nCount: Int = 0 if asn1SizeMin != asn1SizeMax then BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None => return None + case None() => return None() case Some(l) => nCount = l.toInt else nCount = asn1SizeMin.toInt @@ -1431,7 +1431,7 @@ def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1Size if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then return BitStream_DecodeOctetString_no_length(pBitStrm, nCount) else - return None + return None() else return BitStream_DecodeOctetString_fragmentation(pBitStrm, asn1SizeMax) @@ -1491,7 +1491,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa var nCount: Long = 0 if asn1SizeMin != asn1SizeMax then BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None => return None + case None() => return None() case Some(l) => nCount = l else nCount = asn1SizeMin @@ -1504,7 +1504,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa var nCurOffset1: Long = 0 var nLengthTmp1: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 = l var arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) @@ -1519,27 +1519,27 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa else if nRemainingItemsVar1 == 0xC1 then nCurBlockSize1 = 0x4000 else - return None + return None() /*COVERAGE_IGNORE*/ if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then - return None + return None() /*COVERAGE_IGNORE*/ BitStream_ReadBits(pBitStrm, nCurBlockSize1.toInt) match - case None => return None + case None() => return None() case Some(t) => Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => nRemainingItemsVar1 |= l nRemainingItemsVar1 &= 0x7FFF @@ -1547,14 +1547,14 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then BitStream_ReadBits(pBitStrm, nRemainingItemsVar1.toInt) match - case None => return None + case None() => return None() case Some(t) => Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) nLengthTmp1 += nRemainingItemsVar1 if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then return Some(arr) } - return None + return None() } //#ifdef ASN1SCC_STREAMING diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index 0a38e4cbc..882844cb2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -1,5 +1,7 @@ package asn1scala +import stainless.lang.{None => None, Option => Option, Some => Some, _} + val FAILED_READ_ERR_CODE = 5400 def Acn_AlignToNextByte(pBitStrm: BitStream, bEncode: Boolean): Unit = @@ -146,7 +148,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm: BitStream, def Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, encodedSizeInBits: Int): Option[ULong] = { BitStream_DecodeNonNegativeInteger(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(ul) => Some(ul) } @@ -154,7 +156,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, encodedSizeInBits def Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm: BitStream): Option[ULong] = { BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(ub) => Some(ub & 0xFF) } @@ -165,7 +167,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm: BitStream, Size var i: Int = 0 while i < SizeInBytes do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => ret <<= 8 ret |= (ub & 0xFF) @@ -199,7 +201,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, S var i: Int = 0 while i < SizeInBytes do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => tmp = ub & 0xFF tmp <<= i * 8 @@ -260,12 +262,12 @@ def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream): Opt var v: ULong = 0 BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(nBytes) => var i: Int = 0 while i < nBytes do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF) i += 1 @@ -334,14 +336,14 @@ def Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm: BitStream, encodedSizeInBits: var i: Int = 0 while i < nBytes do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => pIntVal = (pIntVal << 8) | (ub & 0xFF) i += 1 if rstBits > 0 then BitStream_ReadPartialByte(pBitStrm, rstBits.toByte) match - case None => return None + case None() => return None() case Some(ub) => pIntVal = (pIntVal << rstBits) | (ub & 0xFF) @@ -352,49 +354,49 @@ def Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm: BitStream, encodedSizeInBits: def Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, 1)) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, 2)) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, 4)) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, WORD_SIZE)) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, 2)) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, 4)) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm: BitStream): Option[Long] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(ul) => Some(uint2int(ul, WORD_SIZE)) } @@ -419,12 +421,12 @@ def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream): Opti var isNegative: Boolean = false BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(nBytes) => var i: Int = 0 while i < nBytes do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => if i == 0 && (ub & 0x80) > 0 then v = Long.MaxValue @@ -484,7 +486,7 @@ def Acn_Dec_Int_BCD_ConstSize(pBitStrm: BitStream, encodedSizeInNibbles: Int): O var encodedSizeInNibblesVar = encodedSizeInNibbles while encodedSizeInNibblesVar > 0 do BitStream_ReadPartialByte(pBitStrm, 4) match - case None => return None + case None() => return None() case Some(digit) => ret *= 10 ret += digit @@ -510,7 +512,7 @@ def Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): def Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = { BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(nNibbles) => Acn_Dec_Int_BCD_ConstSize(pBitStrm, nNibbles) } @@ -535,7 +537,7 @@ def Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm: BitStream): Option[ULong] = while true do BitStream_ReadPartialByte(pBitStrm, 4) match - case None => return None + case None() => return None() case Some(digit) => if (digit > 9) return Some(ret) @@ -588,7 +590,7 @@ def Acn_Dec_UInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): while encodedSizeInBytesVar > 0 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(digit) => assert(digit >= '0' && digit <= '9') @@ -603,7 +605,7 @@ def Acn_Dec_UInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): def Acn_Dec_SInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Long] = { BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(digit) => var sign: Int = 1 if digit == '+' then @@ -614,7 +616,7 @@ def Acn_Dec_SInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): assert(false) Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes - 1) match - case None => None + case None() => None() case Some(ul) => Some(sign * ul) } @@ -684,14 +686,14 @@ def Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong def Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = { BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(nChars) => Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, nChars) } def Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[Long] = { BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(nChars) => Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, nChars) } @@ -765,7 +767,7 @@ def Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte var j: Int = 0 while j < null_characters_size do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -780,7 +782,7 @@ def Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte j += 1 BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => tmp(null_characters_size - 1) = ub digit = (digit - '0').toByte @@ -797,14 +799,14 @@ def Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte var isNegative: Boolean = false BitStream_ReadByte(pBitStrm) match - case None => None + case None() => None() case Some(digit) => assert(digit == '-' || digit == '+') if digit == '-' then isNegative = true Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(ul) => Some(if isNegative then -ul else ul) } @@ -820,7 +822,7 @@ def BitStream_ReadBitPattern(pBitStrm: BitStream, patternToRead: Array[Byte], nB var i: Int = 0 while i < nBytesToRead do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(curByte) => if curByte != patternToRead(i) then pBoolValue = false @@ -828,7 +830,7 @@ def BitStream_ReadBitPattern(pBitStrm: BitStream, patternToRead: Array[Byte], nB if nRemainingBitsToRead > 0 then BitStream_ReadPartialByte(pBitStrm, nRemainingBitsToRead.toByte) match - case None => return None + case None() => return None() case Some(curByte) => if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then pBoolValue = false @@ -845,7 +847,7 @@ def BitStream_ReadBitPattern_ignore_value(pBitStrm: BitStream, nBitsToRead: Int) var i: Int = 0 while i < nBytesToRead do BitStream_ReadByte(pBitStrm) match - case None => return Left(FAILED_READ_ERR_CODE) + case None() => return Left(FAILED_READ_ERR_CODE) case Some(_) => i += 1 if nRemainingBitsToRead > 0 then @@ -873,7 +875,7 @@ def Acn_Dec_Real_IEEE754_32_big_endian(pBitStrm: BitStream): Option[Double] = var i: Int = 0 while i < 4 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -887,7 +889,7 @@ def Acn_Dec_Real_IEEE754_32_big_endian_fp32(pBitStrm: BitStream): Option[Float] var i: Int = 0 while i < 4 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -912,7 +914,7 @@ def Acn_Dec_Real_IEEE754_64_big_endian(pBitStrm: BitStream): Option[Double] = var i: Int = 0 while i < 8 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -937,7 +939,7 @@ def Acn_Dec_Real_IEEE754_32_little_endian(pBitStrm: BitStream): Option[Double] = var i: Int = 3 while i >= 0 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -951,7 +953,7 @@ def Acn_Dec_Real_IEEE754_32_little_endian_fp32(pBitStrm: BitStream): Option[Floa var i: Int = 3 while i >= 0 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -975,7 +977,7 @@ def Acn_Dec_Real_IEEE754_64_little_endian(pBitStrm: BitStream): Option[Double] = var i: Int = 7 while i >= 0 do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -1116,7 +1118,7 @@ def Acn_Dec_String_Ascii_private(pBitStrm: BitStream, max: Long, charactersToDec var i: Int = 0 while i < charactersToDecode do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(decodedCharacter) => strVal(i) = decodedCharacter i += 1 @@ -1188,7 +1190,7 @@ def Acn_Dec_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_cha var i: Int = 0 while i <= max do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(decodedCharacter) => if decodedCharacter != null_character then strVal(i) = decodedCharacter @@ -1197,7 +1199,7 @@ def Acn_Dec_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_cha strVal(i) = 0x0 return Some(strVal) - None + None() } def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = @@ -1209,7 +1211,7 @@ def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, nul var j: Int = 0 while j < null_character_size do BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -1224,13 +1226,13 @@ def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, nul j += 1 BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(ub) => tmp(null_character_size - 1) = ub strVal(i) = 0x0 if !null_character.sameElements(tmp) then - return None + return None() Some(strVal) } @@ -1244,7 +1246,7 @@ def Acn_Dec_String_Ascii_External_Field_Determinant(pBitStrm: BitStream, max: Lo def Acn_Dec_String_Ascii_Internal_Field_Determinant(pBitStrm: BitStream, max: Long, min: Long): Option[Array[ASCIIChar]] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None => None + case None() => None() case Some(nCount) => Acn_Dec_String_Ascii_private(pBitStrm, max, if nCount <= max then nCount else max) } @@ -1255,7 +1257,7 @@ def Acn_Dec_String_CharIndex_private(pBitStrm: BitStream, max: Long, charactersT var i: Int = 0 while i < charactersToDecode do BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, allowedCharSet.length - 1) match - case None => return None + case None() => return None() case Some(charIndex) => strVal(i) = allowedCharSet(charIndex.toInt) i += 1 @@ -1277,7 +1279,7 @@ def Acn_Dec_String_CharIndex_External_Field_Determinant (pBitStrm: BitStream, ma def Acn_Dec_String_CharIndex_Internal_Field_Determinant (pBitStrm: BitStream, max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None => None + case None() => None() case Some(nCount) => Acn_Dec_String_CharIndex_private(pBitStrm, max, if nCount <= max then nCount else max, allowedCharSet) } @@ -1321,7 +1323,7 @@ def Acn_Dec_IA5String_CharIndex_Internal_Field_Determinant(pBitStrm: BitStream, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None => None + case None() => None() case Some(nCount) => Acn_Dec_String_CharIndex_private(pBitStrm, max, if nCount <= max then nCount else max, allowedCharSet) } @@ -1354,509 +1356,509 @@ def milbus_decode(v: Long): Long = def Acn_Dec_Int_PositiveInteger_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UInt] = { Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_PositiveInteger_ConstSize_8UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSizeInt8 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSizeInt16 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSizeInt32 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Int] = { Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSize_8Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_BCD_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UByte] = { Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_BCD_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UShort] = { Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_BCD_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UInt] = { Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_SInt_ASCII_ConstSizeInt8 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Byte] = { Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_SInt_ASCII_ConstSizeInt16 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Short] = { Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_SInt_ASCII_ConstSizeInt32 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Int] = { Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt8 (pBitStrm: BitStream): Option[Byte] = { Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt16 (pBitStrm: BitStream): Option[Short] = { Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt32 (pBitStrm: BitStream): Option[Int] = { Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt8 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt16 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt32 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_UInt_ASCII_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UByte] = { Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_UInt_ASCII_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UShort] = { Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_UInt_ASCII_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UInt] = { Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt8 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toByte) } def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt16 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toShort) } def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt32 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None => None + case None() => None() case Some(v) => Some(v.toInt) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index 79717fa8e..712cd1177 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -1,7 +1,7 @@ package asn1scala import stainless.math.BitVectors._ -import stainless.lang.{None => _, Option => _, Some => _, _} +import stainless.lang.{None => None, Option => Option, Some => Some, _} def ObjectIdentifier_subidentifiers_uper_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { var lastOctet: Boolean = false @@ -88,7 +88,7 @@ def ObjectIdentifier_subidentifiers_uper_decode(pBitStrm: BitStream, pRemainingO while pRemainingOctets > 0 && !bLastOctet do decreases(pRemainingOctets) BitStream_ReadByte(pBitStrm) match - case None => return None + case None() => return None() case Some(curByte) => pRemainingOctets -= 1 @@ -105,12 +105,12 @@ def ObjectIdentifier_uper_decode_lentg(pBitStrm: BitStream): Option[Long] = { var totalSize: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => totalSize = l if totalSize > 0x7F then BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => return None + case None() => return None() case Some(l) => totalSize <<= 8 totalSize |= l @@ -124,11 +124,11 @@ def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifi var pVal = ObjectIdentifier_Init() ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None => return None + case None() => return None() case Some(l) => totalSize = l ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None => return None + case None() => return None() case Some(l, ul) => totalSize = l si = ul @@ -140,7 +140,7 @@ def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifi decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None => return None + case None() => return None() case Some(l, ul) => totalSize = l si = ul @@ -152,7 +152,7 @@ def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifi if totalSize == 0 then Some(pVal) else - None + None() } def RelativeOID_uper_decode (pBitStrm: BitStream): Option[Asn1ObjectIdentifier] = { @@ -161,13 +161,13 @@ def RelativeOID_uper_decode (pBitStrm: BitStream): Option[Asn1ObjectIdentifier] var pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None => return None + case None() => return None() case Some(l) => totalSize = l while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None => return None + case None() => return None() case Some(l, ul) => totalSize = l si = ul @@ -178,5 +178,5 @@ def RelativeOID_uper_decode (pBitStrm: BitStream): Option[Asn1ObjectIdentifier] if totalSize == 0 then Some(pVal) else - None + None() } From 08a1fb0a5306ca3e10d8388ab23b585274c54a1c Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 5 Oct 2023 14:32:00 +0200 Subject: [PATCH 002/174] added stainless Options instead of Scala Option / None / Some - pattern updatet. --- StgScala/acn_scala.stg | 110 +++++++++--------- StgScala/body_scala.stg | 1 + StgScala/uper_scala.stg | 38 +++--- .../asn1scala/asn1jvm_encoding_acn.scala | 2 +- 4 files changed, 76 insertions(+), 75 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index cbaaf48a5..9601746f1 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -97,7 +97,7 @@ Acn_AlignTo(pBitStrm, false) PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm, _encode(

)

, )" PositiveInteger_ConstSize_decode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -105,7 +105,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, ) match PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_8(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -113,7 +113,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match PositiveInteger_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -121,7 +121,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match PositiveInteger_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -129,7 +129,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match PositiveInteger_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -137,7 +137,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match PositiveInteger_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -145,7 +145,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match PositiveInteger_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -153,7 +153,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match PositiveInteger_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm, _encode(

)

)" PositiveInteger_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -161,7 +161,7 @@ Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match PositiveInteger_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= "Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" PositiveInteger_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= << Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -169,7 +169,7 @@ Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match TwosComplement_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize(pBitStrm, _encode(

)

, )" TwosComplement_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -177,7 +177,7 @@ Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, ) match TwosComplement_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_8(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -185,14 +185,14 @@ Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm) match TwosComplement_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> TwosComplement_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -200,7 +200,7 @@ Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match TwosComplement_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -208,7 +208,7 @@ Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match TwosComplement_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -216,7 +216,7 @@ Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match TwosComplement_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -224,7 +224,7 @@ Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match TwosComplement_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm, _encode(

)

)" TwosComplement_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -232,7 +232,7 @@ Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) TwosComplement_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" TwosComplement_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -240,7 +240,7 @@ Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) BCD_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= "Acn_Enc_Int_BCD_ConstSize(pBitStrm, _encode(

)

, )" BCD_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= << Acn_Dec_Int_BCD_ConstSize(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -248,7 +248,7 @@ Acn_Dec_Int_BCD_ConstSize(pBitStrm, ) match BCD_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" BCD_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -256,7 +256,7 @@ Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) BCD_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_BCD_VarSize_NullTerminated(pBitStrm, _encode(

)

)" BCD_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -264,7 +264,7 @@ Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match ASCII_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= "Acn_Enc_SInt_ASCII_ConstSize(pBitStrm, _encode(

)

, ) " ASCII_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -272,7 +272,7 @@ Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, ) match ASCII_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" ASCII_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -283,7 +283,7 @@ Acn_Enc_SInt_ASCII_VarSize_NullTerminated(pBitStrm, _encode(

) ASCII_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, (byte[]){}, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -294,7 +294,7 @@ Acn_Enc_UInt_ASCII_ConstSize(pBitStrm, _encode(

)

(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -305,7 +305,7 @@ Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm, _encode(

) ASCII_UINT_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm,

, (byte[]){}, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -313,28 +313,28 @@ Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm,

, (byte[]){(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> Real_64_big_endian_encode(p, sErrCode) ::= "Acn_Enc_Real_IEEE754_64_big_endian(pBitStrm,

)" Real_64_big_endian_decode(p, sErrCode) ::= << Acn_Dec_Real_IEEE754_64_big_endian(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> Real_32_little_endian_encode(p, sSuffix, sErrCode) ::= "Acn_Enc_Real_IEEE754_32_little_endian(pBitStrm,

)" Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= << Acn_Dec_Real_IEEE754_32_little_endian(pBitStrm) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> Real_64_little_endian_encode(p, sErrCode) ::= "Acn_Enc_Real_IEEE754_64_little_endian(pBitStrm,

)" Real_64_little_endian_decode(p, sErrCode) ::= << Acn_Dec_Real_IEEE754_64_little_endian(pBitStrm) match - case None => + case None() => return Left() case Some(x) =>

= x @@ -357,7 +357,7 @@ Boolean_decode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse var tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) BitStream_ReadBitPattern(pBitStrm, tmp, ) match - case None => + case None() => return Left() case Some(x) =>

= x @@ -379,7 +379,7 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav Null_pattern_decode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << BitStream_ReadBitPattern_ignore_value(pBitStrm, ) match - case None => ret = Left() + case None() => ret = Left() case Some(i) => ret = Right(i) @@ -387,7 +387,7 @@ BitStream_ReadBitPattern_ignore_value(pBitStrm, ) match { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) BitStream_ReadBitPattern(pBitStrm, tmp, ) match - case None => ret = Left() + case None() => ret = Left() case Some(b) => if !b then ret = Left() @@ -448,7 +448,7 @@ if ret.isRight then Acn_String_Ascii_FixSize_encode(p, sErrCode, nAsn1Max) ::= "Acn_Enc_String_Ascii_FixSize(pBitStrm, ,

)" Acn_String_Ascii_FixSize_decode(p, sErrCode, nAsn1Max) ::= << Acn_Dec_String_Ascii_FixSize(pBitStrm, ) match - case None => + case None() => return Left() case Some(x) =>

= x @@ -460,14 +460,14 @@ Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm, , (byte[]){, (byte[]){}, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> Acn_String_Ascii_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld) ::= "Acn_Enc_String_Ascii_External_Field_Determinant(pBitStrm, ,

)" Acn_String_Ascii_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld) ::= << Acn_Dec_String_Ascii_External_Field_Determinant(pBitStrm, , ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -477,7 +477,7 @@ Acn_Enc_String_Ascii_Internal_Field_Determinant(pBitStrm, , Acn_String_Ascii_Internal_Field_Determinant_decode(p, sErrCode, nAsn1Max, nAsn1Min, nInternalLengthDeterminantSizeInBits) ::= << Acn_Dec_String_Ascii_Internal_Field_Determinant(pBitStrm, , ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -493,7 +493,7 @@ Acn_Enc_String_CharIndex_FixSize(pBitStrm, , allowedCharSet, Acn_Dec_String_CharIndex_FixSize(pBitStrm, , allowedCharSet, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -505,7 +505,7 @@ Acn_Enc_String_CharIndex_External_Field_Determinant(pBitStrm, , allowe Acn_String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << Acn_Dec_String_CharIndex_External_Field_Determinant(pBitStrm, , allowedCharSet, , ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -516,7 +516,7 @@ Acn_Enc_IA5String_CharIndex_External_Field_Determinant(pBitStrm, ,

Acn_IA5String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << Acn_Dec_IA5String_CharIndex_External_Field_Determinant(pBitStrm, , ) match - case None => return Left() + case None() => return Left() case Some(x) =>

= x >> @@ -531,7 +531,7 @@ oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sEr if ((\<=) && (\<=)) then

nCount = .asInstanceOf[Int] BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.toInt) match - case None => return Left() + case None() => return Left() case Some(x) => x.copyToArray(

arr) >> @@ -544,7 +544,7 @@ BitStream_EncodeOctetString_no_length(pBitStrm,

arr, ) match oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then BitStream_DecodeOctetString_no_length(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(x) =>

arr = x >> @@ -601,7 +601,7 @@ bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld if (\<=) && (\<=) then

nCount = .asInstanceOf[Int] BitStream_ReadBits(pBitStrm,

nCount) match - case None => return Left() + case None() => return Left() case Some(arr) =>

arr = arr ret = Right(0) @@ -614,7 +614,7 @@ BitStream_AppendBits(pBitStrm,

arr, ) bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then BitStream_ReadBits(pBitStrm, ) match - case None => return Left() + case None() => return Left() case Some(arr) =>

arr = arr ret = Right(0) @@ -628,7 +628,7 @@ BitStream_AppendBits(pBitStrm, (byte[]){}, }, ,

arr, ) match - case None => + case None() => return Left() case Some(x) =>

nCount = x @@ -655,7 +655,7 @@ sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << BitStream_ReadBit(pBitStrm) match case Some(bit) =>

exist. = bit - case None => + case None() => return Left() >> @@ -843,7 +843,7 @@ Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_C Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match - case None => + case None() => return Left() case Some(x) => = x.asInstanceOf[Int] @@ -1036,7 +1036,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco if .asInstanceOf[Int] \<= then BitStream_DecodeOctetString_no_length(pBitStrm, .asInstanceOf[Int]) match - case None => + case None() => return Left() case Some(arr) => bitStrm.buf = arr @@ -1058,7 +1058,7 @@ bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncodi val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then BitStream_ReadBits(pBitStrm, (int)) match - case None => + case None() => return Left() case Some(arr) => bitStrm.buf = arr @@ -1107,7 +1107,7 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits BitStream_DecodeOctetString_no_length(pBitStrm, ) match - case None => + case None() => return Left(pErrCode) case Some(arr) => bitStrm.buf = arr @@ -1115,14 +1115,14 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits var nCount: Int = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match - case None => + case None() => return Left(pErrCode) case Some(x) => nCount = x if ret.isRight then BitStream_DecodeOctetString_no_length(pBitStrm, nCount.asInstanceOf[Int]) - case None => + case None() => return Left(pErrCode) case Some(arr) => bitStrm.buf = arr @@ -1161,7 +1161,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit BitStream_ReadBits(pBitStrm, ) match - case None => + case None() => return Left(pErrCode) case Some(arr) => bitStrm.buf = arr @@ -1172,14 +1172,14 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit var nCount: Int = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match - case None => + case None() => return Left(pErrCode) case Some(x) => nCount = x ret = Right(0) BitStream_ReadBits(pBitStrm, nCount) match - case None => + case None() => return Left(pErrCode) case Some(arr) => bitStrm.buf = arr diff --git a/StgScala/body_scala.stg b/StgScala/body_scala.stg index 3ffae0040..527a875b4 100644 --- a/StgScala/body_scala.stg +++ b/StgScala/body_scala.stg @@ -9,6 +9,7 @@ Code automatically generated by asn1scc tool package asn1src import asn1scala._ +import stainless.lang.{None => None, Option => Option, Some => Some} }; separator="\n"> >> diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 00ee0262b..b1df80bb9 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -109,7 +109,7 @@ InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< BitStream_DecodeConstraintWholeNumberByte(pBitStrm, 0, 127) match case Some(c) =>

() = c - case None => + case None() => return Left() >> @@ -122,7 +122,7 @@ IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match case Some(n) =>

= n - case None => + case None() => return Left() >> @@ -135,7 +135,7 @@ IntFullyConstraintPos_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << BitStream_DecodeConstraintPosWholeNumber(pBitStrm, , ) match case Some(decPosNr) =>

= decPosNr - case None => + case None() => return Left() >> @@ -145,7 +145,7 @@ IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << BitStream_DecodeUnConstraintWholeNumber(pBitStrm) match case Some(x) =>

= x - case None => + case None() => return Left() >> @@ -225,7 +225,7 @@ Boolean_decode(p, sErrCode) ::= << BitStream_ReadBit(pBitStrm) match case Some(bit) =>

= bit - case None => + case None() => return Left() >> @@ -234,7 +234,7 @@ Real_decode(p, sSuffix, sErrCode) ::= << BitStream_DecodeReal(pBitStrm) match case Some(d) =>

= d.asInstanceOf[Double] // TODO this cast may loose precision in case that the target val

is a double - case None => + case None() => return Left() >> @@ -280,7 +280,7 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match case _ => return Left() - case None => + case None() => return Left() // TODO C impl returns first element from enum, even in error case >> @@ -320,7 +320,7 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match }; separator="\n"> case _ => return Left() - case None => + case None() => return Left() >> @@ -332,7 +332,7 @@ sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << BitStream_ReadBit(pBitStrm) match case Some(bit) =>

exist. = bit - case None => + case None() => return Left() >> @@ -419,7 +419,7 @@ BitStream_DecodeConstraintWholeNumberInt(pBitStrm, , ) match case Some(n) => nStringLength = n

(nStringLength) = 0 // TODO do we need a 0 terminator? - case None => + case None() => return Left(405) = 0 @@ -444,7 +444,7 @@ seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nS BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match case Some(n) =>

nCount = n.asInstanceOf[Int] - case None => + case None() => return Left() = 0 @@ -460,7 +460,7 @@ octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << BitStream_DecodeOctetString_no_length(pBitStrm, ) match case Some(x) => x.copyToArray(

arr) - case None => + case None() => return Left(454) >> @@ -476,14 +476,14 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match case Some(n) => assert(n >= 0)

nCount = n - case None => + case None() => return Left() // decode payload BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int]) match case Some(a) => a.copyToArray(

arr) - case None => + case None() => return Left() >> @@ -496,7 +496,7 @@ bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << BitStream_ReadBits(pBitStrm, .asInstanceOf[Int]) match case Some(a) => a.copyToArray(

arr) - case None => + case None() => return Left() >> @@ -509,7 +509,7 @@ bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match case Some(n) =>

nCount = n - case None => + case None() => return Left() >> @@ -731,7 +731,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => + case None() => return Left() case Some(x) => = x.asInstanceOf[Int] @@ -768,7 +768,7 @@ while(( & 0xC0) == 0xC0) { += BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => + case None() => return Left() case Some(x) => = x.asInstanceOf[Int] @@ -778,7 +778,7 @@ if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None => + case None() => return Left() case Some(x) => len2 = x.asInstanceOf[Int] diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index 882844cb2..54fdd639d 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -1,6 +1,6 @@ package asn1scala -import stainless.lang.{None => None, Option => Option, Some => Some, _} +import stainless.lang.{None => None, Option => Option, Some => Some} val FAILED_READ_ERR_CODE = 5400 From 94d1a03c264a2fdbef041caf2b9b39e5d4fab3a4 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 9 Oct 2023 11:26:46 +0200 Subject: [PATCH 003/174] fix C Tests runner for unix --- PUSCScalaTest/Testframework.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index e50d57b6f..e59c4f0a0 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -268,13 +268,13 @@ private void RunCTests(string outDir, bool printOutput) StartInfo = new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "bash", - Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {cConfig}\\{cProject}.exe" : $"./mainprogram", + Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {cConfig}\\{cProject}.exe" : $"-c ./mainprogram", WorkingDirectory = outDir, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardInput = false, - CreateNoWindow = true, + CreateNoWindow = false, } }) { From 02a00d7c38bdfa3ad37333ff3f3d0171f664a39c Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 9 Oct 2023 13:06:19 +0200 Subject: [PATCH 004/174] added tests that failed before in a unix environment --- PUSCScalaTest/AcnInterop.cs | 64 +++++++++++++++++----------------- PUSCScalaTest/UperInterop.cs | 66 ++++++++++++++++++------------------ 2 files changed, 65 insertions(+), 65 deletions(-) diff --git a/PUSCScalaTest/AcnInterop.cs b/PUSCScalaTest/AcnInterop.cs index 5a2baa48c..cc5f99851 100644 --- a/PUSCScalaTest/AcnInterop.cs +++ b/PUSCScalaTest/AcnInterop.cs @@ -4,55 +4,55 @@ public class AcnInterop { private void UPERInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => - new TestBasics().Run_TestService(s, folderSuffix, ServiceVariation.CREATE_SCALA | + new TestBasics().Run_TestService(s, folderSuffix, ServiceVariation.CREATE_SCALA | ServiceVariation.CREATE_C | ServiceVariation.ACN | ServiceVariation.CREATE_TESTS | ServiceVariation.COMPARE_ENCODINGS); - //[TestMethod] - //public void TestService_01() => UPERInteropEncScalaDecC(PUS_C_Service.S1, "S1"); + [TestMethod] + public void TestService_01() => UPERInteropEncScalaDecC(PUS_C_Service.S1, "S1"); - //[TestMethod] - //public void TestService_02() => UPERInteropEncScalaDecC(PUS_C_Service.S2, "S2"); + [TestMethod] + public void TestService_02() => UPERInteropEncScalaDecC(PUS_C_Service.S2, "S2"); - //[TestMethod] - //public void TestService_03() => UPERInteropEncScalaDecC(PUS_C_Service.S3, "S3"); + [TestMethod] + public void TestService_03() => UPERInteropEncScalaDecC(PUS_C_Service.S3, "S3"); - //[TestMethod] - //public void TestService_04() => UPERInteropEncScalaDecC(PUS_C_Service.S4, "S4"); + [TestMethod] + public void TestService_04() => UPERInteropEncScalaDecC(PUS_C_Service.S4, "S4"); - //[TestMethod] - //public void TestService_05() => UPERInteropEncScalaDecC(PUS_C_Service.S5, "S5"); - - //[TestMethod] - //public void TestService_06() => UPERInteropEncScalaDecC(PUS_C_Service.S6, "S6"); + [TestMethod] + public void TestService_05() => UPERInteropEncScalaDecC(PUS_C_Service.S5, "S5"); - //[TestMethod] - //public void TestService_08() => UPERInteropEncScalaDecC(PUS_C_Service.S8, "S8"); + [TestMethod] + public void TestService_06() => UPERInteropEncScalaDecC(PUS_C_Service.S6, "S6"); - //[TestMethod] - //public void TestService_09() => UPERInteropEncScalaDecC(PUS_C_Service.S9, "S9"); + [TestMethod] + public void TestService_08() => UPERInteropEncScalaDecC(PUS_C_Service.S8, "S8"); - //[TestMethod] - //public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); + [TestMethod] + public void TestService_09() => UPERInteropEncScalaDecC(PUS_C_Service.S9, "S9"); - ////[TestMethod] - ////public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); + [TestMethod] + public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); //[TestMethod] - //public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); + //public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); - ////[TestMethod] - ////public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); //[TestMethod] - //public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); + //public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); - //[TestMethod] - //public void TestService_17() => UPERInteropEncScalaDecC(PUS_C_Service.S17, "S17"); + [TestMethod] + public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); - //[TestMethod] - //public void TestService_18() => UPERInteropEncScalaDecC(PUS_C_Service.S18, "S18"); + [TestMethod] + public void TestService_17() => UPERInteropEncScalaDecC(PUS_C_Service.S17, "S17"); - //[TestMethod] - //public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); + [TestMethod] + public void TestService_18() => UPERInteropEncScalaDecC(PUS_C_Service.S18, "S18"); + + [TestMethod] + public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); } } diff --git a/PUSCScalaTest/UperInterop.cs b/PUSCScalaTest/UperInterop.cs index d9bbd5af6..702bd3ac7 100644 --- a/PUSCScalaTest/UperInterop.cs +++ b/PUSCScalaTest/UperInterop.cs @@ -7,54 +7,54 @@ private void UPERInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => new TestBasics().Run_TestService(s, folderSuffix, ServiceVariation.CREATE_SCALA | ServiceVariation.CREATE_C | ServiceVariation.UPER | ServiceVariation.CREATE_TESTS | ServiceVariation.COMPARE_ENCODINGS); - //[TestMethod] - //public void TestService_01() => UPERInteropEncScalaDecC(PUS_C_Service.S1, "S1"); + [TestMethod] + public void TestService_01() => UPERInteropEncScalaDecC(PUS_C_Service.S1, "S1"); - //[TestMethod] - //public void TestService_02() => UPERInteropEncScalaDecC(PUS_C_Service.S2, "S2"); + [TestMethod] + public void TestService_02() => UPERInteropEncScalaDecC(PUS_C_Service.S2, "S2"); - //[TestMethod] - //public void TestService_03() => UPERInteropEncScalaDecC(PUS_C_Service.S3, "S3"); + [TestMethod] + public void TestService_03() => UPERInteropEncScalaDecC(PUS_C_Service.S3, "S3"); - //[TestMethod] - //public void TestService_04() => UPERInteropEncScalaDecC(PUS_C_Service.S4, "S4"); + [TestMethod] + public void TestService_04() => UPERInteropEncScalaDecC(PUS_C_Service.S4, "S4"); - //[TestMethod] - //public void TestService_05() => UPERInteropEncScalaDecC(PUS_C_Service.S5, "S5"); - - //[TestMethod] - //public void TestService_06() => UPERInteropEncScalaDecC(PUS_C_Service.S6, "S6"); + [TestMethod] + public void TestService_05() => UPERInteropEncScalaDecC(PUS_C_Service.S5, "S5"); - //[TestMethod] - //public void TestService_08() => UPERInteropEncScalaDecC(PUS_C_Service.S8, "S8"); + [TestMethod] + public void TestService_06() => UPERInteropEncScalaDecC(PUS_C_Service.S6, "S6"); - //[TestMethod] - //public void TestService_09() => UPERInteropEncScalaDecC(PUS_C_Service.S9, "S9"); + [TestMethod] + public void TestService_08() => UPERInteropEncScalaDecC(PUS_C_Service.S8, "S8"); - //[TestMethod] - //public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); + [TestMethod] + public void TestService_09() => UPERInteropEncScalaDecC(PUS_C_Service.S9, "S9"); - //// does not work in C - interop makes no sense - ////[TestMethod] - ////public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); + [TestMethod] + public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); + // does not work in C - interop makes no sense //[TestMethod] - //public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); + //public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); - //// does not work in C - interop makes no sense - ////[TestMethod] - ////public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); + // does not work in C - interop makes no sense //[TestMethod] - //public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); + //public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); - //[TestMethod] - //public void TestService_17() => UPERInteropEncScalaDecC(PUS_C_Service.S17, "S17"); + [TestMethod] + public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); - //[TestMethod] - //public void TestService_18() => UPERInteropEncScalaDecC(PUS_C_Service.S18, "S18"); + [TestMethod] + public void TestService_17() => UPERInteropEncScalaDecC(PUS_C_Service.S17, "S17"); - //[TestMethod] - //public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); + [TestMethod] + public void TestService_18() => UPERInteropEncScalaDecC(PUS_C_Service.S18, "S18"); + + [TestMethod] + public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); } } From 5bb22cd11f004468897ba73819fa36f22783a4d0 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 9 Oct 2023 13:14:52 +0200 Subject: [PATCH 005/174] fix and add command as argument for C tests --- PUSCScalaTest/Testframework.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index e59c4f0a0..212a81277 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -295,6 +295,7 @@ private void RunMake(string outDir) StartInfo = new ProcessStartInfo { FileName = "bash", + Arguments = "-c make all", WorkingDirectory = outDir, UseShellExecute = false, RedirectStandardOutput = true, @@ -304,11 +305,6 @@ private void RunMake(string outDir) }) { proc.Start(); - proc.StandardInput.WriteLine("make all"); - System.Threading.Thread.Sleep(500); - proc.StandardInput.Flush(); - proc.StandardInput.Close(); - proc.WaitForExit(); // parse output var stdout = proc.StandardOutput.ReadToEnd(); @@ -373,7 +369,7 @@ private void StartSBTWithArg(string outDir, string arg, string check, bool print StartInfo = new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "bash", - Arguments= RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {arg}" : "-c \"{arg}\"", + Arguments= RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {arg}" : $"-c \"{arg}\"", WorkingDirectory = outDir, UseShellExecute = false, RedirectStandardOutput = true, From 34315afd3e886d8023ba2f496da4bf8e17f5a581 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 9 Oct 2023 13:34:52 +0200 Subject: [PATCH 006/174] fix renamed github repository path in dockerfile --- Dockerfile.runtime | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile.runtime b/Dockerfile.runtime index 207e1f741..c73ace2c4 100644 --- a/Dockerfile.runtime +++ b/Dockerfile.runtime @@ -19,7 +19,7 @@ RUN --mount=type=cache,target=/var/cache/apt --mount=type=cache,target=/var/lib/ WORKDIR /src RUN set -ex ;\ - git clone https://github.com/ttsiodras/asn1scc.git ;\ + git clone https://github.com/maxime-esa/asn1scc.git ;\ cd asn1scc/ ;\ #git checkout dotnetcore ;\ dotnet build Antlr/ --configuration Release ;\ From 123b2eefde0d7e6b68f90082f021e3449741f59c Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 11 Oct 2023 17:18:13 +0200 Subject: [PATCH 007/174] added verified parts of code --- asn1scala/project/build.properties | 1 + .../src/main/scala/asn1scala/asn1jvm.scala | 43 +++-- .../scala/asn1scala/asn1jvm_encoding.scala | 162 ++++++++++++++---- .../scala/asn1scala/stainless_utils.scala | 154 +++++++++++++++++ asn1scc/GenerateRTL.fs | 1 + asn1scc/asn1scc.fsproj | 3 + asn1scc/stainless_utils.scala | 154 +++++++++++++++++ 7 files changed, 474 insertions(+), 44 deletions(-) create mode 100644 asn1scala/project/build.properties create mode 100644 asn1scala/src/main/scala/asn1scala/stainless_utils.scala create mode 100644 asn1scc/stainless_utils.scala diff --git a/asn1scala/project/build.properties b/asn1scala/project/build.properties new file mode 100644 index 000000000..46e43a97e --- /dev/null +++ b/asn1scala/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.8.2 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 84c946a3e..3c1ecc108 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -84,19 +84,36 @@ def asn1Real_Initialize(): asn1Real = { 0.0 } - -case class BitStream ( - var buf: Array[Byte], // UByte - var currentByte: Int, - var currentBit: Int, - // TODO - var pushDataPrm: Option[Any], - var fetchDataPrm: Option[Any], -) { - // TODO: currentByte==buf.length temp possible, but with bitstream_push_data_if_required set to 0 again - require(currentByte >= 0 && currentByte <= buf.length) - require(currentBit >= 0 && currentBit < 8) -} +case class BitStream( + var buf: Array[Byte], + var currentByte: Int, + var currentBit: Int, + ) { // all BisStream instances satisfy the following: + require(0 <= currentByte && currentByte <= buf.length) + require(0 <= currentBit && currentBit <= 7) + require(currentByte.toLong * 8 + currentBit.toLong <= 8 * buf.length.toLong) + + def bitIndex: Long = { + currentByte.toLong * 8 + currentBit.toLong + }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) + + def moveOffset(diffInBits: Long): Unit = { + val res = bitIndex + diffInBits + require(0 <= res && res <= 8 * buf.length.toLong) + val nbBytes = (diffInBits / 8).toInt + val nbBits = (diffInBits % 8).toInt + currentByte += nbBytes + if (currentBit + nbBits < 0) { + currentByte -= 1 + currentBit = 8 + nbBits + currentBit + } else if (currentBit + nbBits >= 8) { + currentBit = currentBit + nbBits - 8 + currentByte += 1 + } else { + currentBit += nbBits + } + }.ensuring(_ => old(this).bitIndex + diffInBits == bitIndex) +} // BitStream class case class ByteStream ( var buf: Array[Byte], // UByte diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1fda417e1..ec5b0860f 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1,6 +1,12 @@ package asn1scala -import stainless.lang.{None => None, Option => Option, Some => Some, _} +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, *} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* val masks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 @@ -12,17 +18,19 @@ val masks: Array[UByte] = Array( 0x02, // 2 / 0000 0010 / x02 0x01, // 1 / 0000 0001 / x01 ) + val masksb: Array[UByte] = Array( - 0x00, // 0 / 0000 0000 / x00 - 0x01, // 1 / 0000 0001 / x01 - 0x03, // 3 / 0000 0011 / x03 - 0x07, // 7 / 0000 0111 / x07 - 0x0F, // 15 / 0000 1111 / x0F - 0x1F, // 31 / 0001 1111 / x1F - 0x3F, // 63 / 0011 1111 / x3F - 0x7F, // 127 / 0111 1111 / x7F + 0x00, // 0 / 0000 0000 / x00 + 0x01, // 1 / 0000 0001 / x01 + 0x03, // 3 / 0000 0011 / x03 + 0x07, // 7 / 0000 0111 / x07 + 0x0F, // 15 / 0000 1111 / x0F + 0x1F, // 31 / 0001 1111 / x1F + 0x3F, // 63 / 0011 1111 / x3F + 0x7F, // 127 / 0111 1111 / x7F -0x1, // -1 / 1111 1111 / xFF ) + val masks2: Array[UInt] = Array( 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x00000000 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x000000FF @@ -61,11 +69,12 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), 0, 0, None(), None()) + BitStream(Array.fill(count)(0), 0, 0) } -def BitStream_Init2(count: Int, fetchDataPrm: Option[Any], pushDataPrm: Option[Any]): BitStream = { - BitStream(Array.fill(count)(0), 0, 0, fetchDataPrm, pushDataPrm) +// TODO removed unused params +def BitStream_Init2(count: Int, @scala.annotation.unused fetchDataPrm: Option[Any], @scala.annotation.unused pushDataPrm: Option[Any]): BitStream = { + BitStream(Array.fill(count)(0), 0, 0) } @@ -73,14 +82,11 @@ def BitStream_AttachBuffer(pBitStrm: BitStream, buf: Array[UByte]): Unit = { pBitStrm.buf = buf // TODO: fix illegal aliasing pBitStrm.currentByte = 0 pBitStrm.currentBit = 0 - pBitStrm.pushDataPrm = None() - pBitStrm.fetchDataPrm = None() } -def BitStream_AttachBuffer2(pBitStrm: BitStream, buf: Array[UByte], fetchDataPrm: Option[Any], pushDataPrm: Option[Any]): Unit = { +// TODO removed unused params +def BitStream_AttachBuffer2(pBitStrm: BitStream, buf: Array[UByte], @scala.annotation.unused fetchDataPrm: Option[Any], @scala.annotation.unused pushDataPrm: Option[Any]): Unit = { BitStream_AttachBuffer(pBitStrm, buf) - pBitStrm.pushDataPrm = pushDataPrm - pBitStrm.fetchDataPrm = fetchDataPrm } def BitStream_GetLength(pBitStrm: BitStream): Int = { @@ -105,16 +111,55 @@ or 00010000 xxx1???? **/ +def isPrefix(b1: BitStream, b2: BitStream): Boolean = { + b1.buf.length <= b2.buf.length && + b1.bitIndex <= b2.bitIndex && + (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex) +} + +def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) + +@ghost +def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { + require(isValidPair(w1, w2)) + val r1 = BitStream(snapshot(w2.buf), w1.currentByte, w1.currentBit) + val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) + (r1, r2) +} + +@ghost @pure +def BitStream_ReadBitPure(pBitStrm: BitStream): (BitStream, Option[Boolean]) = { + require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) + val cpy = snapshot(pBitStrm) + (cpy , BitStream_ReadBit(cpy)) +} + +@opaque @inlineOnce def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte + require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) + @ghost val oldpBitStrm = snapshot(pBitStrm) + + val newB = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte + pBitStrm.buf(pBitStrm.currentByte) = newB + + ghostExpr { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, newB) + } if pBitStrm.currentBit < 7 then pBitStrm.currentBit += 1 else pBitStrm.currentBit = 0 pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) - assert(pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8) + +}.ensuring { _ => + val w1 = old(pBitStrm) + val w2 = pBitStrm + w2.bitIndex == w1.bitIndex + 1 && isValidPair(w1, w2) && { + val (r1, r2) = reader(w1, w2) + val (r2Got, bitGot) = BitStream_ReadBitPure(r1) + bitGot.get == true && r2Got == r2 + } } /** @@ -209,7 +254,9 @@ def BitStream_AppendBit(pBitStrm: BitStream, v: Boolean): Unit = { assert(pBitStrm.currentByte + pBitStrm.currentBit/8 <= pBitStrm.buf.length) } +// TODO check if needs Marios implementation def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { + require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) val ret = (pBitStrm.buf(pBitStrm.currentByte) & masks(pBitStrm.currentBit)) != 0 if pBitStrm.currentBit < 7 then @@ -249,28 +296,74 @@ or 000bbbbb xxxbbbbb **/ -def BitStream_AppendByte(pBitStrm: BitStream, vVal: UByte, negate: Boolean): Unit = { - //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; - val cb: UByte = pBitStrm.currentBit.toByte - val ncb: UByte = (8 - cb).toByte - var v = vVal +@opaque @inlineOnce +def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Unit = { + require(pBitStrm.bitIndex + 8 <= pBitStrm.buf.length.toLong * 8) + @ghost val oldpBitStrm = snapshot(pBitStrm) + val cb = pBitStrm.currentBit.toByte + val ncb = (8 - cb).toByte + var mask = (~masksb(ncb)).toByte + + var v = value if negate then v = (~v).toByte - var mask: UByte = (~masksb(ncb)).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF ) >>> cb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >> cb)).toByte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) - assert(pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8) + ghostExpr { + check( + (oldpBitStrm.currentByte < oldpBitStrm.buf.length) ==> + bytePrefix( + oldpBitStrm.buf(oldpBitStrm.currentByte), + pBitStrm.buf(oldpBitStrm.currentByte), + 0, oldpBitStrm.currentBit)) + } + @ghost val old2pBitStrm = snapshot(pBitStrm) if cb > 0 then mask = (~mask).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte // TODO: check if & 0xFF is needed + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v << ncb)).toByte + + ghostExpr { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte - 1, pBitStrm.buf(pBitStrm.currentByte - 1)) + assert(arrayPrefix(oldpBitStrm.buf, old2pBitStrm.buf, 0, pBitStrm.currentByte - 1)) + + if (cb > 0) { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, pBitStrm.buf(pBitStrm.currentByte)) + arrayUpdatedAtPrefixLemma(old2pBitStrm.buf, pBitStrm.currentByte, pBitStrm.buf(pBitStrm.currentByte)) + arrayPrefixTransitive( + oldpBitStrm.buf, + old2pBitStrm.buf, + pBitStrm.buf, + 0, pBitStrm.currentByte - 1, pBitStrm.currentByte + ) + check(arrayPrefix( + oldpBitStrm.buf, + pBitStrm.buf, + 0, + oldpBitStrm.currentByte + )) + } else { + check(arrayPrefix( + oldpBitStrm.buf, + pBitStrm.buf, + 0, + oldpBitStrm.currentByte + )) + } + } +}.ensuring { _ => + val w1 = old(pBitStrm) + val w2 = pBitStrm + w2.bitIndex == w1.bitIndex + 8 && isValidPair(w1, w2) && { + val (r1, r2) = reader(w1, w2) + val (r2Got, vGot) = BitStream_ReadBytePure(r1) + vGot.get == value && r2Got == r2 + } } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { @@ -362,6 +455,13 @@ def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { None() } +@ghost @pure +def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { + require(pBitStrm.bitIndex + 8 <= pBitStrm.buf.length.toLong * 8) + val cpy = snapshot(pBitStrm) + (cpy, BitStream_ReadByte(cpy)) +} + def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): Option[Array[UByte]] = { val arr: Array[UByte] = Array.fill(arr_len)(0) diff --git a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala new file mode 100644 index 000000000..f98fb7e69 --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala @@ -0,0 +1,154 @@ +package asn1scala + +import stainless.* +import stainless.lang.* +import stainless.collection.* +import stainless.annotation.{wrapping => _, *} +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +val masksc: Array[Byte] = Array( + 0x00, // / 0000 0000 / + -0x80, // / 1000 0000 / + -0x40, // / 1100 0000 / + -0x20, // / 1110 0000 / + -0x10, // / 1111 0000 / + -0x08, // / 1111 1000 / + -0x04, // / 1111 1100 / + -0x02, // / 1111 1110 / +) + +def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + decreases(to - from) + if (from == to) true + else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) +} +@opaque @inlineOnce +def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { + require(0 <= at && at < a.length) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(0 <= i && i <= at) + require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) + decreases(i) + if (i == 0) () + else rec(i - 1) + }.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) + } + + rec(at) +}.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) +} + +def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { + require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) + val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt + val arrPrefixEnd = (toBit / 8).toInt + val fromBitIx = (fromBit / 8).toInt + val toBitIx = (toBit / 8).toInt + (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) +} + +def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { + require(0 <= from && from <= to && to <= 7) + ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) +} + +def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { + require(a1.length <= a2.length) + require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) + require(fromBit < a1.length.toLong * 8) + (fromBit < toBit) ==> { + val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) + val restFrom = (fromBit % 8).toInt + val restTo = (toBit % 8).toInt + ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { + if (fromBitIx == toBitIx) { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) + } else { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && + ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) + } + } + } +} + +@opaque @inlineOnce +def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + require(from <= at && at < to) + require(arrayPrefix(a1, a2, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= at) + require(arrayPrefix(a1, a2, i, to)) + decreases(to - i) + if (i == at) () + else rec(i + 1) + }.ensuring { _ => + a1(at) == a2(at) + } + + rec(from) +}.ensuring(_ => a1(at) == a2(at)) + +@opaque @inlineOnce +def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to < a1.length) + require(arrayPrefix(a1, a2, from, to)) + require(a1(to) == a2(to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= to) + require(arrayPrefix(a1, a2, i, to + 1)) + decreases(i) + if (i == from) () + else { + arrayPrefixImpliesEq(a1, a2, from, i - 1, to) + rec(i - 1) + } + }.ensuring { _ => + arrayPrefix(a1, a2, from, to + 1) + } + + rec(to) +}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) + +@opaque @inlineOnce +def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { + require(0 <= from && from <= mid && mid <= to) + require(a1.length <= a2.length && a2.length <= a3.length) + require(mid <= a1.length && to <= a2.length) + require(arrayPrefix(a1, a2, from, mid)) + require(arrayPrefix(a2, a3, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= mid) + require(arrayPrefix(a1, a2, i, mid)) + require(arrayPrefix(a2, a3, i, to)) + require(arrayPrefix(a1, a3, from, i)) + decreases(to - i) + if (i == mid) () + else { + arrayPrefixAppend(a1, a3, from, i) + rec(i + 1) + } + }.ensuring { _ => + arrayPrefix(a1, a3, from, mid) + } + rec(from) +}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) diff --git a/asn1scc/GenerateRTL.fs b/asn1scc/GenerateRTL.fs index 18c53b599..4c94b13f8 100644 --- a/asn1scc/GenerateRTL.fs +++ b/asn1scc/GenerateRTL.fs @@ -109,6 +109,7 @@ let exportRTL (di:DirInfo) (l:ProgrammingLanguage) (args:CommandLineSettings)= | _ -> writeResource di "asn1jvm_encoding.scala" None + writeResource di "stainless_utils.scala" None // needed for verification if hasUper || hasAcn then writeResource di "asn1jvm_encoding_uper.scala" None diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index 4f21ddac8..36eaa2b52 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -8,6 +8,7 @@ + @@ -102,4 +103,6 @@ + + diff --git a/asn1scc/stainless_utils.scala b/asn1scc/stainless_utils.scala new file mode 100644 index 000000000..d280319f6 --- /dev/null +++ b/asn1scc/stainless_utils.scala @@ -0,0 +1,154 @@ +package asn1scala + +import stainless.* +import stainless.lang.* +import stainless.collection.* +import stainless.annotation.{wrapping => _, *} +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +val masksc: Array[Byte] = Array( + 0x00, // / 0000 0000 / + -0x80, // / 1000 0000 / + -0x40, // / 1100 0000 / + -0x20, // / 1110 0000 / + -0x10, // / 1111 0000 / + -0x08, // / 1111 1000 / + -0x04, // / 1111 1100 / + -0x02, // / 1111 1110 / +) + +def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + decreases(to - from) + if (from == to) true + else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) +} +@opaque @inlineOnce +def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { + require(0 <= at && at < a.length) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(0 <= i && i <= at) + require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) + decreases(i) + if (i == 0) () + else rec(i - 1) + }.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) + } + + rec(at) +}.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) +} + +def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { + require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) + val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt + val arrPrefixEnd = (toBit / 8).toInt + val fromBitIx = (fromBit / 8).toInt + val toBitIx = (toBit / 8).toInt + (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) +} + +def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { + require(0 <= from && from <= to && to <= 7) + ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) +} + +def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { + require(a1.length <= a2.length) + require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) + require(fromBit < a1.length.toLong * 8) + (fromBit < toBit) ==> { + val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) + val restFrom = (fromBit % 8).toInt + val restTo = (toBit % 8).toInt + ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { + if (fromBitIx == toBitIx) { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) + } else { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && + ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) + } + } + } +} + +@opaque @inlineOnce +def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + require(from <= at && at < to) + require(arrayPrefix(a1, a2, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= at) + require(arrayPrefix(a1, a2, i, to)) + decreases(to - i) + if (i == at) () + else rec(i + 1) + }.ensuring { _ => + a1(at) == a2(at) + } + + rec(from) +}.ensuring(_ => a1(at) == a2(at)) + +@opaque @inlineOnce +def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to < a1.length) + require(arrayPrefix(a1, a2, from, to)) + require(a1(to) == a2(to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= to) + require(arrayPrefix(a1, a2, i, to + 1)) + decreases(i) + if (i == from) () + else { + arrayPrefixImpliesEq(a1, a2, from, i - 1, to) + rec(i - 1) + } + }.ensuring { _ => + arrayPrefix(a1, a2, from, to + 1) + } + + rec(to) +}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) + +@opaque @inlineOnce +def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { + require(0 <= from && from <= mid && mid <= to) + require(a1.length <= a2.length && a2.length <= a3.length) + require(mid <= a1.length && to <= a2.length) + require(arrayPrefix(a1, a2, from, mid)) + require(arrayPrefix(a2, a3, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= mid) + require(arrayPrefix(a1, a2, i, mid)) + require(arrayPrefix(a2, a3, i, to)) + require(arrayPrefix(a1, a3, from, i)) + decreases(to - i) + if (i == mid) () + else { + arrayPrefixAppend(a1, a3, from, i) + rec(i + 1) + } + }.ensuring { _ => + arrayPrefix(a1, a3, from, mid) + } + rec(from) +}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) From d3efe196e75b30dcfef5d47aad963640b201ce6d Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 12 Oct 2023 19:03:45 +0200 Subject: [PATCH 008/174] formatting --- asn1crt/asn1crt_encoding_acn.c | 47 +++++++++++++++------------------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/asn1crt/asn1crt_encoding_acn.c b/asn1crt/asn1crt_encoding_acn.c index 4d1ba8b24..64c41d7af 100644 --- a/asn1crt/asn1crt_encoding_acn.c +++ b/asn1crt/asn1crt_encoding_acn.c @@ -1210,38 +1210,33 @@ void Acn_Enc_String_CharIndex_Internal_Field_Determinant(BitStream* pBitStrm, as void Acn_Enc_IA5String_CharIndex_External_Field_Determinant(BitStream* pBitStrm, asn1SccSint max, const char* strVal) { - static byte allowedCharSet[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, - 0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13, - 0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D, - 0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27, - 0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31, - 0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B, - 0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45, - 0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, - 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63, - 0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D, - 0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, - 0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F }; + static byte allowedCharSet[] = { + 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, + 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, + 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, + 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, + 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, + 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, + 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, + 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F + }; Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, 128, strVal); } void Acn_Enc_IA5String_CharIndex_Internal_Field_Determinant(BitStream* pBitStrm, asn1SccSint max, asn1SccSint min, const char* strVal) { - static byte allowedCharSet[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, - 0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13, - 0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D, - 0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27, - 0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31, - 0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B, - 0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45, - 0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, - 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63, - 0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D, - 0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, - 0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F }; + static byte allowedCharSet[] = { + 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, + 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, + 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, + 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, + 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, + 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, + 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, + 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F + }; + int strLen = (int)strlen(strVal); BitStream_EncodeConstraintWholeNumber(pBitStrm, strLen <= max ? strLen : max, min, max); Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, 128, strVal); From e7624c261abfc63acdef0c4b40118fabc7e0ec6c Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 12 Oct 2023 19:04:20 +0200 Subject: [PATCH 009/174] verification of asn1jvm.scala --- .../src/main/scala/asn1scala/asn1jvm.scala | 71 +++++++++++-------- .../scala/asn1scala/asn1jvm_encoding.scala | 4 +- 2 files changed, 45 insertions(+), 30 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 3c1ecc108..1c4aa2ba2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -1,6 +1,7 @@ package asn1scala import stainless.lang.{None => None, Option => Option, _} +import stainless.annotation._ // type used in ErrorCases type ErrorCode = Int @@ -20,6 +21,7 @@ type LongNoRTL = Long type ULongNoRTL = ULong // Floating Point Types +@extern type asn1Real = Double val WORD_SIZE = 8 @@ -41,17 +43,20 @@ val ber_aux: Array[ULong] = Array( // TODO: check types and if neccesary as we don't have unsigned types def int2uint(v: Long): ULong = { - var ret: ULong = 0 + v.asInstanceOf[ULong] + /*var ret: ULong = 0 if v < 0 then ret = -v - 1 ret = ~ret else ret = v - ret + ret*/ } def uint2int(v: ULong, uintSizeInBytes: Int): Long = { + require(uintSizeInBytes >= 1 && uintSizeInBytes <= 9) + var vv = v val tmp: ULong = 0x80 val bIsNegative: Boolean = (vv & (tmp << ((uintSizeInBytes - 1) * 8))) > 0 @@ -66,20 +71,27 @@ def uint2int(v: ULong, uintSizeInBytes: Int): Long = { -(~vv) - 1 } -def GetCharIndex(ch: UByte, Set: Array[UByte]): Int = + +def GetCharIndex(ch: UByte, charSet: Array[UByte]): Int = { var i: Int = 0 - while i < Set.length do - if ch == Set(i) then - return i + // TODO what is this? why is 0 the default return? what is the difference between key found in 0 and default? + var ret: Int = 0 + + (while i < charSet.length && ret == 0 do + decreases(charSet.length - i) + if ch == charSet(i) then + ret = i i += 1 - 0 + ).invariant(i >= 0 &&& i < charSet.length) + ret } def NullType_Initialize(): ASCIIChar = { 0 } +@extern @pure def asn1Real_Initialize(): asn1Real = { 0.0 } @@ -217,22 +229,20 @@ enum Asn1TimeZoneClass: /** -####### ### -# # ##### # ###### #### ##### # ##### ###### # # ##### # ###### # ###### ##### -# # # # # # # # # # # # # ## # # # # # # # # -# # ##### # ##### # # # # # ##### # # # # # ##### # ##### # # -# # # # # # # # # # # # # # # # # # # # ##### -# # # # # # # # # # # # # # # ## # # # # # # # -####### ##### #### ###### #### # ### ##### ###### # # # # # # ###### # # +####### ### +# # ##### # ###### #### ##### # ##### ###### # # ##### # ###### # ###### ##### +# # # # # # # # # # # # # ## # # # # # # # # +# # ##### # ##### # # # # # ##### # # # # # ##### # ##### # # +# # # # # # # # # # # # # # # # # # # # ##### +# # # # # # # # # # # # # # # ## # # # # # # # +####### ##### #### ###### #### # ### ##### ###### # # # # # # ###### # # Object Identifier **/ - - def ObjectIdentifier_Init(): Asn1ObjectIdentifier = { - var pVal: Asn1ObjectIdentifier = Asn1ObjectIdentifier(0, Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH)(0)) + val pVal: Asn1ObjectIdentifier = Asn1ObjectIdentifier(0, Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH)(0)) var i: Int = 0 (while i < OBJECT_IDENTIFIER_MAX_LENGTH do decreases(OBJECT_IDENTIFIER_MAX_LENGTH - i) @@ -253,19 +263,22 @@ def RelativeOID_isValid (pVal: Asn1ObjectIdentifier): Boolean = { } def ObjectIdentifier_equal (pVal1: Asn1ObjectIdentifier, pVal2: Asn1ObjectIdentifier): Boolean = { - var i: Int = 0 - if pVal1.nCount == pVal2.nCount && pVal1.nCount <= OBJECT_IDENTIFIER_MAX_LENGTH then // TODO: (pVal1 != NULL) && (pVal2 != NULL) - var ret: Boolean = true - while i < pVal1.nCount && ret do - decreases(pVal1.nCount - i) - ret = (pVal1.values(i) == pVal2.values(i)) - i += 1 - - return ret - else + if pVal1.nCount != pVal2.nCount || pVal1.nCount > OBJECT_IDENTIFIER_MAX_LENGTH then return false + + var i: Int = 0 + + var ret: Boolean = true + (while i < pVal1.nCount && ret do + decreases(pVal1.nCount - i) + + ret = (pVal1.values(i) == pVal2.values(i)) + i += 1 + ).invariant(i >= 0 &&& i < pVal1.nCount) + + return ret } def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { - assert(pBitStrm.currentByte*8 + pBitStrm.currentBit <= pBitStrm.buf.length*8) -} \ No newline at end of file + assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) +} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index ec5b0860f..457714269 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -72,7 +72,7 @@ def BitStream_Init(count: Int): BitStream = { BitStream(Array.fill(count)(0), 0, 0) } -// TODO removed unused params +// TODO remove whole init func - streaming mode code def BitStream_Init2(count: Int, @scala.annotation.unused fetchDataPrm: Option[Any], @scala.annotation.unused pushDataPrm: Option[Any]): BitStream = { BitStream(Array.fill(count)(0), 0, 0) } @@ -793,6 +793,8 @@ def GetLengthInBytesOfSInt (v: Long): Int = { def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long, max: Long): Unit = { require(min <= max) + require(min <= v && v <= max) + val range = max - min if range == 0 then return From b99f3b144f5d7d149bd0c01d6777a8858b4b1bb8 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 13 Oct 2023 16:45:19 +0200 Subject: [PATCH 010/174] asn1jvm.scala runs through stainless --- .../src/main/scala/asn1scala/asn1jvm.scala | 22 ++++++++++++------- .../scala/asn1scala/asn1jvm_encoding.scala | 18 +++++++-------- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 1c4aa2ba2..861afc92a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -65,9 +65,11 @@ def uint2int(v: ULong, uintSizeInBytes: Int): Long = { return v var i: Int = WORD_SIZE-1 - while i >= uintSizeInBytes do + (while i >= uintSizeInBytes do + decreases(i) vv |= ber_aux(i) i -= 1 + ).invariant(i <= WORD_SIZE-1 && i >= uintSizeInBytes - 1) -(~vv) - 1 } @@ -83,7 +85,7 @@ def GetCharIndex(ch: UByte, charSet: Array[UByte]): Int = if ch == charSet(i) then ret = i i += 1 - ).invariant(i >= 0 &&& i < charSet.length) + ).invariant(i >= 0 &&& i <= charSet.length) ret } @@ -105,12 +107,13 @@ case class BitStream( require(0 <= currentBit && currentBit <= 7) require(currentByte.toLong * 8 + currentBit.toLong <= 8 * buf.length.toLong) - def bitIndex: Long = { + def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) def moveOffset(diffInBits: Long): Unit = { - val res = bitIndex + diffInBits + require(diffInBits >= 0 && diffInBits <= 8 * buf.length.toLong) + val res = bitIndex() + diffInBits require(0 <= res && res <= 8 * buf.length.toLong) val nbBytes = (diffInBits / 8).toInt val nbBits = (diffInBits % 8).toInt @@ -124,7 +127,7 @@ case class BitStream( } else { currentBit += nbBits } - }.ensuring(_ => old(this).bitIndex + diffInBits == bitIndex) + }.ensuring(_ => old(this).bitIndex() + diffInBits == bitIndex()) } // BitStream class case class ByteStream ( @@ -263,18 +266,21 @@ def RelativeOID_isValid (pVal: Asn1ObjectIdentifier): Boolean = { } def ObjectIdentifier_equal (pVal1: Asn1ObjectIdentifier, pVal2: Asn1ObjectIdentifier): Boolean = { + require(pVal1.nCount >= 0 && pVal1.nCount <= OBJECT_IDENTIFIER_MAX_LENGTH) + require(pVal2.nCount >= 0 && pVal2.nCount <= OBJECT_IDENTIFIER_MAX_LENGTH) + if pVal1.nCount != pVal2.nCount || pVal1.nCount > OBJECT_IDENTIFIER_MAX_LENGTH then return false var i: Int = 0 var ret: Boolean = true - (while i < pVal1.nCount && ret do + (while i < pVal1.nCount do decreases(pVal1.nCount - i) - ret = (pVal1.values(i) == pVal2.values(i)) + ret &= (pVal1.values(i) == pVal2.values(i)) i += 1 - ).invariant(i >= 0 &&& i < pVal1.nCount) + ).invariant(i >= 0 &&& i <= pVal1.nCount) return ret } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 457714269..a7426e1f4 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -113,8 +113,8 @@ or 00010000 def isPrefix(b1: BitStream, b2: BitStream): Boolean = { b1.buf.length <= b2.buf.length && - b1.bitIndex <= b2.bitIndex && - (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex) + b1.bitIndex() <= b2.bitIndex() && + (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex()) } def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) @@ -129,14 +129,14 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { @ghost @pure def BitStream_ReadBitPure(pBitStrm: BitStream): (BitStream, Option[Boolean]) = { - require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) + require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) val cpy = snapshot(pBitStrm) (cpy , BitStream_ReadBit(cpy)) } @opaque @inlineOnce def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { - require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) + require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) @ghost val oldpBitStrm = snapshot(pBitStrm) val newB = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte @@ -155,7 +155,7 @@ def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { }.ensuring { _ => val w1 = old(pBitStrm) val w2 = pBitStrm - w2.bitIndex == w1.bitIndex + 1 && isValidPair(w1, w2) && { + w2.bitIndex() == w1.bitIndex() + 1 && isValidPair(w1, w2) && { val (r1, r2) = reader(w1, w2) val (r2Got, bitGot) = BitStream_ReadBitPure(r1) bitGot.get == true && r2Got == r2 @@ -256,7 +256,7 @@ def BitStream_AppendBit(pBitStrm: BitStream, v: Boolean): Unit = { // TODO check if needs Marios implementation def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { - require(pBitStrm.bitIndex + 1 <= pBitStrm.buf.length.toLong * 8) + require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) val ret = (pBitStrm.buf(pBitStrm.currentByte) & masks(pBitStrm.currentBit)) != 0 if pBitStrm.currentBit < 7 then @@ -299,7 +299,7 @@ or 000bbbbb @opaque @inlineOnce def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Unit = { - require(pBitStrm.bitIndex + 8 <= pBitStrm.buf.length.toLong * 8) + require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) @ghost val oldpBitStrm = snapshot(pBitStrm) val cb = pBitStrm.currentBit.toByte val ncb = (8 - cb).toByte @@ -359,7 +359,7 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni }.ensuring { _ => val w1 = old(pBitStrm) val w2 = pBitStrm - w2.bitIndex == w1.bitIndex + 8 && isValidPair(w1, w2) && { + w2.bitIndex() == w1.bitIndex() + 8 && isValidPair(w1, w2) && { val (r1, r2) = reader(w1, w2) val (r2Got, vGot) = BitStream_ReadBytePure(r1) vGot.get == value && r2Got == r2 @@ -457,7 +457,7 @@ def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { @ghost @pure def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { - require(pBitStrm.bitIndex + 8 <= pBitStrm.buf.length.toLong * 8) + require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) val cpy = snapshot(pBitStrm) (cpy, BitStream_ReadByte(cpy)) } From 797417f454d81ce1dfaf09e3247fbd2270fdac84 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 16 Oct 2023 14:38:44 +0200 Subject: [PATCH 011/174] fix stainless_utils.scala resource --- asn1scc/asn1scc.fsproj | 4 +- asn1scc/stainless_utils.scala | 154 ---------------------------------- 2 files changed, 3 insertions(+), 155 deletions(-) delete mode 100644 asn1scc/stainless_utils.scala diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index 36eaa2b52..cfb65f324 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -8,7 +8,6 @@ - @@ -101,6 +100,9 @@ asn1jvm_encoding_acn.scala + + stainless_utils.scala + diff --git a/asn1scc/stainless_utils.scala b/asn1scc/stainless_utils.scala deleted file mode 100644 index d280319f6..000000000 --- a/asn1scc/stainless_utils.scala +++ /dev/null @@ -1,154 +0,0 @@ -package asn1scala - -import stainless.* -import stainless.lang.* -import stainless.collection.* -import stainless.annotation.{wrapping => _, *} -import stainless.proof.* -import stainless.math.* -import StaticChecks.* - -val masksc: Array[Byte] = Array( - 0x00, // / 0000 0000 / - -0x80, // / 1000 0000 / - -0x40, // / 1100 0000 / - -0x20, // / 1110 0000 / - -0x10, // / 1111 0000 / - -0x08, // / 1111 1000 / - -0x04, // / 1111 1100 / - -0x02, // / 1111 1110 / -) - -def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - decreases(to - from) - if (from == to) true - else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) -} -@opaque @inlineOnce -def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { - require(0 <= at && at < a.length) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(0 <= i && i <= at) - require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) - decreases(i) - if (i == 0) () - else rec(i - 1) - }.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) - } - - rec(at) -}.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) -} - -def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { - require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) - val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt - val arrPrefixEnd = (toBit / 8).toInt - val fromBitIx = (fromBit / 8).toInt - val toBitIx = (toBit / 8).toInt - (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) -} - -def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { - require(0 <= from && from <= to && to <= 7) - ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) -} - -def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { - require(a1.length <= a2.length) - require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) - require(fromBit < a1.length.toLong * 8) - (fromBit < toBit) ==> { - val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) - val restFrom = (fromBit % 8).toInt - val restTo = (toBit % 8).toInt - ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { - if (fromBitIx == toBitIx) { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) - } else { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && - ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) - } - } - } -} - -@opaque @inlineOnce -def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - require(from <= at && at < to) - require(arrayPrefix(a1, a2, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= at) - require(arrayPrefix(a1, a2, i, to)) - decreases(to - i) - if (i == at) () - else rec(i + 1) - }.ensuring { _ => - a1(at) == a2(at) - } - - rec(from) -}.ensuring(_ => a1(at) == a2(at)) - -@opaque @inlineOnce -def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to < a1.length) - require(arrayPrefix(a1, a2, from, to)) - require(a1(to) == a2(to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= to) - require(arrayPrefix(a1, a2, i, to + 1)) - decreases(i) - if (i == from) () - else { - arrayPrefixImpliesEq(a1, a2, from, i - 1, to) - rec(i - 1) - } - }.ensuring { _ => - arrayPrefix(a1, a2, from, to + 1) - } - - rec(to) -}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) - -@opaque @inlineOnce -def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { - require(0 <= from && from <= mid && mid <= to) - require(a1.length <= a2.length && a2.length <= a3.length) - require(mid <= a1.length && to <= a2.length) - require(arrayPrefix(a1, a2, from, mid)) - require(arrayPrefix(a2, a3, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= mid) - require(arrayPrefix(a1, a2, i, mid)) - require(arrayPrefix(a2, a3, i, to)) - require(arrayPrefix(a1, a3, from, i)) - decreases(to - i) - if (i == mid) () - else { - arrayPrefixAppend(a1, a3, from, i) - rec(i + 1) - } - }.ensuring { _ => - arrayPrefix(a1, a3, from, mid) - } - rec(from) -}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) From c73e2595ff3b7e18c6da8744b93573821652776d Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 16 Oct 2023 14:41:15 +0200 Subject: [PATCH 012/174] introduce Option/None/Some for mutable objects --- StgScala/acn_scala.stg | 40 ++++----- StgScala/uper_scala.stg | 12 +-- .../scala/asn1scala/asn1jvm_encoding.scala | 82 +++++++++---------- .../scala/asn1scala/stainless_utils.scala | 4 + 4 files changed, 71 insertions(+), 67 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index a4e9932cd..bb4299516 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -531,8 +531,8 @@ oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sEr if ((\<=) && (\<=)) then

nCount = .asInstanceOf[Int] BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.toInt) match - case None() => return Left() - case Some(x) => x.copyToArray(

arr) + case NoneMut() => return Left() + case SomeMut(x) => x.copyToArray(

arr) >> oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << @@ -544,8 +544,8 @@ BitStream_EncodeOctetString_no_length(pBitStrm,

arr, ) match oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then BitStream_DecodeOctetString_no_length(pBitStrm, ) match - case None() => return Left() - case Some(x) =>

arr = x + case NoneMut() => return Left() + case SomeMut(x) =>

arr = x >> @@ -601,8 +601,8 @@ bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld if (\<=) && (\<=) then

nCount = .asInstanceOf[Int] BitStream_ReadBits(pBitStrm,

nCount) match - case None() => return Left() - case Some(arr) => + case NoneMut() => return Left() + case SomeMut(arr) =>

arr = arr ret = Right(0) >> @@ -614,8 +614,8 @@ BitStream_AppendBits(pBitStrm,

arr, ) bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then BitStream_ReadBits(pBitStrm, ) match - case None() => return Left() - case Some(arr) => + case NoneMut() => return Left() + case SomeMut(arr) =>

arr = arr ret = Right(0) >> @@ -1036,9 +1036,9 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco if .asInstanceOf[Int] \<= then BitStream_DecodeOctetString_no_length(pBitStrm, .asInstanceOf[Int]) match - case None() => + case NoneMut() => return Left() - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr pBitStrm = bitStrm @@ -1058,9 +1058,9 @@ bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncodi val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then BitStream_ReadBits(pBitStrm, (int)) match - case None() => + case NoneMut() => return Left() - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr ret = (

, bitStrm) @@ -1107,9 +1107,9 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits BitStream_DecodeOctetString_no_length(pBitStrm, ) match - case None() => + case NoneMut() => return Left(pErrCode) - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr @@ -1122,9 +1122,9 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits if ret.isRight then BitStream_DecodeOctetString_no_length(pBitStrm, nCount.asInstanceOf[Int]) - case None() => + case NoneMut() => return Left(pErrCode) - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr @@ -1161,9 +1161,9 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit BitStream_ReadBits(pBitStrm, ) match - case None() => + case NoneMut() => return Left(pErrCode) - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr if ret.isRight then @@ -1179,9 +1179,9 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit ret = Right(0) BitStream_ReadBits(pBitStrm, nCount) match - case None() => + case NoneMut() => return Left(pErrCode) - case Some(arr) => + case SomeMut(arr) => bitStrm.buf = arr ret = Right(0) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index b1df80bb9..5848f60c1 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -458,9 +458,9 @@ if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr, .a octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << BitStream_DecodeOctetString_no_length(pBitStrm, ) match - case Some(x) => + case SomeMut(x) => x.copyToArray(

arr) - case None() => + case NoneMut() => return Left(454) >> @@ -481,9 +481,9 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // decode payload BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int]) match - case Some(a) => + case SomeMut(a) => a.copyToArray(

arr) - case None() => + case NoneMut() => return Left() >> @@ -494,9 +494,9 @@ BitStream_AppendBits(pBitStrm,

arr, .asInstanceOf[Int]) >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << BitStream_ReadBits(pBitStrm, .asInstanceOf[Int]) match - case Some(a) => + case SomeMut(a) => a.copyToArray(

arr) - case None() => + case NoneMut() => return Left() >> diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index a7426e1f4..e17490188 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1,7 +1,7 @@ package asn1scala import stainless.* -import stainless.lang.{None => None, ghost => ghostExpr, *} +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} import stainless.collection.* import stainless.annotation.* import stainless.proof.* @@ -462,14 +462,14 @@ def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { (cpy, BitStream_ReadByte(cpy)) } -def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): Option[Array[UByte]] = { +def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): OptionMut[Array[UByte]] = { val arr: Array[UByte] = Array.fill(arr_len)(0) val cb: UByte = pBitStrm.currentBit.toByte val ncb: UByte = (8 - cb).toByte if (pBitStrm.currentByte+arr_len).toLong*8 + cb.toInt > pBitStrm.buf.length.toLong*8 then - return None() + return NoneMut() var i: Int = 0 while i < arr_len do @@ -480,25 +480,25 @@ def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): Option[Array[UBy arr(i) = (arr(i) | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> ncb).toByte i += 1 - Some(arr) + SomeMut(arr) } -def BitStream_ReadBits(pBitStrm: BitStream, nbits: Int): Option[Array[UByte]] = { +def BitStream_ReadBits(pBitStrm: BitStream, nbits: Int): OptionMut[Array[UByte]] = { val bytesToRead: Int = nbits / 8 val remainingBits: UByte = (nbits % 8).toByte var ret: Boolean = false BitStream_DecodeOctetString_no_length(pBitStrm, bytesToRead) match - case None() => return None() - case Some(arr) => + case NoneMut() => return NoneMut() + case SomeMut(arr) => if remainingBits > 0 then BitStream_ReadPartialByte(pBitStrm, remainingBits) match - case None() => None() + case None() => return NoneMut() case Some(ub) => arr(bytesToRead) = ub arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte - Some(arr) + SomeMut(arr) else - Some(arr) + SomeMut(arr) } @@ -1371,7 +1371,7 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt // //#else if pBitStrm.currentByte + nCount > pBitStrm.buf.length then - return None() + return NoneMut() //memcpy(arr, pBitStrm.buf(pBitStrm.currentByte), nCount) pBitStrm.buf.slice(pBitStrm.currentByte, pBitStrm.currentByte+nCount).copyToArray(arr) @@ -1380,10 +1380,10 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt else BitStream_ReadByteArray(pBitStrm, nCount) match - case None() => return None() - case Some(a) => a.copyToArray(arr) + case NoneMut() => return NoneMut() + case SomeMut(a) => a.copyToArray(arr) - return Some(arr) + return SomeMut(arr) } @@ -1434,8 +1434,8 @@ def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UB return ret } -def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: Long): Option[Array[UByte]] = { - var arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) +def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) var nCount: Int = 0 var nLengthTmp1: Long = 0 @@ -1444,7 +1444,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: var nCurOffset1: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l while (nRemainingItemsVar1 & 0xC0) == 0xC0 do @@ -1458,27 +1458,27 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: else if nRemainingItemsVar1 == 0xC1 then nCurBlockSize1 = 0x4000 else - return None() + return NoneMut() var i1: Int = nCurOffset1.toInt while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) BitStream_ReadByte(pBitStrm) match - case None() => return None() + case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l nRemainingItemsVar1 &= 0x7FFF @@ -1488,18 +1488,18 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) BitStream_ReadByte(pBitStrm) match - case None() => return None() + case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 nLengthTmp1 += nRemainingItemsVar1 if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return Some(arr.take(nLengthTmp1.toInt)) + return SomeMut(arr.take(nLengthTmp1.toInt)) else - return None() + return NoneMut() - return None() + return NoneMut() } @@ -1519,13 +1519,13 @@ def BitStream_EncodeOctetString(pBitStrm: BitStream, arr: Array[UByte], nCount: } -def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): Option[Array[UByte]] = { +def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { if asn1SizeMax < 65536 then var nCount: Int = 0 if asn1SizeMin != asn1SizeMax then BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nCount = l.toInt else nCount = asn1SizeMin.toInt @@ -1533,7 +1533,7 @@ def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1Size if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then return BitStream_DecodeOctetString_no_length(pBitStrm, nCount) else - return None() + return NoneMut() else return BitStream_DecodeOctetString_fragmentation(pBitStrm, asn1SizeMax) @@ -1587,13 +1587,13 @@ def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: In } -def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): Option[Array[UByte]] = { +def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { if (asn1SizeMax < 65536) { var nCount: Long = 0 if asn1SizeMin != asn1SizeMax then BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nCount = l else nCount = asn1SizeMin @@ -1606,7 +1606,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa var nCurOffset1: Long = 0 var nLengthTmp1: Long = 0 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l var arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) @@ -1621,27 +1621,27 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa else if nRemainingItemsVar1 == 0xC1 then nCurBlockSize1 = 0x4000 else - return None() + return NoneMut() /*COVERAGE_IGNORE*/ if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then - return None() + return NoneMut() /*COVERAGE_IGNORE*/ BitStream_ReadBits(pBitStrm, nCurBlockSize1.toInt) match - case None() => return None() - case Some(t) => + case NoneMut() => return NoneMut() + case SomeMut(t) => Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() + case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l nRemainingItemsVar1 &= 0x7FFF @@ -1649,14 +1649,14 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then BitStream_ReadBits(pBitStrm, nRemainingItemsVar1.toInt) match - case None() => return None() - case Some(t) => + case NoneMut() => return NoneMut() + case SomeMut(t) => Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) nLengthTmp1 += nRemainingItemsVar1 if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return Some(arr) + return SomeMut(arr) } - return None() + return NoneMut() } //#ifdef ASN1SCC_STREAMING diff --git a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala index f98fb7e69..1924eab1d 100644 --- a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala +++ b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala @@ -152,3 +152,7 @@ def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int } rec(from) }.ensuring(_ => arrayPrefix(a1, a3, from, mid)) + +sealed trait OptionMut[@mutable A] +case class NoneMut[@mutable A]() extends OptionMut[A] +case class SomeMut[@mutable A](v: A) extends OptionMut[A] From d3e3aef01deeec0d559d27ddca71b3f0a6308b5f Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 16 Oct 2023 16:06:43 +0200 Subject: [PATCH 013/174] extern facade method for double, internal double bit string long meth --- .../scala/asn1scala/asn1jvm_encoding.scala | 149 ++++++++---------- 1 file changed, 62 insertions(+), 87 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index a7426e1f4..98c3deeae 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -807,32 +807,18 @@ def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Lon def BitStream_EncodeConstraintPosWholeNumber(pBitStrm: BitStream, v: ULong, min: ULong, max: ULong): Unit = { - // TODO: handle large max values better - if min <= max then - assert(min <= v) - assert(v <= max) - val range: ULong = (max - min) - if range == 0 then - return - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - BitStream_AppendNBitZero(pBitStrm, nRangeBits - nBits) - BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) - else - var max_b = scala.math.BigInt(max.toBinaryString, 2) - var min_b = scala.math.BigInt(min.toBinaryString, 2) - var v_b = scala.math.BigInt(v.toBinaryString, 2) - assert(min_b <= v_b) - assert(v_b <= max_b) - val range_b = (max_b - min_b) - if range_b == 0 then - return - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range_b.toLong) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v_b - min_b).toLong) - BitStream_AppendNBitZero(pBitStrm, nRangeBits - nBits) - BitStream_EncodeNonNegativeInteger(pBitStrm, (v_b - min_b).toLong) -} + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) + require(min <= v && v <= max) + val range: ULong = (max - min) + if range == 0 then + return + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) + BitStream_AppendNBitZero(pBitStrm, nRangeBits - nBits) + BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) +} def BitStream_DecodeConstraintWholeNumber(pBitStrm: BitStream, min: Long, max: Long): Option[Long] = { @@ -900,35 +886,19 @@ def BitStream_DecodeConstraintWholeNumberUInt(pBitStrm: BitStream, min: UInt, ma def BitStream_DecodeConstraintPosWholeNumber(pBitStrm: BitStream, min: ULong, max: ULong): Option[ULong] = { - // TODO: handle large max values better - if min <= max then - val range: ULong = max - min - - //ASSERT_OR_RETURN_FALSE(min <= max); - - if range == 0 then - return Some(min) - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - - BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None() => None() - case Some(uv) => Some(uv + min) - else - val max_b = scala.math.BigInt(max.toBinaryString, 2) - val min_b = scala.math.BigInt(min.toBinaryString, 2) - val range_b = max_b - min_b + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) - //ASSERT_OR_RETURN_FALSE(min <= max); + val range: ULong = max - min - if range_b == 0 then - return Some(min_b.toLong) + if range == 0 then + return Some(min) - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range_b.toLong) + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None() => None() - case Some(uv) => Some(uv + min_b.toLong) + BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match + case None() => None() + case Some(uv) => Some(uv + min) } def BitStream_EncodeSemiConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long): Unit = { @@ -1071,80 +1041,85 @@ cd:11 --> 1 byte for encoding the length of the exponent, then the expoent +-+-+-+-+-+-+-+-+ **/ -//#if FP_WORD_SIZE==8 -val ExpoBitMask = 0x7FF0000000000000L -val MantBitMask = 0x000FFFFFFFFFFFFFL -val MantBitMask2 = 0xFFE0000000000000L -val MantisaExtraBit = 0x0010000000000000L -//#else -//#define ExpoBitMask 0x7F800000U -//#define MantBitMask 0x007FFFFFU -//#define MantBitMask2 0xF0000000U -//#define MantisaExtraBit 0x00800000U -//#endif +val ExpoBitMask = 0x7ff0_0000_0000_0000L +val MantissaBitMask = 0x000f_ffff_ffff_ffffL +val MantissaExtraBit = 0x0010_0000_0000_0000L // hidden bit +val SignBitMask = 0x8000_0000_0000_0000L +val InverseSignBitMask = 0x7fff_ffff_ffff_ffffL + +val DoublePosInfBitString = 0x7ff0_0000_0000_0000L +val DoubleNegInfBitString = 0xfff0_0000_0000_0000L +val DoubleZeroBitString = 0x0000_0000_0000_0000L +val NoOfSignBit = 1 // double & float +val DoubleNoOfExponentBits = 11 +val DoubleNoOfMantissaBits = 52 +val DoubleBias = (1 << 10) - 1 // 1023 -def CalculateMantissaAndExponent(d: Double): (Int, ULong) = { - val ll: ULong = java.lang.Double.doubleToLongBits(d) +def CalculateMantissaAndExponent(dAsll: Long): (ULong, ULong) = { + // incoming dAsll is already a double bit string - var exponent: Int = 0 + var exponent: ULong = 0 var mantissa: ULong = 0 - //#if FP_WORD_SIZE == 8 - exponent = (((ll & ExpoBitMask) >>> 52) - 1023 - 52).toInt - mantissa = ll & MantBitMask - mantissa = mantissa | MantisaExtraBit - //#else - //exponent.x = (int)(((ll & ExpoBitMask) >>> 23) - 127 - 23); - //mantissa.x = ll & MantBitMask; - //mantissa.x |= MantisaExtraBit; - //#endif - return (exponent, mantissa) + exponent = ((dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits) - DoubleBias - DoubleNoOfMantissaBits + mantissa = dAsll & MantissaBitMask + mantissa = mantissa | MantissaExtraBit + + (exponent, mantissa) } def GetDoubleByMantissaAndExp(mantissa: ULong, exponentVal: Int): Double = { - return java.lang.Double.longBitsToDouble(((exponentVal + 1023L + 52L) << 52L) | (mantissa & MantBitMask)) + return java.lang.Double.longBitsToDouble(((exponentVal + DoubleBias + + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask)) } +@extern def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { - var header: UByte = -0x80 + BitStream_EncodeRealBitString(pBitStrm, java.lang.Double.doubleToLongBits(vVal)) +} +def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { var v = vVal - if (v == 0.0) { + if (v == DoubleZeroBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 0, 0, 0xFF) return } - if (v == Double.PositiveInfinity) { + + if (v == DoublePosInfBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) return } - if (v == Double.NegativeInfinity) { + if (v == DoubleNegInfBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) return } - if (v < 0) { - header = (header | 0x40).toByte - v = -v + var header = 0x80 + if ((v & SignBitMask) == SignBitMask) { // check sign bit + header |= 0x40 + v &= InverseSignBitMask // clear sign bit } val (exponent, mantissa) = CalculateMantissaAndExponent(v) - val nExpLen: Int = GetLengthInBytesOfSInt(exponent.toLong) + val nManLen: Int = GetLengthInBytesOfUInt(mantissa) + val nExpLen: Int = GetLengthInBytesOfSInt(exponent) assert(nExpLen <= 3) + if nExpLen == 2 then - header = (header | 1).toByte + header |= 1 else if nExpLen == 3 then - header = (header | 2).toByte + header |= 2 /* encode length */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1 + nExpLen + nManLen.toLong, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, 1 + nExpLen + nManLen, 0, 0xFF) /* encode header */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, header.toLong & 0xFF, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, header & 0xFF, 0, 0xFF) /* encode exponent */ if exponent >= 0 then From 716a3648d4f20ec7cc622ab54d441506fdc24d52 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 16 Oct 2023 16:40:13 +0200 Subject: [PATCH 014/174] fixed LL bug --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 98c3deeae..5bab6132e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1052,9 +1052,9 @@ val DoubleNegInfBitString = 0xfff0_0000_0000_0000L val DoubleZeroBitString = 0x0000_0000_0000_0000L val NoOfSignBit = 1 // double & float -val DoubleNoOfExponentBits = 11 -val DoubleNoOfMantissaBits = 52 -val DoubleBias = (1 << 10) - 1 // 1023 +val DoubleNoOfExponentBits = 11L +val DoubleNoOfMantissaBits = 52L +val DoubleBias = (1L << 10) - 1 // 1023 def CalculateMantissaAndExponent(dAsll: Long): (ULong, ULong) = { // incoming dAsll is already a double bit string @@ -1081,7 +1081,7 @@ def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { var v = vVal - if (v == DoubleZeroBitString) { + if ((v & InverseSignBitMask) == DoubleZeroBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 0, 0, 0xFF) return } From c7c4714d59ae8fef36aa1ea3fc2dc8c987e8bbab Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 16 Oct 2023 16:45:42 +0200 Subject: [PATCH 015/174] fix missed OptionMut --- .../scala/asn1scala/asn1jvm_encoding.scala | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index c591f378d..04949a192 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -72,22 +72,12 @@ def BitStream_Init(count: Int): BitStream = { BitStream(Array.fill(count)(0), 0, 0) } -// TODO remove whole init func - streaming mode code -def BitStream_Init2(count: Int, @scala.annotation.unused fetchDataPrm: Option[Any], @scala.annotation.unused pushDataPrm: Option[Any]): BitStream = { - BitStream(Array.fill(count)(0), 0, 0) -} - - def BitStream_AttachBuffer(pBitStrm: BitStream, buf: Array[UByte]): Unit = { pBitStrm.buf = buf // TODO: fix illegal aliasing pBitStrm.currentByte = 0 pBitStrm.currentBit = 0 } -// TODO removed unused params -def BitStream_AttachBuffer2(pBitStrm: BitStream, buf: Array[UByte], @scala.annotation.unused fetchDataPrm: Option[Any], @scala.annotation.unused pushDataPrm: Option[Any]): Unit = { - BitStream_AttachBuffer(pBitStrm, buf) -} def BitStream_GetLength(pBitStrm: BitStream): Int = { var ret: Int = pBitStrm.currentByte @@ -1255,7 +1245,7 @@ def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern } -def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): Option[(Array[UByte], Int)] = { +def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { var checkBitPatternPresentResult: Int = 0 var bitsRead: Int = 0 @@ -1266,7 +1256,7 @@ def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_patter while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do decreases(nMaxReadBits - bitsRead) BitStream_ReadBit(pBitStrm) match - case None() => return None() + case None() => return NoneMut() case Some(bitVal) => BitStream_AppendBit(tmpStrm, bitVal) bitsRead += 1 @@ -1278,9 +1268,9 @@ def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_patter checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) if checkBitPatternPresentResult != 2 then - return None() + return NoneMut() - return Some((tmpStrm.buf, bitsRead)) + return SomeMut((tmpStrm.buf, bitsRead)) } From 6c934c7ff215606902bd6de53ac63bd461a5b51f Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 16 Oct 2023 16:54:17 +0200 Subject: [PATCH 016/174] fix additional missed OptionMut --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 04949a192..200280943 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -476,7 +476,6 @@ def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): OptionMut[Array[ def BitStream_ReadBits(pBitStrm: BitStream, nbits: Int): OptionMut[Array[UByte]] = { val bytesToRead: Int = nbits / 8 val remainingBits: UByte = (nbits % 8).toByte - var ret: Boolean = false BitStream_DecodeOctetString_no_length(pBitStrm, bytesToRead) match case NoneMut() => return NoneMut() @@ -1314,9 +1313,9 @@ def BitStream_EncodeOctetString_no_length(pBitStrm: BitStream, arr: Array[UByte] } -def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Option[Array[UByte]] = { +def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): OptionMut[Array[UByte]] = { val cb: Int = pBitStrm.currentBit - var arr: Array[UByte] = Array.fill(nCount+1)(0) + val arr: Array[UByte] = Array.fill(nCount+1)(0) if cb == 0 then //#ifdef ASN1SCC_STREAMING From 32fabcfee57b217a64cbedb1df5ac11bcfa7474f Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 16 Oct 2023 17:10:56 +0200 Subject: [PATCH 017/174] real bitstring decoding for stainless --- .../scala/asn1scala/asn1jvm_encoding.scala | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 200280943..8e586700b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1058,9 +1058,8 @@ def CalculateMantissaAndExponent(dAsll: Long): (ULong, ULong) = { (exponent, mantissa) } -def GetDoubleByMantissaAndExp(mantissa: ULong, exponentVal: Int): Double = { - return java.lang.Double.longBitsToDouble(((exponentVal + DoubleBias + - DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask)) +def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { + ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) } @extern @@ -1123,38 +1122,46 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { BitStream_EncodeNonNegativeInteger(pBitStrm, mantissa) } - +@extern def BitStream_DecodeReal(pBitStrm: BitStream): Option[Double] = { + BitStream_DecodeRealBitString(pBitStrm) match + case None() => + None() + case Some(ll) => + Some(java.lang.Double.longBitsToDouble(ll)) +} + +def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { BitStream_ReadByte(pBitStrm) match - case None() => return None() + case None() => None() case Some(length) => if length == 0 then - return Some(0.0) + return Some(0) BitStream_ReadByte(pBitStrm) match - case None() => return None() + case None() => None() case Some(header) => if header == 0x40 then - return Some(Double.PositiveInfinity) + return Some(DoublePosInfBitString) if header == 0x41 then - return Some(Double.NegativeInfinity) + return Some(DoubleNegInfBitString) - return DecodeRealAsBinaryEncoding(pBitStrm, length.toInt - 1, header) + DecodeRealAsBinaryEncoding(pBitStrm, length.toInt - 1, header) } -def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Double] = { +def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { var length = lengthVal - var sign: Int = 1 + var setSign = false /*int base=2;*/ var factor: ULong = 1 var expFactor: Int = 1 var N: ULong = 0 if (header & 0x40) > 0 then - sign = -1 + setSign = true if (header & 0x10) > 0 then /*base = 8;*/ expFactor = 3 @@ -1196,12 +1203,12 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt j += 1 /* *v = N*factor * pow(base,exp);*/ - var v: Double = GetDoubleByMantissaAndExp(N * factor, expFactor * exponent) + var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) - if sign < 0 then - v = -v + if setSign then + v |= SignBitMask - return Some(v) + Some(v) } def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { From 42b79b0a4d2374cd1f6bb942d923f8b343d3a325 Mon Sep 17 00:00:00 2001 From: Mario Bucev Date: Tue, 17 Oct 2023 14:31:45 +0200 Subject: [PATCH 018/174] Some changes for running Stainless on asn1jvm --- .../src/main/scala/asn1scala/asn1jvm.scala | 1 + .../scala/asn1scala/asn1jvm_encoding.scala | 28 +++++++------ .../asn1scala/asn1jvm_encoding_uper.scala | 32 +++++++-------- .../scala/asn1scala/stainless_utils.scala | 39 +++++++++++++++++++ 4 files changed, 72 insertions(+), 28 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 861afc92a..b3c2eaebd 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -11,6 +11,7 @@ type UByte = Byte type UShort = Short type UInt = Int type ULong = Long +@extern type RealNoRTL = Float type BooleanNoRTL = Boolean type ASCIIChar = UByte diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 8e586700b..e04b767b1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -47,10 +47,11 @@ def ByteStream_Init(count: Int): ByteStream = { ByteStream(Array.fill(count)(0), 0, false) } +@extern def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { - pStrm.buf = buf // TODO: fix illegal aliasing + pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... pStrm.currentByte = 0 -} +}.ensuring(_ => pStrm.buf == buf && pStrm.currentByte == 0 && pStrm.EncodeWhiteSpace == old(pStrm).EncodeWhiteSpace) def ByteStream_GetLength(pStrm: ByteStream): Int = { pStrm.currentByte @@ -60,7 +61,7 @@ def ByteStream_GetLength(pStrm: ByteStream): Int = { /** Bit Stream Functions **/ /***********************************************************************************************/ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { - arr1.sameElements(arr2) + arraySameElements(arr1, arr2) //return // (nBitsLength1 == nBitsLength2) && // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && @@ -72,11 +73,12 @@ def BitStream_Init(count: Int): BitStream = { BitStream(Array.fill(count)(0), 0, 0) } +@extern def BitStream_AttachBuffer(pBitStrm: BitStream, buf: Array[UByte]): Unit = { - pBitStrm.buf = buf // TODO: fix illegal aliasing + pBitStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... pBitStrm.currentByte = 0 pBitStrm.currentBit = 0 -} +}.ensuring(_ => pBitStrm.buf == buf && pBitStrm.currentByte == 0 && pBitStrm.currentBit == 0) def BitStream_GetLength(pBitStrm: BitStream): Int = { @@ -1304,7 +1306,7 @@ def BitStream_EncodeOctetString_no_length(pBitStrm: BitStream, arr: Array[UByte] ret = pBitStrm.currentByte + nCount <= pBitStrm.buf.length if ret then //memcpy(pBitStrm.buf(pBitStrm.currentByte), arr, nCount) - arr.copyToArray(pBitStrm.buf, pBitStrm.currentByte, nCount) + copyToArray(arr, pBitStrm.buf, pBitStrm.currentByte, nCount) pBitStrm.currentByte += nCount //#endif @@ -1345,14 +1347,14 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt return NoneMut() //memcpy(arr, pBitStrm.buf(pBitStrm.currentByte), nCount) - pBitStrm.buf.slice(pBitStrm.currentByte, pBitStrm.currentByte+nCount).copyToArray(arr) + arrayCopyOffset(pBitStrm.buf, arr, pBitStrm.currentByte, pBitStrm.currentByte+nCount, 0) pBitStrm.currentByte += nCount //#endif else BitStream_ReadByteArray(pBitStrm, nCount) match case NoneMut() => return NoneMut() - case SomeMut(a) => a.copyToArray(arr) + case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) return SomeMut(arr) } @@ -1466,7 +1468,9 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: nLengthTmp1 += nRemainingItemsVar1 if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return SomeMut(arr.take(nLengthTmp1.toInt)) + val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) + arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) + return SomeMut(newArr) else return NoneMut() @@ -1580,7 +1584,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l - var arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) while (nRemainingItemsVar1 & 0xC0) == 0xC0 do //decreases() if nRemainingItemsVar1 == 0xC4 then @@ -1602,7 +1606,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa BitStream_ReadBits(pBitStrm, nCurBlockSize1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => - Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match @@ -1622,7 +1626,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa BitStream_ReadBits(pBitStrm, nRemainingItemsVar1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => - Array.copy(t, 0, arr, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) nLengthTmp1 += nRemainingItemsVar1 if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then return SomeMut(arr) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index 712cd1177..8bda59c07 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -118,18 +118,18 @@ def ObjectIdentifier_uper_decode_lentg(pBitStrm: BitStream): Option[Long] = { return Some(totalSize) } -def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifier] = { +def ObjectIdentifier_uper_decode(pBitStrm: BitStream): OptionMut[Asn1ObjectIdentifier] = { var si: ULong = 0 var totalSize: Long = 0 - var pVal = ObjectIdentifier_Init() + val pVal = ObjectIdentifier_Init() ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None() => return None() + case None() => return NoneMut() case Some(l) => totalSize = l ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return None() - case Some(l, ul) => + case None() => return NoneMut() + case Some((l, ul)) => totalSize = l si = ul @@ -140,8 +140,8 @@ def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifi decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return None() - case Some(l, ul) => + case None() => return NoneMut() + case Some((l, ul)) => totalSize = l si = ul @@ -150,25 +150,25 @@ def ObjectIdentifier_uper_decode(pBitStrm: BitStream): Option[Asn1ObjectIdentifi //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH if totalSize == 0 then - Some(pVal) + SomeMut(pVal) else - None() + NoneMut() } -def RelativeOID_uper_decode (pBitStrm: BitStream): Option[Asn1ObjectIdentifier] = { +def RelativeOID_uper_decode (pBitStrm: BitStream): OptionMut[Asn1ObjectIdentifier] = { var si: ULong = 0 var totalSize: Long = 0 - var pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() + val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None() => return None() + case None() => return NoneMut() case Some(l) => totalSize = l while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return None() - case Some(l, ul) => + case None() => return NoneMut() + case Some((l, ul)) => totalSize = l si = ul pVal.values(pVal.nCount) = si @@ -176,7 +176,7 @@ def RelativeOID_uper_decode (pBitStrm: BitStream): Option[Asn1ObjectIdentifier] //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH if totalSize == 0 then - Some(pVal) + SomeMut(pVal) else - None() + NoneMut() } diff --git a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala index 1924eab1d..94f99ee4d 100644 --- a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala +++ b/asn1scala/src/main/scala/asn1scala/stainless_utils.scala @@ -19,6 +19,45 @@ val masksc: Array[Byte] = Array( -0x02, // / 1111 1110 / ) +def arrayRangesEqOffset[T](a1: Array[T], a2: Array[T], fromA1: Int, toA1: Int, fromA2: Int): Boolean = { + require(0 <= fromA1 && fromA1 <= toA1) + require(toA1 <= a1.length) + require(0 <= fromA2 && fromA2 <= a2.length - (toA1 - fromA1)) + decreases(toA1 - fromA1) + if (fromA1 == toA1) true + else a1(fromA1) == a2(fromA2) && arrayRangesEqOffset(a1, a2, fromA1 + 1, toA1, fromA2 + 1) +} + +def arrayCopyOffset[T](src: Array[T], dst: Array[T], fromSrc: Int, toSrc: Int, fromDst: Int): Unit = { + require(0 <= fromSrc && fromSrc <= toSrc) + require(toSrc <= src.length) + require(0 <= fromDst && fromDst <= dst.length - (toSrc - fromSrc)) + decreases(toSrc - fromSrc) + + if (fromSrc < toSrc) { + dst(fromDst) = src(fromSrc) + arrayCopyOffset(src, dst, fromSrc + 1, toSrc, fromDst + 1) + } +} + +def arrayCopyOffsetLen[T](src: Array[T], dst: Array[T], fromSrc: Int, fromDst: Int, len: Int): Unit = { + require(0 <= len && len <= src.length && len <= dst.length) + require(0 <= fromSrc && fromSrc <= src.length - len) + require(0 <= fromDst && fromDst <= dst.length - len) + arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) +} + +def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { + require(0 <= len && len <= src.length) + require(0 <= startInDst && startInDst <= src.length - len) + require(src.length <= dst.length) + arrayCopyOffset(src, dst, 0, len, startInDst) +} + +def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = + a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) + +// TODO: Reimplement in terms of arrayRangesEqOffset def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { require(0 <= from && from <= to) require(a1.length <= a2.length) From 26c6e6376ab5c6c92b401eec6b4fcfbc073fae35 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 18 Oct 2023 17:47:54 +0200 Subject: [PATCH 019/174] WIP: verify encoding methods --- .../scala/asn1scala/asn1jvm_encoding.scala | 74 +++++++++++-------- 1 file changed, 42 insertions(+), 32 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index e04b767b1..9c62af6e1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -838,7 +838,7 @@ def BitStream_DecodeConstraintWholeNumberByte(pBitStrm: BitStream, min: Byte, ma def BitStream_DecodeConstraintWholeNumberShort(pBitStrm: BitStream, min: Short, max: Short): Option[Short] = { - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match case None() => None() case Some(l) => Some(l.toShort) } @@ -846,36 +846,47 @@ def BitStream_DecodeConstraintWholeNumberShort(pBitStrm: BitStream, min: Short, def BitStream_DecodeConstraintWholeNumberInt(pBitStrm: BitStream, min: Int, max: Int): Option[Int] = { - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match case None() => None() case Some(l) => Some(l.toInt) } +/* + * Meths to upcast unsigned integer data types on the JVM + */ + extension (ub: UByte) { + def unsignedToLong: Long = ub & 0xFFL + } + +extension (us: UShort) { + def unsignedToLong: Long = us & 0xFF_FFL +} + +extension (ui: UInt) { + def unsignedToLong: Long = ui & 0xFF_FF_FF_FFL +} def BitStream_DecodeConstraintWholeNumberUByte(pBitStrm: BitStream, min: UByte, max: UByte): Option[UByte] = { - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toByte) } - def BitStream_DecodeConstraintWholeNumberUShort(pBitStrm: BitStream, min: UShort, max: UShort): Option[UShort] = { - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toShort) } - def BitStream_DecodeConstraintWholeNumberUInt(pBitStrm: BitStream, min: UInt, max: UInt): Option[UInt] = { - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toInt) } - def BitStream_DecodeConstraintPosWholeNumber(pBitStrm: BitStream, min: ULong, max: ULong): Option[ULong] = { require(max >= 0 && max <= Long.MaxValue) require(min >= 0 && min <= max) @@ -1327,36 +1338,18 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt val arr: Array[UByte] = Array.fill(nCount+1)(0) if cb == 0 then - //#ifdef ASN1SCC_STREAMING - // var remainingBytesToRead: Int = nCount - // while remainingBytesToRead > 0 do - // decreases(remainingBytesToRead) - // val currentBatch: Int = - // if pBitStrm.currentByte + remainingBytesToRead <= pBitStrm.buf.length then - // remainingBytesToRead else - // pBitStrm.buf.length - pBitStrm.currentByte - // - // Array.copy(pBitStrm.buf, pBitStrm.currentByte, arr, 0, currentBatch) // TODO: 0? - // //memcpy(arr, pBitStrm.buf(pBitStrm.currentByte), currentBatch) // STAINLESS: howto? Array.copy - // pBitStrm.currentByte += currentBatch - // bitstream_fetch_data_if_required(pBitStrm) - // remainingBytesToRead -= currentBatch - // - //#else if pBitStrm.currentByte + nCount > pBitStrm.buf.length then return NoneMut() - //memcpy(arr, pBitStrm.buf(pBitStrm.currentByte), nCount) arrayCopyOffset(pBitStrm.buf, arr, pBitStrm.currentByte, pBitStrm.currentByte+nCount, 0) pBitStrm.currentByte += nCount - //#endif else BitStream_ReadByteArray(pBitStrm, nCount) match case NoneMut() => return NoneMut() case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) - return SomeMut(arr) + SomeMut(arr) } @@ -1408,6 +1401,8 @@ def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UB } def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) var nCount: Int = 0 @@ -1416,12 +1411,16 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: var nCurBlockSize1: Long = 0 var nCurOffset1: Long = 0 + // get header data BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l + // 11xx_xxxx header, there is a next fragment while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - //decreases() + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + + // get current block size if nRemainingItemsVar1 == 0xC4 then nCurBlockSize1 = 0x10000 else if nRemainingItemsVar1 == 0xC3 then @@ -1433,6 +1432,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: else return NoneMut() + // fill current payload fragment into dest var i1: Int = nCurOffset1.toInt while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) @@ -1441,23 +1441,31 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: case Some(ub) => arr(i1) = ub i1 += 1 + // sum combined length nLengthTmp1 += nCurBlockSize1 + // set offset for next run nCurOffset1 += nCurBlockSize1 + + // get next header BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l + // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower if (nRemainingItemsVar1 & 0x80) > 0 then - nRemainingItemsVar1 <<= 8 + nRemainingItemsVar1 <<= 8 // put upper at correct position + // get size (lower byte) BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match case None() => return NoneMut() case Some(l) => - nRemainingItemsVar1 |= l - nRemainingItemsVar1 &= 0x7FFF + nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size + nRemainingItemsVar1 &= 0x7FFF // clear the control bit if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then var i1: Int = nCurOffset1.toInt + + // fill last payload fragment into dest while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) BitStream_ReadByte(pBitStrm) match @@ -1465,8 +1473,10 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: case Some(ub) => arr(i1) = ub i1 += 1 + // add remainingSize to already written size - this var holds the absolut number in all fragments nLengthTmp1 += nRemainingItemsVar1 + // resize output array and copy data if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) @@ -1474,7 +1484,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: else return NoneMut() - return NoneMut() + NoneMut() } From ba1c1330662d07c94509f40982a358ac52d62743 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 19 Oct 2023 11:33:09 +0200 Subject: [PATCH 020/174] - add some requires - remove STREAMING_MODE stuff --- .../scala/asn1scala/asn1jvm_encoding.scala | 36 +++++-------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 9c62af6e1..36f5d26e0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -169,6 +169,7 @@ def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { xxx0???? **/ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { + require(pBitStrm.currentByte < pBitStrm.buf.length) val nmask = ~masks(pBitStrm.currentBit) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte if pBitStrm.currentBit < 7 then @@ -215,6 +216,7 @@ def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { } def BitStream_AppendBits(pBitStrm: BitStream, srcBuffer: Array[UByte], nbits: Int): Unit = { + require(nbits/8 < srcBuffer.length) var lastByte: UByte = 0 val bytesToEncode: Int = nbits / 8 @@ -302,7 +304,7 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni v = (~v).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >> cb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte pBitStrm.currentByte += 1 ghostExpr { @@ -359,6 +361,7 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { + require(pBitStrm.currentByte < pBitStrm.buf.length) val cb: UByte = pBitStrm.currentBit.toByte val ncb: UByte = (8-cb).toByte @@ -380,6 +383,8 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { } def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { + require(0 <= arr_len && arr_len <= arr.length) + require(pBitStrm.currentByte+arr_len < pBitStrm.buf.length) //static byte masks[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; //static byte masksb[] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF }; @@ -390,7 +395,7 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I val nmask: UByte = (~mask).toByte //if (pBitStrm->currentByte + (int)arr_len + (cb > 0 ? 1 : 0) >= pBitStrm->count) - if (pBitStrm.currentByte+arr_len).toLong*8 + pBitStrm.currentBit > pBitStrm.buf.length.toLong*8 then + if (pBitStrm.currentByte.toLong+arr_len)*8 + pBitStrm.currentBit > pBitStrm.buf.length.toLong*8 then return false if arr_len > 0 then @@ -1298,37 +1303,14 @@ def BitStream_EncodeOctetString_no_length(pBitStrm: BitStream, arr: Array[UByte] var ret: Boolean = false if cb == 0 then - //#ifdef ASN1SCC_STREAMING -// var remainingBytesToSend: Int = nCount -// while remainingBytesToSend > 0 do -// decreases(remainingBytesToSend) -// val currentBatch = -// if pBitStrm.currentByte + remainingBytesToSend <= pBitStrm.buf.length then -// remainingBytesToSend -// else -// pBitStrm.buf.length - pBitStrm.currentByte -// -// //memcpy(pBitStrm.buf(pBitStrm.currentByte), arr, currentBatch) // STAINLESS: Array.copy -// pBitStrm.currentByte += currentBatch -// bitstream_push_data_if_required(pBitStrm) -// remainingBytesToSend -= currentBatch - - //else ret = pBitStrm.currentByte + nCount <= pBitStrm.buf.length if ret then - //memcpy(pBitStrm.buf(pBitStrm.currentByte), arr, nCount) copyToArray(arr, pBitStrm.buf, pBitStrm.currentByte, nCount) pBitStrm.currentByte += nCount - //#endif else ret = BitStream_AppendByteArray(pBitStrm, arr, nCount) - /*var i1 = 0 - while i1 < nCount && ret do - decreases(nCount - i1) - ret = BitStream_AppendByte0(pBitStrm, arr(i1)) - i1 += 1 - */ + ret } @@ -1596,7 +1578,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - //decreases() + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease if nRemainingItemsVar1 == 0xC4 then nCurBlockSize1 = 0x10000 else if nRemainingItemsVar1 == 0xC3 then From 7357c4e6548990d12716bcab2e0a2fd9edd6435c Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 19 Oct 2023 15:17:17 +0200 Subject: [PATCH 021/174] unsignedToByte extension for Int --- .../scala/asn1scala/asn1jvm_encoding.scala | 16 +---------- .../scala/asn1scala/asn1jvm_unsigned.scala | 27 +++++++++++++++++++ asn1scc/GenerateRTL.fs | 1 + asn1scc/asn1scc.fsproj | 3 +++ 4 files changed, 32 insertions(+), 15 deletions(-) create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 36f5d26e0..326c7734a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -205,7 +205,7 @@ def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { var nbits = nbitsVal while nbits >= 8 do decreases(nbits) - BitStream_AppendByte(pBitStrm, 0xFF.toByte, false) + BitStream_AppendByte(pBitStrm, 0xFF.unsignedToByte, false) nbits -= 8 var i = 0 @@ -856,20 +856,6 @@ def BitStream_DecodeConstraintWholeNumberInt(pBitStrm: BitStream, min: Int, max: case Some(l) => Some(l.toInt) } -/* - * Meths to upcast unsigned integer data types on the JVM - */ - extension (ub: UByte) { - def unsignedToLong: Long = ub & 0xFFL - } - -extension (us: UShort) { - def unsignedToLong: Long = us & 0xFF_FFL -} - -extension (ui: UInt) { - def unsignedToLong: Long = ui & 0xFF_FF_FF_FFL -} def BitStream_DecodeConstraintWholeNumberUByte(pBitStrm: BitStream, min: UByte, max: UByte): Option[UByte] = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala new file mode 100644 index 000000000..55155390c --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala @@ -0,0 +1,27 @@ +package asn1scala + + +/* +* Meths to upcast unsigned integer data types on the JVM +*/ +extension (ub: UByte) { + def unsignedToLong: Long = ub & 0xFFL +} + +extension (us: UShort) { + def unsignedToLong: Long = us & 0xFF_FFL +} + +extension (ui: UInt) { + def unsignedToLong: Long = ui & 0xFF_FF_FF_FFL +} + +extension (i: Int) { + def unsignedToByte: UByte = { + require(i >= 0 && i <= 0xFF) + if ((i & 0x80) == 0x80) + ((i & 0x7F) - 0x80).toByte + else + i.toByte + } +} \ No newline at end of file diff --git a/asn1scc/GenerateRTL.fs b/asn1scc/GenerateRTL.fs index 4c94b13f8..ad1abf724 100644 --- a/asn1scc/GenerateRTL.fs +++ b/asn1scc/GenerateRTL.fs @@ -109,6 +109,7 @@ let exportRTL (di:DirInfo) (l:ProgrammingLanguage) (args:CommandLineSettings)= | _ -> writeResource di "asn1jvm_encoding.scala" None + writeResource di "asn1jvm_unsigned.scala" None writeResource di "stainless_utils.scala" None // needed for verification if hasUper || hasAcn then diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index cfb65f324..8dcfbf2ad 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -103,6 +103,9 @@ stainless_utils.scala + + asn1jvm_unsigned.scala + From ffbb0ec95ed0ec4448023d42ddc71b7fefcb4c1d Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 19 Oct 2023 15:21:24 +0200 Subject: [PATCH 022/174] WIP: verification --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 36f5d26e0..c8405a379 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -724,12 +724,13 @@ def GetNumberOfBitsForNonNegativeInteger32(vVal: Int): Int = { ret = 24 v = v >>> 24 - while v > 0 do + (while v > 0 do decreases(v) v = v >>> 1 ret += 1 + ).invariant(ret >= 0 && ret <= 32) - return ret + ret } def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { if WORD_SIZE == 8 then @@ -1555,6 +1556,7 @@ def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: In def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax <= Int.MaxValue) if (asn1SizeMax < 65536) { var nCount: Long = 0 From 5bca6a516075e17151d418d45637affa83c08adc Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 19 Oct 2023 15:22:19 +0200 Subject: [PATCH 023/174] some verifications on BitStream_AppendNBitOne, BitStream_AppendByteArray --- .../scala/asn1scala/asn1jvm_encoding.scala | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index c9475912e..af032d153 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -202,17 +202,21 @@ def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { } def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { + require(nbitsVal >= 0) + require(pBitStrm.bitIndex() + nbitsVal <= pBitStrm.buf.length.toLong * 8) var nbits = nbitsVal - while nbits >= 8 do + + (while nbits >= 8 do decreases(nbits) BitStream_AppendByte(pBitStrm, 0xFF.unsignedToByte, false) nbits -= 8 + ).invariant(pBitStrm.bitIndex()+nbits <= pBitStrm.buf.length.toLong * 8) - var i = 0 - while i < nbits do - decreases(nbits - i) + (while nbits > 0 do + decreases(nbits) BitStream_AppendBitOne(pBitStrm) - i+= 1 + nbits -= 1 + ).invariant(nbits >= 0 && pBitStrm.bitIndex()+nbits <= pBitStrm.buf.length.toLong * 8) } def BitStream_AppendBits(pBitStrm: BitStream, srcBuffer: Array[UByte], nbits: Int): Unit = { @@ -384,7 +388,7 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { require(0 <= arr_len && arr_len <= arr.length) - require(pBitStrm.currentByte+arr_len < pBitStrm.buf.length) + require(pBitStrm.currentByte < pBitStrm.buf.length - arr_len) //static byte masks[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; //static byte masksb[] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF }; @@ -409,7 +413,7 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte var i: Int = 1 - while i < arr_len-1 do + (while i < arr_len-1 do decreases(arr_len-1-i) val v: UByte = arr(i) val v1: UByte = ((v & 0xFF) >>> cb).toByte @@ -419,6 +423,7 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I bitstream_push_data_if_required(pBitStrm) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | v2).toByte i += 1 + ).invariant(1 <= i &&& i <= arr_len-1 &&& pBitStrm.currentByte < pBitStrm.buf.length) if arr_len - 1 > 0 then val v: UByte = arr(arr_len - 1) From d60fadfc7d27d823e18efb1b507250915e151268 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 19 Oct 2023 15:49:05 +0200 Subject: [PATCH 024/174] removed WORD_LENGTH - makes no sense on the JVM --- .../src/main/scala/asn1scala/asn1jvm.scala | 6 ++-- .../scala/asn1scala/asn1jvm_encoding.scala | 25 ++++++------- .../asn1scala/asn1jvm_encoding_acn.scala | 36 ++++++------------- .../asn1scala/asn1jvm_encoding_uper.scala | 4 +-- 4 files changed, 27 insertions(+), 44 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index b3c2eaebd..a661427d8 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -25,7 +25,7 @@ type ULongNoRTL = ULong @extern type asn1Real = Double -val WORD_SIZE = 8 +val NO_OF_BYTES_IN_JVM_LONG = 8 val OBJECT_IDENTIFIER_MAX_LENGTH = 20 val NOT_INITIALIZED_ERR_CODE = 1337 @@ -65,12 +65,12 @@ def uint2int(v: ULong, uintSizeInBytes: Int): Long = { if !bIsNegative then return v - var i: Int = WORD_SIZE-1 + var i: Int = NO_OF_BYTES_IN_JVM_LONG-1 (while i >= uintSizeInBytes do decreases(i) vv |= ber_aux(i) i -= 1 - ).invariant(i <= WORD_SIZE-1 && i >= uintSizeInBytes - 1) + ).invariant(i <= NO_OF_BYTES_IN_JVM_LONG-1 && i >= uintSizeInBytes - 1) -(~vv) - 1 } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index c9475912e..a4ee83c54 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -731,26 +731,23 @@ def GetNumberOfBitsForNonNegativeInteger32(vVal: Int): Int = { ).invariant(ret >= 0 && ret <= 32) ret -} +}.ensuring(ret => 0 <= ret && ret <= 32) + def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { - if WORD_SIZE == 8 then - if v >>> 32 == 0 then - return GetNumberOfBitsForNonNegativeInteger32(v.toInt) - else - val hi = (v >>> 32).toInt - return 32 + GetNumberOfBitsForNonNegativeInteger32(hi) + if v >>> 32 == 0 then + GetNumberOfBitsForNonNegativeInteger32(v.toInt) else - return GetNumberOfBitsForNonNegativeInteger32(v.toInt) + val hi = (v >>> 32).toInt + 32 + GetNumberOfBitsForNonNegativeInteger32(hi) } def GetLengthInBytesOfUInt (v: ULong): Int = { var ret: Int = 0 var v32: UInt = v.toInt - //if (WORD_SIZE == 8) { + if v > 0xFFFFFFFF.toLong then ret = 4 v32 = (v >>> 32).toInt - // } if v32 < 0x100 then return ret + 1 @@ -765,11 +762,10 @@ def GetLengthInBytesOfUInt (v: ULong): Int = { def GetLengthSIntHelper(v: ULong): Int = { var ret: Int = 0 var v32: UInt = v.toInt - //#if WORD_SIZE == 8 + if v > 0x7FFFFFFF then ret = 4 v32 = (v >>> 32).toInt - //#endif if v32 <= 0x7F then return ret + 1 @@ -777,14 +773,15 @@ def GetLengthSIntHelper(v: ULong): Int = { return ret + 2 if v32 <= 0x7FFFFF then return ret + 3 - return ret + 4 + + ret + 4 } def GetLengthInBytesOfSInt (v: Long): Int = { if v >= 0 then return GetLengthSIntHelper(v) - return GetLengthSIntHelper((-v - 1)) + GetLengthSIntHelper((-v - 1)) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index 54fdd639d..d0b3d04b0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -99,14 +99,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm: BitStream, int def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm: BitStream, intVal: ULong): Unit = { - // Avoid dead code warnings by conditionally compiling this part. - /*#if WORD_SIZE != 8 - int i; - for (i = 0; i < 8 - WORD_SIZE; i ++) { - BitStream_AppendByte0(pBitStrm, 0x0); - } - #endif*/ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm, intVal, WORD_SIZE) + Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm, intVal, NO_OF_BYTES_IN_JVM_LONG) } def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, intVal: ULong, size: Int): Unit = @@ -135,13 +128,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm: BitStream, def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm: BitStream, intVal: ULong): Unit = { - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, intVal, WORD_SIZE) - // Avoid dead code warnings by conditionally compiling this part. - if WORD_SIZE != 8 then - var i: Int = 0 - while i < 8 - WORD_SIZE do - BitStream_AppendByte0(pBitStrm, 0x0) - i += 1 + Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, intVal, NO_OF_BYTES_IN_JVM_LONG) } @@ -188,9 +175,9 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm: BitStream): Op def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm: BitStream): Option[ULong] = { - pBitStrm.currentByte += (8 - WORD_SIZE) + pBitStrm.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm, WORD_SIZE) + Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm, NO_OF_BYTES_IN_JVM_LONG) } def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, SizeInBytes: Int): Option[ULong] = @@ -223,22 +210,22 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm: BitStream): def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm: BitStream): Option[ULong] = { - val ret = Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, WORD_SIZE) - pBitStrm.currentByte += (8 - WORD_SIZE) + val ret = Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, NO_OF_BYTES_IN_JVM_LONG) + pBitStrm.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) ret } def Encode_UnsignedInteger(pBitStrm: BitStream, v: ULong, nBytes: Byte): Unit = { - val MAX_BYTE_MASK = if WORD_SIZE == 8 then 0xFF00000000000000L else 0xFF000000 + val MAX_BYTE_MASK = 0xFF00000000000000L assert(nBytes <= 8) - var vv: ULong = v << (WORD_SIZE * 8 -nBytes * 8) + var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 -nBytes * 8) var i: Int = 0 while i < nBytes do - val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((WORD_SIZE - 1) * 8)).toByte + val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte BitStream_AppendByte0(pBitStrm, ByteToEncode) vv <<= 8 i += 1 @@ -376,7 +363,7 @@ def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm: BitStream): Opt { Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match case None() => None() - case Some(ul) => Some(uint2int(ul, WORD_SIZE)) + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) } def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm: BitStream): Option[Long] = @@ -397,11 +384,10 @@ def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm: BitStream): { Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match case None() => None() - case Some(ul) => Some(uint2int(ul, WORD_SIZE)) + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) } - def Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: Long): Unit = { val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index 8bda59c07..8930be41b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -29,7 +29,7 @@ def ObjectIdentifier_subidentifiers_uper_encode(encodingBuf: Array[UByte], pSize return pSize } def ObjectIdentifier_uper_encode(pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): Unit = { - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (WORD_SIZE + 2))(0) + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) var totalSize: Int = 0 var i: Int = 0 @@ -56,7 +56,7 @@ def ObjectIdentifier_uper_encode(pBitStrm: BitStream, pVal: Asn1ObjectIdentifier def RelativeOID_uper_encode (pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): Unit = { //a subifentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (WORD_SIZE + 2))(0) + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) var totalSize: Int = 0 var i: Int = 0 From c97a726a6efbebb9cc368d65020e9a760887ba3e Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 19 Oct 2023 17:22:05 +0200 Subject: [PATCH 025/174] try to verify GetNumberOfBitsForNonNegativeInteger --- .../scala/asn1scala/asn1jvm_encoding.scala | 5 ++- .../scala/asn1scala/asn1jvm_unsigned.scala | 44 +++++++++++++++---- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 4707cdc9f..1d71b14e0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -208,7 +208,7 @@ def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { (while nbits >= 8 do decreases(nbits) - BitStream_AppendByte(pBitStrm, 0xFF.unsignedToByte, false) + BitStream_AppendByte(pBitStrm, 0xFF.toUnsignedByte, false) nbits -= 8 ).invariant(pBitStrm.bitIndex()+nbits <= pBitStrm.buf.length.toLong * 8) @@ -742,7 +742,8 @@ def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { if v >>> 32 == 0 then GetNumberOfBitsForNonNegativeInteger32(v.toInt) else - val hi = (v >>> 32).toInt + val hs = v >>> 32 + val hi = hs.toUnsignedInt 32 + GetNumberOfBitsForNonNegativeInteger32(hi) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala index 55155390c..a3674b1f0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala @@ -1,27 +1,55 @@ package asn1scala +// all bits of the integer +val MASK_BYTE = 0xFFL +val MASK_SHORT = 0xFF_FFL +val MASK_INT = 0xFF_FF_FF_FFL + +// MSBs (neg bits of the integer) +val MASK_MSB_BYTE = 0x80L +val MASK_MSB_INT = 0x80_00_00_00L + +// pos bits of the integer +val MASK_POS_BYTE = 0x7FL +val MASK_POS_INT = 0x7F_FF_FF_FFL /* * Meths to upcast unsigned integer data types on the JVM */ extension (ub: UByte) { - def unsignedToLong: Long = ub & 0xFFL + def unsignedToLong: Long = ub & MASK_BYTE } extension (us: UShort) { - def unsignedToLong: Long = us & 0xFF_FFL + def unsignedToLong: Long = us & MASK_SHORT } extension (ui: UInt) { - def unsignedToLong: Long = ui & 0xFF_FF_FF_FFL + def unsignedToLong: Long = ui & MASK_INT } extension (i: Int) { - def unsignedToByte: UByte = { - require(i >= 0 && i <= 0xFF) - if ((i & 0x80) == 0x80) - ((i & 0x7F) - 0x80).toByte + def toUnsignedByte: UByte = { + require(i >= 0 && i <= MASK_BYTE) + + if(i == MASK_MSB_BYTE) + (-MASK_MSB_BYTE).toByte + else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) + ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte else i.toByte } -} \ No newline at end of file +} + +extension (l: Long) { + def toUnsignedInt: UInt = { + require(l >= 0 && l <= MASK_INT) + + if(l == MASK_MSB_INT) + (-MASK_MSB_INT).toInt + else if ((l & MASK_MSB_INT) == MASK_MSB_INT) + ((l & MASK_POS_INT) - MASK_MSB_INT).toInt + else + l.toInt + } +} From 17bbc9e52a1157d8bb8d8bbacdf7303c43dc92cf Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 19 Oct 2023 19:32:28 +0200 Subject: [PATCH 026/174] verified GetNumberOfBitsForNonNegativeInteger32 --- .../scala/asn1scala/asn1jvm_encoding.scala | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1d71b14e0..8e4b8bf58 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -713,30 +713,42 @@ def BitStream_EncodeNonNegativeIntegerNeg(pBitStrm: BitStream, v: ULong, negate: } -def GetNumberOfBitsForNonNegativeInteger32(vVal: Int): Int = { - var ret: Int = 0 - - var v = vVal +def bar(v: UInt): (UInt, Int) = { if v >>> 8 == 0 then - ret = 0 + (v, 0) else if v >>> 16 == 0 then - ret = 8 - v = v >>> 8 + (v >>> 8, 8) else if v >>> 24 == 0 then - ret = 16 - v = v >>> 16 + (v >>> 16, 16) else - ret = 24 - v = v >>> 24 + (v >>> 24, 24) +}.ensuring((v,n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24 &&& 256 > (v >>> n) ) - (while v > 0 do - decreases(v) - v = v >>> 1 - ret += 1 - ).invariant(ret >= 0 && ret <= 32) +def fooRec (vVal: UInt, n: UInt): Int = { + require(vVal >= 0 && vVal <= 0xFF) + require(n >= 0 && n <= 8) + require(1<<(8-n) > vVal) + decreases(8-n) - ret -}.ensuring(ret => 0 <= ret && ret <= 32) + if(vVal == 0) then + n + else + fooRec(vVal >>> 1, n+1) +} + + +def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { + + val (ret, n) = bar(vVal) + n + fooRec(ret, 0) +// (while v > 0 do +// decreases(v) +// v = v >>> 1 +// ret += 1 +// ).invariant(v >= 0 && ret >= 0 && ret <= 32) +// +// ret +} def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { if v >>> 32 == 0 then From 9756a6917213989640a199313e808c5e8aae428b Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 19 Oct 2023 19:44:08 +0200 Subject: [PATCH 027/174] better naming --- .../scala/asn1scala/asn1jvm_encoding.scala | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 8e4b8bf58..82c7830c6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -713,7 +713,7 @@ def BitStream_EncodeNonNegativeIntegerNeg(pBitStrm: BitStream, v: ULong, negate: } -def bar(v: UInt): (UInt, Int) = { +def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { if v >>> 8 == 0 then (v, 0) else if v >>> 16 == 0 then @@ -724,7 +724,7 @@ def bar(v: UInt): (UInt, Int) = { (v >>> 24, 24) }.ensuring((v,n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24 &&& 256 > (v >>> n) ) -def fooRec (vVal: UInt, n: UInt): Int = { +def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { require(vVal >= 0 && vVal <= 0xFF) require(n >= 0 && n <= 8) require(1<<(8-n) > vVal) @@ -733,21 +733,13 @@ def fooRec (vVal: UInt, n: UInt): Int = { if(vVal == 0) then n else - fooRec(vVal >>> 1, n+1) + GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) } def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { - - val (ret, n) = bar(vVal) - n + fooRec(ret, 0) -// (while v > 0 do -// decreases(v) -// v = v >>> 1 -// ret += 1 -// ).invariant(v >= 0 && ret >= 0 && ret <= 32) -// -// ret + val (ret, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) + n + GetNumberOfBitsInLastByteRec(ret, 0) } def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { From 2d87a9e465f1fa28bad7e7197ce73a2960ffcb4f Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 20 Oct 2023 09:18:29 +0200 Subject: [PATCH 028/174] formatting comments --- .../scala/asn1scala/asn1jvm_encoding.scala | 80 +++++++++---------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 82c7830c6..ea9cc021a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -10,38 +10,38 @@ import StaticChecks.* val masks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 - 0x40, // 64 / 0100 0000 / x40 - 0x20, // 32 / 0010 0000 / x20 - 0x10, // 16 / 0001 0000 / x10 - 0x08, // 8 / 0000 1000 / x08 - 0x04, // 4 / 0000 0100 / x04 - 0x02, // 2 / 0000 0010 / x02 - 0x01, // 1 / 0000 0001 / x01 + 0x40, // 64 / 0100 0000 / x40 + 0x20, // 32 / 0010 0000 / x20 + 0x10, // 16 / 0001 0000 / x10 + 0x08, // 8 / 0000 1000 / x08 + 0x04, // 4 / 0000 0100 / x04 + 0x02, // 2 / 0000 0010 / x02 + 0x01, // 1 / 0000 0001 / x01 ) val masksb: Array[UByte] = Array( - 0x00, // 0 / 0000 0000 / x00 - 0x01, // 1 / 0000 0001 / x01 - 0x03, // 3 / 0000 0011 / x03 - 0x07, // 7 / 0000 0111 / x07 - 0x0F, // 15 / 0000 1111 / x0F - 0x1F, // 31 / 0001 1111 / x1F - 0x3F, // 63 / 0011 1111 / x3F + 0x00, // 0 / 0000 0000 / x00 + 0x01, // 1 / 0000 0001 / x01 + 0x03, // 3 / 0000 0011 / x03 + 0x07, // 7 / 0000 0111 / x07 + 0x0F, // 15 / 0000 1111 / x0F + 0x1F, // 31 / 0001 1111 / x1F + 0x3F, // 63 / 0011 1111 / x3F 0x7F, // 127 / 0111 1111 / x7F - -0x1, // -1 / 1111 1111 / xFF + -0x1, // -1 / 1111 1111 / xFF ) val masks2: Array[UInt] = Array( - 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x00000000 - 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x000000FF - 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000FF00 - 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF0000 - 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF000000 + 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 + 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF + 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000 FF00 + 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF 0000 + 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 ) /***********************************************************************************************/ -/** Byte Stream Functions **/ +/** Byte Stream Functions **/ /***********************************************************************************************/ def ByteStream_Init(count: Int): ByteStream = { ByteStream(Array.fill(count)(0), 0, false) @@ -58,7 +58,7 @@ def ByteStream_GetLength(pStrm: ByteStream): Int = { } /***********************************************************************************************/ -/** Bit Stream Functions **/ +/** Bit Stream Functions **/ /***********************************************************************************************/ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { arraySameElements(arr1, arr2) @@ -92,15 +92,15 @@ def BitStream_GetLength(pBitStrm: BitStream): Int = { Append bit one. Example - cur bit = 3 + cur bit = 3 x x x | |_|_|_|_|_|_|_|_| 0 1 2 3 4 5 6 7 - xxxy???? -or 00010000 ------------- - xxx1???? + xxxy???? +or 00010000 +------------- + xxx1???? **/ def isPrefix(b1: BitStream, b2: BitStream): Boolean = { @@ -159,14 +159,14 @@ def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { Example cur bit = 3 - x x x | + x x x | |_|_|_|_|_|_|_|_| - 0 1 2 3 4 5 6 7 + 0 1 2 3 4 5 6 7 - xxxy???? + xxxy???? and 11101111 - ------------ - xxx0???? + -------- + xxx0???? **/ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { require(pBitStrm.currentByte < pBitStrm.buf.length) @@ -279,19 +279,19 @@ Append byte. Example cur bit = 3 - | + | x x x b b b b b b b b |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 first byte - xxx????? -and 11100000 (mask) ------------- - xxx00000 + xxx????? +and 11100000 (mask) +-------------- + xxx00000 or 000bbbbb ------------- - xxxbbbbb +-------------- + xxxbbbbb **/ @@ -584,7 +584,7 @@ def BitStream_ReadPartialByte(pBitStrm: BitStream, nbits: UByte): Option[UByte] /***********************************************************************************************/ /***********************************************************************************************/ /***********************************************************************************************/ -/** Integer Functions **/ +/** Integer Functions **/ /***********************************************************************************************/ /***********************************************************************************************/ /***********************************************************************************************/ From 69a72890bb0325a203497ecfb4033bf786e2056e Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 20 Oct 2023 13:28:17 +0200 Subject: [PATCH 029/174] - byte to byte shift - start validating BitStream_AppendByte --- .../scala/asn1scala/asn1jvm_encoding.scala | 8 +++--- .../scala/asn1scala/asn1jvm_unsigned.scala | 27 ++++++++++++++----- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index ea9cc021a..1893e587e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -307,8 +307,8 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni if negate then v = (~v).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte // set bits right of currentbit to zero (where our value will be inserted) + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>>> cb)).toByte // set value into bits right of currentbit, but keep bits to the left pBitStrm.currentByte += 1 ghostExpr { @@ -323,8 +323,8 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni if cb > 0 then mask = (~mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v << ncb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte // set bits to the left of currentbit in next byte to zero (where the rest of our value will be inserted) + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v <<<< ncb)).toByte // set value into the bits left of currentbit, but keep the bits to the right ghostExpr { arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte - 1, pBitStrm.buf(pBitStrm.currentByte - 1)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala index a3674b1f0..34620ff37 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala @@ -1,9 +1,10 @@ package asn1scala // all bits of the integer -val MASK_BYTE = 0xFFL -val MASK_SHORT = 0xFF_FFL -val MASK_INT = 0xFF_FF_FF_FFL +val MASK_BYTE = 0xFF +val MASK_BYTE_L = 0xFFL +val MASK_SHORT_L = 0xFF_FFL +val MASK_INT_L = 0xFF_FF_FF_FFL // MSBs (neg bits of the integer) val MASK_MSB_BYTE = 0x80L @@ -17,15 +18,15 @@ val MASK_POS_INT = 0x7F_FF_FF_FFL * Meths to upcast unsigned integer data types on the JVM */ extension (ub: UByte) { - def unsignedToLong: Long = ub & MASK_BYTE + def unsignedToLong: Long = ub & MASK_BYTE_L } extension (us: UShort) { - def unsignedToLong: Long = us & MASK_SHORT + def unsignedToLong: Long = us & MASK_SHORT_L } extension (ui: UInt) { - def unsignedToLong: Long = ui & MASK_INT + def unsignedToLong: Long = ui & MASK_INT_L } extension (i: Int) { @@ -43,7 +44,7 @@ extension (i: Int) { extension (l: Long) { def toUnsignedInt: UInt = { - require(l >= 0 && l <= MASK_INT) + require(l >= 0 && l <= MASK_INT_L) if(l == MASK_MSB_INT) (-MASK_MSB_INT).toInt @@ -53,3 +54,15 @@ extension (l: Long) { l.toInt } } + +extension (b: Byte) { + def >>>>(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte + } + + def <<<<(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt << i) & MASK_BYTE).toUnsignedByte + } +} From 9cf9d97984f0b4225b8bce17145b1004005c7ca5 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 20 Oct 2023 13:36:19 +0200 Subject: [PATCH 030/174] validate BitStream_AppendByte0 --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1893e587e..24cbfaffb 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -365,14 +365,14 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { - require(pBitStrm.currentByte < pBitStrm.buf.length) + require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) val cb: UByte = pBitStrm.currentBit.toByte val ncb: UByte = (8-cb).toByte var mask = ~masksb(ncb) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>>> cb)).toByte pBitStrm.currentByte += 1 bitstream_push_data_if_required(pBitStrm) @@ -381,7 +381,7 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { return false mask = ~mask pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte + pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v <<<< ncb)).toByte true } From 0c1dac4883c8a19614dc922ae4135fe15b141c3d Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 20 Oct 2023 15:45:11 +0200 Subject: [PATCH 031/174] added Asn1Real_Equal and replaced doubleToLongBits with doubleToRawLongBits that does not mask the mantissa away in an NaN case --- StgScala/equal_scala.stg | 2 +- .../src/main/scala/asn1scala/asn1jvm.scala | 31 +++++++++++++++++++ .../scala/asn1scala/asn1jvm_encoding.scala | 25 +++------------ 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/StgScala/equal_scala.stg b/StgScala/equal_scala.stg index d6baf846e..e4e86f8aa 100644 --- a/StgScala/equal_scala.stg +++ b/StgScala/equal_scala.stg @@ -93,7 +93,7 @@ isEqual_Enumerated(p1, p2) /*nogen*/::= "" isEqual_Boolean(p1, p2) /*nogen*/::= "ret = ( ( && ) || (! && !))" -isEqual_Real(p1, p2) ::= " == " +isEqual_Real(p1, p2) ::= "Asn1Real_Equal(, )" isEqual_IA5String(p1, p2) /*nogen*/::= "ret = (strcmp(, ) ==0)" diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index a661427d8..d48315d76 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -31,6 +31,23 @@ val OBJECT_IDENTIFIER_MAX_LENGTH = 20 val NOT_INITIALIZED_ERR_CODE = 1337 val ERR_INVALID_ENUM_VALUE = 2805 +// Floating Point Masks +val ExpoBitMask = 0x7ff0_0000_0000_0000L +val MantissaBitMask = 0x000f_ffff_ffff_ffffL +val MantissaExtraBit = 0x0010_0000_0000_0000L // hidden bit +val SignBitMask = 0x8000_0000_0000_0000L +val InverseSignBitMask = 0x7fff_ffff_ffff_ffffL + +val DoublePosInfBitString = 0x7ff0_0000_0000_0000L +val DoubleNegInfBitString = 0xfff0_0000_0000_0000L +val DoubleZeroBitString = 0x0000_0000_0000_0000L + +val NoOfSignBit = 1 // double & float +val DoubleNoOfExponentBits = 11L +val DoubleNoOfMantissaBits = 52L +val DoubleBias = (1L << 10) - 1 // 1023 + + val ber_aux: Array[ULong] = Array( 0xFFL, 0xFF00L, @@ -231,6 +248,20 @@ case class Asn1DateTimeWithTimeZone( enum Asn1TimeZoneClass: case Asn1TC_LocalTimeStamp, Asn1TC_UtcTimeStamp, Asn1TC_LocalTimeTZStamp +@extern +def Asn1Real_Equal(left: Double, right: Double): Boolean = { + if left == right then + true + else if left == 0.0 then + right == 0.0 // why?? + else if (left > 0.0 && right < 0.0) || (left < 0.0 && right > 0.0) then + false + else if Math.abs(left) > Math.abs(right) then + Math.abs(right) / Math.abs(left) >= 0.99999 + else + Math.abs(left) / Math.abs(right) >= 0.99999 +} + /** ####### ### diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 82c7830c6..a7c47b800 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -773,15 +773,15 @@ def GetLengthSIntHelper(v: ULong): Int = { var ret: Int = 0 var v32: UInt = v.toInt - if v > 0x7FFFFFFF then + if v > Int.MaxValue then ret = 4 v32 = (v >>> 32).toInt - if v32 <= 0x7F then + if v32 <= Byte.MaxValue then return ret + 1 - if v32 <= 0x7FFF then + if v32 <= Short.MaxValue then return ret + 2 - if v32 <= 0x7FFFFF then + if v32 <= 0x7F_FF_FF then return ret + 3 ret + 4 @@ -1042,21 +1042,6 @@ cd:11 --> 1 byte for encoding the length of the exponent, then the expoent +-+-+-+-+-+-+-+-+ **/ -val ExpoBitMask = 0x7ff0_0000_0000_0000L -val MantissaBitMask = 0x000f_ffff_ffff_ffffL -val MantissaExtraBit = 0x0010_0000_0000_0000L // hidden bit -val SignBitMask = 0x8000_0000_0000_0000L -val InverseSignBitMask = 0x7fff_ffff_ffff_ffffL - -val DoublePosInfBitString = 0x7ff0_0000_0000_0000L -val DoubleNegInfBitString = 0xfff0_0000_0000_0000L -val DoubleZeroBitString = 0x0000_0000_0000_0000L - -val NoOfSignBit = 1 // double & float -val DoubleNoOfExponentBits = 11L -val DoubleNoOfMantissaBits = 52L -val DoubleBias = (1L << 10) - 1 // 1023 - def CalculateMantissaAndExponent(dAsll: Long): (ULong, ULong) = { // incoming dAsll is already a double bit string @@ -1076,7 +1061,7 @@ def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long @extern def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { - BitStream_EncodeRealBitString(pBitStrm, java.lang.Double.doubleToLongBits(vVal)) + BitStream_EncodeRealBitString(pBitStrm, java.lang.Double.doubleToRawLongBits(vVal)) } def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { From c4337a2eab3945168d6c4e752afedb4e274e70e4 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 20 Oct 2023 23:55:38 +0200 Subject: [PATCH 032/174] rewrote all byte counting meths and verified them --- .../src/main/scala/asn1scala/asn1jvm.scala | 2 + .../scala/asn1scala/asn1jvm_encoding.scala | 54 +++---------------- 2 files changed, 10 insertions(+), 46 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index d48315d76..7a508ed52 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -25,6 +25,8 @@ type ULongNoRTL = ULong @extern type asn1Real = Double +val NO_OF_BITS_IN_BYTE = 8 +val NO_OF_BITS_IN_LONG = 64 val NO_OF_BYTES_IN_JVM_LONG = 8 val OBJECT_IDENTIFIER_MAX_LENGTH = 20 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1bcd48e29..138f3da89 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -736,7 +736,6 @@ def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) } - def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { val (ret, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) n + GetNumberOfBitsInLastByteRec(ret, 0) @@ -744,56 +743,19 @@ def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { if v >>> 32 == 0 then - GetNumberOfBitsForNonNegativeInteger32(v.toInt) + GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) else - val hs = v >>> 32 - val hi = hs.toUnsignedInt - 32 + GetNumberOfBitsForNonNegativeInteger32(hi) -} + val h = (v >>> 32).toUnsignedInt + 32 + GetNumberOfBitsForNonNegativeInteger32(h) +}.ensuring(n => n >= 0 && n <= 64) def GetLengthInBytesOfUInt (v: ULong): Int = { - var ret: Int = 0 - var v32: UInt = v.toInt - - if v > 0xFFFFFFFF.toLong then - ret = 4 - v32 = (v >>> 32).toInt - - if v32 < 0x100 then - return ret + 1 - if v32 < 0x10000 then - return ret + 2 - if v32 < 0x1000000 then - return ret + 3 - - return ret + 4 -} - -def GetLengthSIntHelper(v: ULong): Int = { - var ret: Int = 0 - var v32: UInt = v.toInt - - if v > Int.MaxValue then - ret = 4 - v32 = (v >>> 32).toInt - - if v32 <= Byte.MaxValue then - return ret + 1 - if v32 <= Short.MaxValue then - return ret + 2 - if v32 <= 0x7F_FF_FF then - return ret + 3 - - ret + 4 -} + GetLengthInBytesOfSInt(v) // just call signed, is signed anyway +}.ensuring(n => n >= 0 && n <= NO_OF_BYTES_IN_JVM_LONG) def GetLengthInBytesOfSInt (v: Long): Int = { - if v >= 0 then - return GetLengthSIntHelper(v) - - GetLengthSIntHelper((-v - 1)) -} - + min((GetNumberOfBitsForNonNegativeInteger(v) / NO_OF_BITS_IN_BYTE) + 1, 8) +}.ensuring(n => n >= 0 && n <= NO_OF_BYTES_IN_JVM_LONG) def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long, max: Long): Unit = { require(min <= max) From f52ba3cb843d86815cde240d9e9f6cfc8d39b56a Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 23 Oct 2023 19:48:10 +0200 Subject: [PATCH 033/174] verifying REAL encode / dec --- .../scala/asn1scala/asn1jvm_encoding.scala | 93 +++++++++++-------- 1 file changed, 53 insertions(+), 40 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 138f3da89..4a8014bbc 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -979,7 +979,7 @@ def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = } /** -Bynary encoding will be used +Binary encoding will be used REAL = M*B^E where M = S*N*2^F @@ -996,7 +996,7 @@ ab: F (0..3) cd:00 --> 1 byte for exponent as 2's complement cd:01 --> 2 byte for exponent as 2's complement cd:10 --> 3 byte for exponent as 2's complement -cd:11 --> 1 byte for encoding the length of the exponent, then the expoent +cd:11 --> 1 byte for encoding the length of the exponent, then the exponent 8 7 6 5 4 3 2 1 +-+-+-+-+-+-+-+-+ @@ -1004,18 +1004,19 @@ cd:11 --> 1 byte for encoding the length of the exponent, then the expoent +-+-+-+-+-+-+-+-+ **/ -def CalculateMantissaAndExponent(dAsll: Long): (ULong, ULong) = { +def CalculateMantissaAndExponent(dAsll: Long): (UInt, ULong) = { // incoming dAsll is already a double bit string - var exponent: ULong = 0 - var mantissa: ULong = 0 - - exponent = ((dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits) - DoubleBias - DoubleNoOfMantissaBits - mantissa = dAsll & MantissaBitMask + val exponent: UInt = ((dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt + var mantissa: ULong = dAsll & MantissaBitMask mantissa = mantissa | MantissaExtraBit (exponent, mantissa) -} + + // TODO remove ensuring block - just for REAL encoding test +}.ensuring((e,m) => GetLengthInBytesOfUInt(e) >= 1 &&& + GetLengthInBytesOfUInt(e) <= 3 &&& GetLengthInBytesOfUInt(m) >= 1 &&& GetLengthInBytesOfUInt(m) <= 7) + def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) @@ -1027,25 +1028,37 @@ def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { } def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { + // according to X.690 2002 + var v = vVal + + // 8.5.2 if ((v & InverseSignBitMask) == DoubleZeroBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 0, 0, 0xFF) return } + // 8.5.8 PLUS-INFINITY if (v == DoublePosInfBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) return } + // 8.5.8 MINUS-INFINITY if (v == DoubleNegInfBitString) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) return } + // 8.5.5 a) + // fixed encoding style to binary + // 8.5.6.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 + // 8.5.6.3 F value is always zero - bit 0x08 and 0x04 are always 0 var header = 0x80 + + // 8.5.6.1 if ((v & SignBitMask) == SignBitMask) { // check sign bit header |= 0x40 v &= InverseSignBitMask // clear sign bit @@ -1054,13 +1067,16 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { val (exponent, mantissa) = CalculateMantissaAndExponent(v) val nManLen: Int = GetLengthInBytesOfUInt(mantissa) + assert(nManLen <= 7) // 52 bit + val nExpLen: Int = GetLengthInBytesOfSInt(exponent) - assert(nExpLen <= 3) + assert(nExpLen >= 1 && nExpLen <= 3) // 11 bit + // 8.5.6.4 if nExpLen == 2 then - header |= 1 + header |= 0x01 else if nExpLen == 3 then - header |= 2 + header |= 0x02 /* encode length */ BitStream_EncodeConstraintWholeNumber(pBitStrm, 1 + nExpLen + nManLen, 0, 0xFF) @@ -1111,36 +1127,23 @@ def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { + require(lengthVal >= 0 && lengthVal <= Int.MaxValue) - var length = lengthVal - var setSign = false - /*int base=2;*/ - var factor: ULong = 1 - var expFactor: Int = 1 - var N: ULong = 0 + // 8.5.5 a) + assert((header & 0x80) == 0x80) - if (header & 0x40) > 0 then - setSign = true - if (header & 0x10) > 0 then - /*base = 8;*/ - expFactor = 3 - else if (header & 0x20) > 0 then - /*base = 16;*/ - expFactor = 4 - - val F: Int = ((header & 0x0C) >>> 2).toInt - factor <<= F - - val expLen: Int = ((header & 0x03) + 1).toInt - - if expLen > length then + // 8.5.6.4 + val expLen = (header & 0x03) + 1 + // sanity check + if expLen > lengthVal then return None() + val expIsNegative = BitStream_PeekBit(pBitStrm) - var exponent: Int = if expIsNegative then 0xFFFFFFFF else 0 + var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 var i: Int = 0 - while i < expLen do + (while i < expLen do decreases(expLen - i) BitStream_ReadByte(pBitStrm) match @@ -1148,23 +1151,33 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) i += 1 + ).invariant(i >= 0 && i <= expLen) - length -= expLen - + val length = lengthVal - expLen + var N: ULong = 0 var j: Int = 0 - while j < length do + (while j < length do decreases(length - j) BitStream_ReadByte(pBitStrm) match case None() => return None() - case Some(ub) => N = N << 8 | (ub.toInt & 0xFF) + case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) j += 1 + ).invariant(j >= 0 && j <= length) /* *v = N*factor * pow(base,exp);*/ + var factor = 1 << ((header & 0x0C) >>> 2) + + // parse base factor + val expFactor: Int = header match + case x if (x & 0x10) > 0 => 3 // 2^3 = 8 + case x if (x & 0x20) > 0 => 4 // 2^4 = 16 + case _ => 1 // 2^1 = 2 + var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) - if setSign then + if (header & 0x40) > 0 then v |= SignBitMask Some(v) From 065b69350045e69a861ba7f7c6353a4b7ce06b5a Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 25 Oct 2023 20:02:29 +0200 Subject: [PATCH 034/174] fixed real encoding problem --- .../scala/asn1scala/asn1jvm_encoding.scala | 53 ++++++++++++++----- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 4a8014bbc..3ed0a4e14 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -669,6 +669,7 @@ def BitStream_EncodeNonNegativeInteger(pBitStrm: BitStream, v: ULong): Unit = { //else // BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v.toInt, false) } + def BitStream_DecodeNonNegativeInteger(pBitStrm: BitStream, nBits: Int): Option[ULong] = { // TODO: support WORD_SIZE=4? // if WORD_SIZE == 8 then @@ -737,8 +738,8 @@ def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { } def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { - val (ret, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) - n + GetNumberOfBitsInLastByteRec(ret, 0) + val (v, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) + n + GetNumberOfBitsInLastByteRec(v, 0) } def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { @@ -751,11 +752,11 @@ def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { def GetLengthInBytesOfUInt (v: ULong): Int = { GetLengthInBytesOfSInt(v) // just call signed, is signed anyway -}.ensuring(n => n >= 0 && n <= NO_OF_BYTES_IN_JVM_LONG) +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) def GetLengthInBytesOfSInt (v: Long): Int = { - min((GetNumberOfBitsForNonNegativeInteger(v) / NO_OF_BITS_IN_BYTE) + 1, 8) -}.ensuring(n => n >= 0 && n <= NO_OF_BYTES_IN_JVM_LONG) + max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long, max: Long): Unit = { require(min <= max) @@ -1005,7 +1006,10 @@ cd:11 --> 1 byte for encoding the length of the exponent, then the exponent **/ def CalculateMantissaAndExponent(dAsll: Long): (UInt, ULong) = { - // incoming dAsll is already a double bit string + require({ + val rawExp = (dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits + rawExp >= 0 &&& rawExp <= ((1 << 11) - 2) // 2046, 2047 is the infinity case - never end up here with infinity + }) val exponent: UInt = ((dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt var mantissa: ULong = dAsll & MantissaBitMask @@ -1013,10 +1017,32 @@ def CalculateMantissaAndExponent(dAsll: Long): (UInt, ULong) = { (exponent, mantissa) - // TODO remove ensuring block - just for REAL encoding test -}.ensuring((e,m) => GetLengthInBytesOfUInt(e) >= 1 &&& - GetLengthInBytesOfUInt(e) <= 3 &&& GetLengthInBytesOfUInt(m) >= 1 &&& GetLengthInBytesOfUInt(m) <= 7) +}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits)) + +/** +Helper function for REAL encoding + +Negative Ints always need 4 bytes of space, the ASN.1 standard compacts those numbers down +to 8, 16 or 24 bits depending on the leading bytes full of 1s. + +Example: +-4 in Int: 0b1111_..._1111_1100 +--> compacted to 0b1111_1100 +The ASN.1 header holds the detail on how to interprete this number +**/ +def RemoveLeadingFFBytesIfNegative(v: Int): Int = { + if v >= 0 then + v + else if v >= Byte.MinValue then + v & 0xFF + else if v >= Short.MinValue then + v & 0xFF_FF + else if v >= -8_388_608 then + v & 0xFF_FF_FF + else + v +} def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) @@ -1069,8 +1095,9 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { val nManLen: Int = GetLengthInBytesOfUInt(mantissa) assert(nManLen <= 7) // 52 bit - val nExpLen: Int = GetLengthInBytesOfSInt(exponent) - assert(nExpLen >= 1 && nExpLen <= 3) // 11 bit + val compactExp = RemoveLeadingFFBytesIfNegative(exponent) + val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) + assert(nExpLen >= 1 && nExpLen <= 3) // 8.5.6.4 if nExpLen == 2 then @@ -1086,11 +1113,11 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { /* encode exponent */ if exponent >= 0 then + // fill with zeros to have a whole byte BitStream_AppendNBitZero(pBitStrm, nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) BitStream_EncodeNonNegativeInteger(pBitStrm, exponent) else - BitStream_AppendNBitOne(pBitStrm, nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(-exponent - 1)) - BitStream_EncodeNonNegativeIntegerNeg(pBitStrm, -exponent - 1, true) + BitStream_EncodeNonNegativeInteger(pBitStrm, compactExp) /* encode mantissa */ BitStream_AppendNBitZero(pBitStrm, nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) From bff94ef8f245889c5a590b7cd88f9bbce7fa17d8 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 25 Oct 2023 23:01:29 +0200 Subject: [PATCH 035/174] nan case found --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 3ed0a4e14..1518d6199 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -723,7 +723,7 @@ def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = (v >>> 16, 16) else (v >>> 24, 24) -}.ensuring((v,n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24 &&& 256 > (v >>> n) ) +}.ensuring((v, n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24) def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { require(vVal >= 0 && vVal <= 0xFF) @@ -1017,7 +1017,8 @@ def CalculateMantissaAndExponent(dAsll: Long): (UInt, ULong) = { (exponent, mantissa) -}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits)) +}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) + &&& m >= 0 &&& m <= MantissaBitMask) /** Helper function for REAL encoding @@ -1078,6 +1079,8 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { return } + // TODO NaN case fails in stainless - fix! + // 8.5.5 a) // fixed encoding style to binary // 8.5.6.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 From 66ffb2c54bae6c50e2cabbdbdd38338b17e1caf2 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 26 Oct 2023 13:58:02 +0200 Subject: [PATCH 036/174] add NaN encoding (X.690-202102) --- .../scala/asn1scala/asn1jvm_encoding.scala | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1518d6199..b491aceec 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1065,21 +1065,26 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { return } - // 8.5.8 PLUS-INFINITY - if (v == DoublePosInfBitString) { - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) - return - } - - // 8.5.8 MINUS-INFINITY - if (v == DoubleNegInfBitString) { - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) - return - } - - // TODO NaN case fails in stainless - fix! + // 8.5.9 SpecialRealValues (2021 standard) + if(v & ExpoBitMask) == ExpoBitMask then + + // 8.5.9 PLUS-INFINITY + if v == DoublePosInfBitString then + BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) + return + + // 8.5.9 MINUS-INFINITY + else if v == DoubleNegInfBitString then + BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) + return + + // 8.5.9 NOT-A-NUMBER + else + BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x42, 0, 0xFF) + return // 8.5.5 a) // fixed encoding style to binary @@ -1100,12 +1105,12 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { val compactExp = RemoveLeadingFFBytesIfNegative(exponent) val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) - assert(nExpLen >= 1 && nExpLen <= 3) + assert(nExpLen >= 1 && nExpLen <= 2) // 8.5.6.4 if nExpLen == 2 then header |= 0x01 - else if nExpLen == 3 then + else if nExpLen == 3 then // this will never happen with this implementation header |= 0x02 /* encode length */ From ed39afaf32808d031d929232f9e39496f2047b55 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 26 Oct 2023 11:05:11 +0200 Subject: [PATCH 037/174] validating BitStream_AppendBitOne --- .../src/main/scala/asn1scala/asn1jvm.scala | 68 +++++++++++++------ .../scala/asn1scala/asn1jvm_encoding.scala | 4 +- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 7a508ed52..61e6effaf 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -118,36 +118,64 @@ def asn1Real_Initialize(): asn1Real = { 0.0 } +object BitStream { + @pure @inline + def invariant(pBitStrm: BitStream): Boolean = { + BitStream.invariant(pBitStrm.currentByte, pBitStrm.currentBit, pBitStrm.buf.length) + } + + @pure @inline + def invariant(currentByte: Int, currentBit: Int, buf_length: Int): Boolean = { + 0 <= currentBit && currentBit <= 7 &&& + 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) + } + + @ghost + def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { + require(0 <= bits) + val nBits = bits % 8 + val nBytes = bits / 8 + + require(nBits >= 0 && nBits <= 7 && nBits <= Int.MaxValue - pBitStrm.currentBit) + val new_currentBitVal: Int = pBitStrm.currentBit + nBits + + require(nBytes >= 0 && nBytes <= Int.MaxValue - pBitStrm.currentByte - (new_currentBitVal / 8)) + var new_currentByte: Int = pBitStrm.currentByte + nBytes + + var new_currentBit = new_currentBitVal + if new_currentBit > 7 then + new_currentBit = new_currentBit % 8 + new_currentByte += 1 + + new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length) + } + + @ghost + def validate_offset_bytes(pBitStrm: BitStream, bytes: Int = 0): Boolean = { + require(bytes >= 0 && bytes <= Int.MaxValue - pBitStrm.currentByte) + + val new_currentByte: Int = pBitStrm.currentByte + bytes + new_currentByte < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && new_currentByte <= pBitStrm.buf.length) + } +} + + case class BitStream( var buf: Array[Byte], var currentByte: Int, var currentBit: Int, ) { // all BisStream instances satisfy the following: - require(0 <= currentByte && currentByte <= buf.length) - require(0 <= currentBit && currentBit <= 7) - require(currentByte.toLong * 8 + currentBit.toLong <= 8 * buf.length.toLong) + require(BitStream.invariant(currentByte, currentBit, buf.length)) def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) - def moveOffset(diffInBits: Long): Unit = { - require(diffInBits >= 0 && diffInBits <= 8 * buf.length.toLong) - val res = bitIndex() + diffInBits - require(0 <= res && res <= 8 * buf.length.toLong) - val nbBytes = (diffInBits / 8).toInt - val nbBits = (diffInBits % 8).toInt - currentByte += nbBytes - if (currentBit + nbBits < 0) { - currentByte -= 1 - currentBit = 8 + nbBits + currentBit - } else if (currentBit + nbBits >= 8) { - currentBit = currentBit + nbBits - 8 - currentByte += 1 - } else { - currentBit += nbBits - } - }.ensuring(_ => old(this).bitIndex() + diffInBits == bitIndex()) + @inlineOnce @opaque @ghost + def ensureInvariant(): Unit = { + }.ensuring(_ => + BitStream.invariant(currentByte, currentBit, buf.length) + ) } // BitStream class case class ByteStream ( diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index b491aceec..39c4b1099 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -128,7 +128,7 @@ def BitStream_ReadBitPure(pBitStrm: BitStream): (BitStream, Option[Boolean]) = { @opaque @inlineOnce def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { - require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bits(pBitStrm, 1)) @ghost val oldpBitStrm = snapshot(pBitStrm) val newB = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte @@ -151,7 +151,7 @@ def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { val (r1, r2) = reader(w1, w2) val (r2Got, bitGot) = BitStream_ReadBitPure(r1) bitGot.get == true && r2Got == r2 - } + } && BitStream.invariant(pBitStrm) } /** From 6cbe350a1457880dcc118b79ac8ca4a5637e6f59 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 26 Oct 2023 11:05:27 +0200 Subject: [PATCH 038/174] validating BitStream_AppendBitZero --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 39c4b1099..ea95dc605 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -169,7 +169,7 @@ def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { xxx0???? **/ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { - require(pBitStrm.currentByte < pBitStrm.buf.length) + require(BitStream.validate_offset_bits(pBitStrm, 1)) val nmask = ~masks(pBitStrm.currentBit) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte if pBitStrm.currentBit < 7 then @@ -178,8 +178,7 @@ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { pBitStrm.currentBit = 0 pBitStrm.currentByte += 1 bitstream_push_data_if_required(pBitStrm) - assert(pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8) -} +}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { require(nbits < Int.MaxValue - pBitStrm.currentBit) From 2da9ecc6c690c6358736a77db62474c9384e44a2 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 26 Oct 2023 11:05:40 +0200 Subject: [PATCH 039/174] validating BitStream_AppendNBitZero --- .../scala/asn1scala/asn1jvm_encoding.scala | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index ea95dc605..ad140cb73 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -181,24 +181,24 @@ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { }.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { - require(nbits < Int.MaxValue - pBitStrm.currentBit) - val totalBits: Int = pBitStrm.currentBit + nbits - val totalBytes: Int = totalBits / 8 + require(0 <= nbits) + require(nbits/8 >= 0 && nbits/8 <= Int.MaxValue - pBitStrm.currentByte - (pBitStrm.currentBit+nbits%8 / 8)) + require(BitStream.validate_offset_bits(pBitStrm, nbits)) - val newCurrentBit = totalBits % 8 - assert(0 <= newCurrentBit && newCurrentBit < 8) - pBitStrm.currentBit = newCurrentBit - //pBitStrm->currentByte += totalBits / 8; + val nBits = nbits % 8 + val nBytes = nbits / 8 - if pBitStrm.currentByte <= pBitStrm.buf.length - totalBytes then - pBitStrm.currentByte += totalBytes - bitstream_push_data_if_required(pBitStrm) - else - val extraBytes: Int = pBitStrm.currentByte + totalBytes - pBitStrm.buf.length - pBitStrm.currentByte = pBitStrm.buf.length - bitstream_push_data_if_required(pBitStrm) - pBitStrm.currentByte = extraBytes -} + var new_currentBit: Int = pBitStrm.currentBit + nBits + var new_currentByte: Int = pBitStrm.currentByte + nBytes + + if new_currentBit > 7 then + new_currentBit = new_currentBit % 8 + new_currentByte += 1 + + pBitStrm.currentBit = new_currentBit + pBitStrm.currentByte = new_currentByte + +}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { require(nbitsVal >= 0) From a686589c2cec3ce37caf691fe0939d8906c21ba1 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 26 Oct 2023 16:03:00 +0200 Subject: [PATCH 040/174] - validating AppendX functions - remove bitstream_push_data_if_required stuff --- .../src/main/scala/asn1scala/asn1jvm.scala | 41 +++++-- .../scala/asn1scala/asn1jvm_encoding.scala | 103 +++++------------- .../asn1scala/asn1jvm_encoding_acn.scala | 13 --- 3 files changed, 59 insertions(+), 98 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 61e6effaf..c46e8490c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -130,24 +130,38 @@ object BitStream { 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) } + @ghost + def validate_offset_bit(pBitStrm: BitStream): Boolean = { + var new_currentBit: Int = pBitStrm.currentBit + 1 + var new_currentByte: Int = pBitStrm.currentByte + + if new_currentBit > 7 then + new_currentBit = new_currentBit % 8 + new_currentByte += 1 + + 0 <= new_currentBit + && new_currentBit <= 7 + && 0 <= new_currentByte + && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) + } + @ghost def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { require(0 <= bits) val nBits = bits % 8 val nBytes = bits / 8 - require(nBits >= 0 && nBits <= 7 && nBits <= Int.MaxValue - pBitStrm.currentBit) - val new_currentBitVal: Int = pBitStrm.currentBit + nBits - - require(nBytes >= 0 && nBytes <= Int.MaxValue - pBitStrm.currentByte - (new_currentBitVal / 8)) - var new_currentByte: Int = pBitStrm.currentByte + nBytes + var new_currentByte: Long = pBitStrm.currentByte.toLong + nBytes + var new_currentBit: Long = pBitStrm.currentBit.toLong + nBits - var new_currentBit = new_currentBitVal if new_currentBit > 7 then new_currentBit = new_currentBit % 8 new_currentByte += 1 - new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length) + 0 <= new_currentBit + && new_currentBit <= 7 + && 0 <= new_currentByte + && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) } @ghost @@ -171,6 +185,19 @@ case class BitStream( currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) + def increaseBitIndex(): Unit = { + require(currentByte < buf.length) + if currentBit < 7 then + currentBit += 1 + else + currentBit = 0 + currentByte += 1 + }.ensuring {_ => + val oldBitStrm = old(this) + oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& + BitStream.invariant(this) + } + @inlineOnce @opaque @ghost def ensureInvariant(): Unit = { }.ensuring(_ => diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index ad140cb73..f1ffb2aa7 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -121,37 +121,36 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { @ghost @pure def BitStream_ReadBitPure(pBitStrm: BitStream): (BitStream, Option[Boolean]) = { - require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bit(pBitStrm)) val cpy = snapshot(pBitStrm) (cpy , BitStream_ReadBit(cpy)) } @opaque @inlineOnce def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { - require(BitStream.validate_offset_bits(pBitStrm, 1)) + require(BitStream.validate_offset_bit(pBitStrm)) @ghost val oldpBitStrm = snapshot(pBitStrm) val newB = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte pBitStrm.buf(pBitStrm.currentByte) = newB ghostExpr { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, newB) + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, newB) } - if pBitStrm.currentBit < 7 then - pBitStrm.currentBit += 1 - else - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 + pBitStrm.increaseBitIndex() }.ensuring { _ => val w1 = old(pBitStrm) val w2 = pBitStrm - w2.bitIndex() == w1.bitIndex() + 1 && isValidPair(w1, w2) && { + w2.bitIndex() == w1.bitIndex() + 1 + &&& isValidPair(w1, w2) + &&& { val (r1, r2) = reader(w1, w2) val (r2Got, bitGot) = BitStream_ReadBitPure(r1) bitGot.get == true && r2Got == r2 - } && BitStream.invariant(pBitStrm) + } + &&& BitStream.invariant(pBitStrm) } /** @@ -172,17 +171,12 @@ def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { require(BitStream.validate_offset_bits(pBitStrm, 1)) val nmask = ~masks(pBitStrm.currentBit) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - if pBitStrm.currentBit < 7 then - pBitStrm.currentBit += 1 - else - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) + + pBitStrm.increaseBitIndex() }.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { require(0 <= nbits) - require(nbits/8 >= 0 && nbits/8 <= Int.MaxValue - pBitStrm.currentByte - (pBitStrm.currentBit+nbits%8 / 8)) require(BitStream.validate_offset_bits(pBitStrm, nbits)) val nBits = nbits % 8 @@ -201,25 +195,21 @@ def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { }.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { - require(nbitsVal >= 0) - require(pBitStrm.bitIndex() + nbitsVal <= pBitStrm.buf.length.toLong * 8) + require(0 <= nbitsVal) + require(BitStream.validate_offset_bits(pBitStrm, nbitsVal)) var nbits = nbitsVal - (while nbits >= 8 do - decreases(nbits) - BitStream_AppendByte(pBitStrm, 0xFF.toUnsignedByte, false) - nbits -= 8 - ).invariant(pBitStrm.bitIndex()+nbits <= pBitStrm.buf.length.toLong * 8) - (while nbits > 0 do decreases(nbits) BitStream_AppendBitOne(pBitStrm) nbits -= 1 - ).invariant(nbits >= 0 && pBitStrm.bitIndex()+nbits <= pBitStrm.buf.length.toLong * 8) + ).invariant(nbits >= 0 &&& BitStream.validate_offset_bits(pBitStrm, nbits)) + () } def BitStream_AppendBits(pBitStrm: BitStream, srcBuffer: Array[UByte], nbits: Int): Unit = { - require(nbits/8 < srcBuffer.length) + require(0 <= nbits && nbits/8 < srcBuffer.length) + require(BitStream.validate_offset_bits(pBitStrm, nbits)) var lastByte: UByte = 0 val bytesToEncode: Int = nbits / 8 @@ -233,44 +223,31 @@ def BitStream_AppendBits(pBitStrm: BitStream, srcBuffer: Array[UByte], nbits: In } def BitStream_AppendBit(pBitStrm: BitStream, v: Boolean): Unit = { - // TODO: currentByte=pBitStrm.buf.length temp possible, but with bitstream_push_data_if_required set to 0 again - require(pBitStrm.currentByte + (pBitStrm.currentBit+1) / 8 < pBitStrm.buf.length) + require(BitStream.validate_offset_bits(pBitStrm, 1)) if v then pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte else val nmask = ~masks(pBitStrm.currentBit) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - if pBitStrm.currentBit < 7 then - pBitStrm.currentBit += 1 - else - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) - - assert(pBitStrm.currentByte + pBitStrm.currentBit/8 <= pBitStrm.buf.length) -} + pBitStrm.increaseBitIndex() +}.ensuring(_ => BitStream.invariant(pBitStrm)) // TODO check if needs Marios implementation def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { - require(pBitStrm.bitIndex() + 1 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bit(pBitStrm)) val ret = (pBitStrm.buf(pBitStrm.currentByte) & masks(pBitStrm.currentBit)) != 0 - if pBitStrm.currentBit < 7 then - pBitStrm.currentBit += 1 - else - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 - bitstream_fetch_data_if_required(pBitStrm) + pBitStrm.increaseBitIndex() if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then Some(ret) else None() -} +}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_PeekBit(pBitStrm: BitStream): Boolean = { - ((pBitStrm.buf(pBitStrm.currentByte) & 0xFF) & (masks(pBitStrm.currentBit) & 0xFF)) > 0 + ((pBitStrm.buf(pBitStrm.currentByte) & 0xFF) & (masks(pBitStrm.currentBit) & 0xFF)) > 0 } /** @@ -360,7 +337,7 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni val (r1, r2) = reader(w1, w2) val (r2Got, vGot) = BitStream_ReadBytePure(r1) vGot.get == value && r2Got == r2 - } + } && BitStream.invariant(pBitStrm) } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { @@ -373,7 +350,6 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>>> cb)).toByte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) if cb > 0 then if pBitStrm.currentByte >= pBitStrm.buf.length then @@ -406,7 +382,6 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte //make zero right bits (i.e. the ones that will get the new value) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte //shift right and then populate current byte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte @@ -419,7 +394,6 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I val v2: UByte = ((v & 0xFF) << ncb).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | v1).toByte //shift right and then populate current byte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | v2).toByte i += 1 ).invariant(1 <= i &&& i <= arr_len-1 &&& pBitStrm.currentByte < pBitStrm.buf.length) @@ -429,7 +403,6 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask ).toByte //make zero right bits (i.e. the ones that will get the new value) pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte //shift right and then populate current byte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) if cb > 0 then pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte @@ -445,7 +418,6 @@ def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { var v: UByte = (pBitStrm.buf(pBitStrm.currentByte) << cb).toByte pBitStrm.currentByte += 1 - bitstream_fetch_data_if_required(pBitStrm) if cb > 0 then v = (v | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> ncb).toByte // TODO: check if & 0xFF is needed @@ -477,7 +449,6 @@ def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): OptionMut[Array[ decreases(arr_len - i) arr(i) = (pBitStrm.buf(pBitStrm.currentByte) << cb).toByte pBitStrm.currentByte += 1 - bitstream_fetch_data_if_required(pBitStrm) arr(i) = (arr(i) | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> ncb).toByte i += 1 @@ -530,14 +501,12 @@ def BitStream_AppendPartialByte(pBitStrm: BitStream, vVal: UByte, nbits: UByte, if pBitStrm.currentBit == 8 then pBitStrm.currentBit = 0 pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) } else { val totalBitsForNextByte: UByte = (totalBits - 8).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask1).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>> totalBitsForNextByte)).toByte pBitStrm.currentByte += 1 - bitstream_push_data_if_required(pBitStrm) val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v << (8 - totalBitsForNextByte))).toByte @@ -560,13 +529,11 @@ def BitStream_ReadPartialByte(pBitStrm: BitStream, nbits: UByte): Option[UByte] if pBitStrm.currentBit == 8 then pBitStrm.currentBit = 0 pBitStrm.currentByte += 1 - bitstream_fetch_data_if_required(pBitStrm) } else { var totalBitsForNextByte: UByte = (totalBits - 8).toByte v = (pBitStrm.buf(pBitStrm.currentByte) << totalBitsForNextByte).toByte pBitStrm.currentByte += 1 - bitstream_fetch_data_if_required(pBitStrm) v = (v | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> (8 - totalBitsForNextByte)).toByte v = (v & masksb(nbits)).toByte pBitStrm.currentBit = totalBitsForNextByte.toInt @@ -1614,23 +1581,3 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa } return NoneMut() } - -//#ifdef ASN1SCC_STREAMING -//def fetchData(pBitStrm: BitStream, fetchDataPrm: Option[Any]) = ??? -//def pushData(pBitStrm: BitStream, pushDataPrm: Option[Any]) = ??? -// -// -//def bitstream_fetch_data_if_required(pStrm: BitStream): Unit = { -// if pStrm.currentByte == pStrm.buf.length && pStrm.fetchDataPrm != null then -// fetchData(pStrm, pStrm.fetchDataPrm) -// pStrm.currentByte = 0 -//} -//def bitstream_push_data_if_required(pStrm: BitStream): Unit = { -// if pStrm.currentByte == pStrm.buf.length && pStrm.pushDataPrm != null then -// pushData(pStrm, pStrm.pushDataPrm) -// pStrm.currentByte = 0 -//} -//#endif - -def bitstream_fetch_data_if_required(pStrm: BitStream): Unit = {} -def bitstream_push_data_if_required(pStrm: BitStream): Unit = {} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index d0b3d04b0..e88e1189b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -9,10 +9,6 @@ def Acn_AlignToNextByte(pBitStrm: BitStream, bEncode: Boolean): Unit = if pBitStrm.currentBit != 0 then pBitStrm.currentBit = 0 pBitStrm.currentByte += 1 - if bEncode then - bitstream_push_data_if_required(pBitStrm) - else - bitstream_fetch_data_if_required(pBitStrm) CHECK_BIT_STREAM(pBitStrm) } @@ -21,11 +17,6 @@ def Acn_AlignToNextWord(pBitStrm: BitStream, bEncode: Boolean): Unit = Acn_AlignToNextByte(pBitStrm, bEncode) pBitStrm.currentByte += pBitStrm.currentByte % 2 - if bEncode then - bitstream_push_data_if_required(pBitStrm) - else - bitstream_fetch_data_if_required(pBitStrm) - CHECK_BIT_STREAM(pBitStrm) } @@ -40,10 +31,6 @@ def Acn_AlignToNextDWord(pBitStrm: BitStream, bEncode: Boolean): Unit = else val extraBytes: Int = pBitStrm.currentByte + totalBytes - pBitStrm.buf.length pBitStrm.currentByte = pBitStrm.buf.length - if bEncode then - bitstream_push_data_if_required(pBitStrm) - else - bitstream_fetch_data_if_required(pBitStrm) pBitStrm.currentByte = extraBytes CHECK_BIT_STREAM(pBitStrm) From 5d0f0b4c4b356fd34d38ef8d27f90b5c9cb94ee8 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 26 Oct 2023 16:35:33 +0200 Subject: [PATCH 041/174] use ensuring from Stainless --- .../src/main/scala/asn1scala/asn1jvm.scala | 24 ++++++++++--------- .../scala/asn1scala/asn1jvm_encoding.scala | 1 + 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index c46e8490c..b8517f608 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -2,6 +2,7 @@ package asn1scala import stainless.lang.{None => None, Option => Option, _} import stainless.annotation._ +import StaticChecks.* // type used in ErrorCases type ErrorCode = Int @@ -132,17 +133,18 @@ object BitStream { @ghost def validate_offset_bit(pBitStrm: BitStream): Boolean = { - var new_currentBit: Int = pBitStrm.currentBit + 1 - var new_currentByte: Int = pBitStrm.currentByte - - if new_currentBit > 7 then - new_currentBit = new_currentBit % 8 - new_currentByte += 1 - - 0 <= new_currentBit - && new_currentBit <= 7 - && 0 <= new_currentByte - && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) +// var new_currentBit: Int = pBitStrm.currentBit + 1 +// var new_currentByte: Int = pBitStrm.currentByte +// +// if new_currentBit > 7 then +// new_currentBit = new_currentBit % 8 +// new_currentByte += 1 +// +// 0 <= new_currentBit +// && new_currentBit <= 7 +// && 0 <= new_currentByte +// && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && pBitStrm.currentByte <= pBitStrm.buf.length)) + pBitStrm.currentByte < pBitStrm.buf.length } @ghost diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index f1ffb2aa7..1a6849bf0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -247,6 +247,7 @@ def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { }.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_PeekBit(pBitStrm: BitStream): Boolean = { + require(pBitStrm.currentByte < pBitStrm.buf.length) ((pBitStrm.buf(pBitStrm.currentByte) & 0xFF) & (masks(pBitStrm.currentBit) & 0xFF)) > 0 } From 88b66a67e00b3b515af29527c2d83669b5bb9eaf Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 26 Oct 2023 16:58:05 +0200 Subject: [PATCH 042/174] encoder done, decoder started --- .../src/main/scala/asn1scala/asn1jvm.scala | 19 ++-- .../scala/asn1scala/asn1jvm_encoding.scala | 92 ++++++++++++------- .../scala/asn1scala/asn1jvm_unsigned.scala | 1 + 3 files changed, 71 insertions(+), 41 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 7a508ed52..fbc5aac7a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -33,16 +33,19 @@ val OBJECT_IDENTIFIER_MAX_LENGTH = 20 val NOT_INITIALIZED_ERR_CODE = 1337 val ERR_INVALID_ENUM_VALUE = 2805 -// Floating Point Masks -val ExpoBitMask = 0x7ff0_0000_0000_0000L -val MantissaBitMask = 0x000f_ffff_ffff_ffffL +// Floating Point Mask & Variables +val ExpoBitMask = 0x7FF0_0000_0000_0000L +val MantissaBitMask = 0x000F_FFFF_FFFF_FFFFL val MantissaExtraBit = 0x0010_0000_0000_0000L // hidden bit val SignBitMask = 0x8000_0000_0000_0000L -val InverseSignBitMask = 0x7fff_ffff_ffff_ffffL - -val DoublePosInfBitString = 0x7ff0_0000_0000_0000L -val DoubleNegInfBitString = 0xfff0_0000_0000_0000L -val DoubleZeroBitString = 0x0000_0000_0000_0000L +val InverseSignBitMask = 0x7FFF_FFFF_FFFF_FFFFL + +val DoublePosInfBitString = ExpoBitMask +val DoubleNegInfBitString = 0xFFF0_0000_0000_0000L +val DoublePosZeroBitString = 0x0000_0000_0000_0000L +val DoubleNegZeroBitString = SignBitMask +val DoubleNotANumber = 0x7FF8_0000_0000_0000L // definied in java.lang.Double.NaN +val DoubleMaxLengthOfSentBytes = 10 // mantissa max 7, exp max 2, header 1 val NoOfSignBit = 1 // double & float val DoubleNoOfExponentBits = 11L diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index b491aceec..d185ed2aa 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1055,44 +1055,49 @@ def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { } def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { - // according to X.690 2002 + // according to T-REC-X.690 2021 var v = vVal - // 8.5.2 - if ((v & InverseSignBitMask) == DoubleZeroBitString) { + // 8.5.2 Plus Zero + if v == DoublePosZeroBitString then BitStream_EncodeConstraintWholeNumber(pBitStrm, 0, 0, 0xFF) - return - } + return; + + // 8.5.3 Minus Zero + if v == DoubleNegZeroBitString then + BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x43, 0, 0xFF) + return; // 8.5.9 SpecialRealValues (2021 standard) - if(v & ExpoBitMask) == ExpoBitMask then + if (v & ExpoBitMask) == ExpoBitMask then // 8.5.9 PLUS-INFINITY if v == DoublePosInfBitString then BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) - return + return; // 8.5.9 MINUS-INFINITY else if v == DoubleNegInfBitString then BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) - return + return; // 8.5.9 NOT-A-NUMBER else BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x42, 0, 0xFF) - return + return; - // 8.5.5 a) + // 8.5.6 a) // fixed encoding style to binary - // 8.5.6.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 - // 8.5.6.3 F value is always zero - bit 0x08 and 0x04 are always 0 + // 8.5.7.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 + // 8.5.7.3 F value is always zero - bit 0x08 and 0x04 are always 0 var header = 0x80 - // 8.5.6.1 + // 8.5.7.1 if ((v & SignBitMask) == SignBitMask) { // check sign bit header |= 0x40 v &= InverseSignBitMask // clear sign bit @@ -1107,7 +1112,7 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) assert(nExpLen >= 1 && nExpLen <= 2) - // 8.5.6.4 + // 8.5.7.4 if nExpLen == 2 then header |= 0x01 else if nExpLen == 3 then // this will never happen with this implementation @@ -1145,35 +1150,63 @@ def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { BitStream_ReadByte(pBitStrm) match case None() => None() case Some(length) => + // 8.5.2 Plus Zero if length == 0 then return Some(0) + // invalid state + if length < 0 || length > DoubleMaxLengthOfSentBytes then + return None() + BitStream_ReadByte(pBitStrm) match case None() => None() case Some(header) => + // 8.5.6 a) + if (header.unsignedToInt & 0x80) != 0x80 then + return None() + + // 8.5.9 PLUS-INFINITY if header == 0x40 then - return Some(DoublePosInfBitString) + Some(DoublePosInfBitString) - if header == 0x41 then - return Some(DoubleNegInfBitString) + // 8.5.9 MINUS-INFINITY + else if header == 0x41 then + Some(DoubleNegInfBitString) - DecodeRealAsBinaryEncoding(pBitStrm, length.toInt - 1, header) -} + // 8.5.9 NOT-A-NUMBER + else if header == 0x42 then + Some(DoubleNotANumber) + + // 8.5.3 Minus Zero + else if header == 0x43 then + Some(DoubleNegZeroBitString) + // Decode 8.5.7 + else + DecodeRealAsBinaryEncoding(pBitStrm, length.toInt - 1, header) +} def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { - require(lengthVal >= 0 && lengthVal <= Int.MaxValue) + require(lengthVal >= 0 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte + require((header.unsignedToInt & 0x80) == 0x80) - // 8.5.5 a) - assert((header & 0x80) == 0x80) + // 8.5.7.2 Base + val expFactor: Int = header.unsignedToInt match + case x if (x & 0x10) > 0 => 3 // 2^3 = 8 + case x if (x & 0x20) > 0 => 4 // 2^4 = 16 + case _ => 1 // 2^1 = 2 + + // 8.5.7.3 Factor F + val factor = 1 << ((header & 0x0C) >>> 2) - // 8.5.6.4 + // 8.5.7.4 Length of Exponent val expLen = (header & 0x03) + 1 + // sanity check if expLen > lengthVal then return None() - + // decode exponent val expIsNegative = BitStream_PeekBit(pBitStrm) var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 @@ -1188,6 +1221,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt i += 1 ).invariant(i >= 0 && i <= expLen) + // decode mantissa val length = lengthVal - expLen var N: ULong = 0 var j: Int = 0 @@ -1201,17 +1235,9 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt j += 1 ).invariant(j >= 0 && j <= length) - /* *v = N*factor * pow(base,exp);*/ - var factor = 1 << ((header & 0x0C) >>> 2) - - // parse base factor - val expFactor: Int = header match - case x if (x & 0x10) > 0 => 3 // 2^3 = 8 - case x if (x & 0x20) > 0 => 4 // 2^4 = 16 - case _ => 1 // 2^1 = 2 - var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) + // 8.5.7.1 Set Sign bit if (header & 0x40) > 0 then v |= SignBitMask diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala index 34620ff37..2c4e8fdd1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala @@ -19,6 +19,7 @@ val MASK_POS_INT = 0x7F_FF_FF_FFL */ extension (ub: UByte) { def unsignedToLong: Long = ub & MASK_BYTE_L + def unsignedToInt: Int = ub & MASK_BYTE } extension (us: UShort) { From 2a31e703cb6ea098b9cf89e76b426ffdf52370da Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 26 Oct 2023 21:46:46 +0200 Subject: [PATCH 043/174] wip --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 2 +- asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 79f5de9f6..689a6e7be 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1154,7 +1154,7 @@ def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { } def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { - require(lengthVal >= 0 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte + require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) // 8.5.7.2 Base diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala index 2c4e8fdd1..fffd802bf 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala @@ -19,7 +19,7 @@ val MASK_POS_INT = 0x7F_FF_FF_FFL */ extension (ub: UByte) { def unsignedToLong: Long = ub & MASK_BYTE_L - def unsignedToInt: Int = ub & MASK_BYTE + def unsignedToInt: Int = ub.toInt & MASK_BYTE } extension (us: UShort) { From 62a70e29bf326bb0bcfc659361c2230a6914df8e Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 27 Oct 2023 10:55:22 +0200 Subject: [PATCH 044/174] validate BitStream_AppendByte --- asn1scala/src/main/scala/asn1scala/asn1jvm.scala | 4 +--- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 8 ++++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index 2412bacbb..cbb8e871e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -171,9 +171,7 @@ object BitStream { @ghost def validate_offset_bytes(pBitStrm: BitStream, bytes: Int = 0): Boolean = { - require(bytes >= 0 && bytes <= Int.MaxValue - pBitStrm.currentByte) - - val new_currentByte: Int = pBitStrm.currentByte + bytes + val new_currentByte: Long = pBitStrm.currentByte.toLong + bytes new_currentByte < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && new_currentByte <= pBitStrm.buf.length) } } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 689a6e7be..1d3504ed6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -274,7 +274,7 @@ or 000bbbbb @opaque @inlineOnce def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Unit = { - require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bytes(pBitStrm, 1)) @ghost val oldpBitStrm = snapshot(pBitStrm) val cb = pBitStrm.currentBit.toByte val ncb = (8 - cb).toByte @@ -334,11 +334,11 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni }.ensuring { _ => val w1 = old(pBitStrm) val w2 = pBitStrm - w2.bitIndex() == w1.bitIndex() + 8 && isValidPair(w1, w2) && { + w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { val (r1, r2) = reader(w1, w2) val (r2Got, vGot) = BitStream_ReadBytePure(r1) - vGot.get == value && r2Got == r2 - } && BitStream.invariant(pBitStrm) + ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 + } &&& BitStream.invariant(pBitStrm) } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { From 1ef5252c65fa9d40b14f1cbc9fc69852f1f8b840 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 27 Oct 2023 11:49:01 +0200 Subject: [PATCH 045/174] typo --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 1d3504ed6..8452794c3 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -997,7 +997,7 @@ Example: -4 in Int: 0b1111_..._1111_1100 --> compacted to 0b1111_1100 -The ASN.1 header holds the detail on how to interprete this number +The ASN.1 header holds the detail on how to interpret this number **/ def RemoveLeadingFFBytesIfNegative(v: Int): Int = { if v >= 0 then From 053461c6271b099887ffe0a3a2cf1b398283f652 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 27 Oct 2023 15:58:38 +0200 Subject: [PATCH 046/174] added constrains for the bitstream --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 2 ++ 1 file changed, 2 insertions(+) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 8452794c3..f637b357e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -1156,6 +1156,8 @@ def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) + require(pBitStrm.buf.length > lengthVal) + require(pBitStrm.currentByte < pBitStrm.buf.length - lengthVal) // 8.5.7.2 Base val expFactor: Int = header.unsignedToInt match From a5f56f08075860154900b79fe3f9e5a4c900e75f Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 27 Oct 2023 14:25:28 +0200 Subject: [PATCH 047/174] validate BitStream_AppendByte0 --- asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index f637b357e..4d1babe67 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -342,7 +342,7 @@ def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Uni } def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { - require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bytes(pBitStrm, 1)) val cb: UByte = pBitStrm.currentBit.toByte val ncb: UByte = (8-cb).toByte @@ -356,11 +356,14 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { if pBitStrm.currentByte >= pBitStrm.buf.length then return false mask = ~mask + ghostExpr { + pBitStrm.ensureInvariant() + } pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v <<<< ncb)).toByte true -} +}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { require(0 <= arr_len && arr_len <= arr.length) From 26c306c28608b99f83eaa917da9bb3b22c1be316 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 27 Oct 2023 14:25:58 +0200 Subject: [PATCH 048/174] simplify BitStream_AppendByteArray --- .../scala/asn1scala/asn1jvm_encoding.scala | 49 +++---------------- 1 file changed, 8 insertions(+), 41 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 4d1babe67..f720ef1a9 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -367,53 +367,20 @@ def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { require(0 <= arr_len && arr_len <= arr.length) - require(pBitStrm.currentByte < pBitStrm.buf.length - arr_len) - //static byte masks[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; - //static byte masksb[] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF }; + require(BitStream.validate_offset_bytes(pBitStrm, arr_len)) - val cb: UByte = pBitStrm.currentBit.toByte - val ncb: UByte = (8 - cb).toByte - - val mask: UByte = (~masksb(ncb)).toByte - val nmask: UByte = (~mask).toByte - - //if (pBitStrm->currentByte + (int)arr_len + (cb > 0 ? 1 : 0) >= pBitStrm->count) - if (pBitStrm.currentByte.toLong+arr_len)*8 + pBitStrm.currentBit > pBitStrm.buf.length.toLong*8 then + if !(pBitStrm.currentByte.toLong + arr_len < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && pBitStrm.currentByte.toLong + arr_len <= pBitStrm.buf.length)) then return false - if arr_len > 0 then - val v: UByte = arr(0) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte //make zero right bits (i.e. the ones that will get the new value) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte //shift right and then populate current byte - pBitStrm.currentByte += 1 - - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte - - var i: Int = 1 - (while i < arr_len-1 do - decreases(arr_len-1-i) - val v: UByte = arr(i) - val v1: UByte = ((v & 0xFF) >>> cb).toByte - val v2: UByte = ((v & 0xFF) << ncb).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | v1).toByte //shift right and then populate current byte - pBitStrm.currentByte += 1 - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | v2).toByte + var i: Int = 0 + (while i < arr_len do + decreases(arr_len - i) + BitStream_AppendByte0(pBitStrm, arr(i)) i += 1 - ).invariant(1 <= i &&& i <= arr_len-1 &&& pBitStrm.currentByte < pBitStrm.buf.length) - - if arr_len - 1 > 0 then - val v: UByte = arr(arr_len - 1) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask ).toByte //make zero right bits (i.e. the ones that will get the new value) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) >>> cb)).toByte //shift right and then populate current byte - pBitStrm.currentByte += 1 - - if cb > 0 then - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | ((v & 0xFF) << ncb)).toByte + ).invariant(0 <= i &&& i <= arr_len &&& BitStream.validate_offset_bytes(pBitStrm, arr_len-i)) true -} +}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { From 466d094c90272c8ef1fbd9b819208f1f8885a99e Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 27 Oct 2023 14:27:10 +0200 Subject: [PATCH 049/174] verified BitStream_ReadByte, BitStream_ReadBytePure --- .../src/main/scala/asn1scala/asn1jvm_encoding.scala | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index f720ef1a9..0bd4b027c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -383,17 +383,18 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I }.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { + require(BitStream.validate_offset_bytes(pBitStrm, 1)) val cb: UByte = pBitStrm.currentBit.toByte val ncb: UByte = (8 - cb).toByte - var v: UByte = (pBitStrm.buf(pBitStrm.currentByte) << cb).toByte + var v: UByte = (pBitStrm.buf(pBitStrm.currentByte) <<<< cb) pBitStrm.currentByte += 1 if cb > 0 then - v = (v | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> ncb).toByte // TODO: check if & 0xFF is needed + v = (v | (pBitStrm.buf(pBitStrm.currentByte) >>>> ncb)).toByte - if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then + if BitStream.invariant(pBitStrm) then Some(v) else None() @@ -401,7 +402,7 @@ def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { @ghost @pure def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { - require(pBitStrm.bitIndex() + 8 <= pBitStrm.buf.length.toLong * 8) + require(BitStream.validate_offset_bytes(pBitStrm, 1)) val cpy = snapshot(pBitStrm) (cpy, BitStream_ReadByte(cpy)) } From fa74429ba2a5e9344ea24a8e2ea69e3e21617bee Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 27 Oct 2023 16:48:37 +0200 Subject: [PATCH 050/174] WIP verifying BitStream_ReadByteArray, BitStream_ReadPartialByte --- .../scala/asn1scala/asn1jvm_encoding.scala | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 0bd4b027c..eb1b4e81b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -408,21 +408,24 @@ def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { } def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): OptionMut[Array[UByte]] = { + require(0 < arr_len && arr_len <= pBitStrm.buf.length) + require(BitStream.validate_offset_bytes(pBitStrm, arr_len)) val arr: Array[UByte] = Array.fill(arr_len)(0) - val cb: UByte = pBitStrm.currentBit.toByte - val ncb: UByte = (8 - cb).toByte + val cb = pBitStrm.currentBit + val ncb = 8 - cb - if (pBitStrm.currentByte+arr_len).toLong*8 + cb.toInt > pBitStrm.buf.length.toLong*8 then + if !(pBitStrm.currentByte.toLong + arr_len < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && pBitStrm.currentByte.toLong + arr_len <= pBitStrm.buf.length)) then return NoneMut() var i: Int = 0 - while i < arr_len do + (while i < arr_len do decreases(arr_len - i) - arr(i) = (pBitStrm.buf(pBitStrm.currentByte) << cb).toByte - pBitStrm.currentByte += 1 - arr(i) = (arr(i) | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> ncb).toByte + BitStream_ReadByte(pBitStrm) match + case Some(v) => arr(i) = v + case None() => return NoneMut() i += 1 + ).invariant(0 <= i &&& i <= arr_len &&& i <= arr.length &&& BitStream.validate_offset_bytes(pBitStrm, arr_len-i) &&& BitStream.invariant(pBitStrm)) SomeMut(arr) } @@ -490,28 +493,38 @@ def BitStream_AppendPartialByte(pBitStrm: BitStream, vVal: UByte, nbits: UByte, /* nbits 1..7*/ def BitStream_ReadPartialByte(pBitStrm: BitStream, nbits: UByte): Option[UByte] = { + require(0 <= nbits && nbits < 8) + require(BitStream.validate_offset_bits(pBitStrm, nbits)) var v: UByte = 0 val cb: UByte = pBitStrm.currentBit.toByte val totalBits: UByte = (cb + nbits).toByte if (totalBits <= 8) { - v = ((pBitStrm.buf(pBitStrm.currentByte) >>> (8 - totalBits)) & masksb(nbits)).toByte - pBitStrm.currentBit += nbits.toInt - if pBitStrm.currentBit == 8 then - pBitStrm.currentBit = 0 + + ghostExpr { + BitStream.invariant(pBitStrm) + } + v = ((pBitStrm.buf(pBitStrm.currentByte) >>>> (8 - totalBits)) & masksb(nbits)).toByte + ghostExpr { + BitStream.validate_offset_bits(pBitStrm, nbits) + } + if pBitStrm.currentBit + nbits >= 8 then + pBitStrm.currentBit = (pBitStrm.currentBit + nbits) % 8 pBitStrm.currentByte += 1 + else + pBitStrm.currentBit += nbits.toInt } else { var totalBitsForNextByte: UByte = (totalBits - 8).toByte - v = (pBitStrm.buf(pBitStrm.currentByte) << totalBitsForNextByte).toByte + v = (pBitStrm.buf(pBitStrm.currentByte) <<<< totalBitsForNextByte) pBitStrm.currentByte += 1 - v = (v | (pBitStrm.buf(pBitStrm.currentByte) & 0xFF) >>> (8 - totalBitsForNextByte)).toByte + v = (v | pBitStrm.buf(pBitStrm.currentByte) >>>> (8 - totalBitsForNextByte)).toByte v = (v & masksb(nbits)).toByte pBitStrm.currentBit = totalBitsForNextByte.toInt } - if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then + if BitStream.invariant(pBitStrm) then Some(v) else None() From fe0ff4f19cd0276842861acf6ffc9fc8be447ca2 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 27 Oct 2023 18:38:37 +0200 Subject: [PATCH 051/174] WIP - tranlated first part --- .../src/main/scala/asn1scala/asn1jvm.scala | 88 +----- .../scala/asn1scala/asn1jvm_Bitstream.scala | 276 ++++++++++++++++++ .../scala/asn1scala/asn1jvm_encoding.scala | 202 ++----------- .../asn1scala/asn1jvm_encoding_acn.scala | 8 +- .../asn1scala/asn1jvm_encoding_uper.scala | 4 +- 5 files changed, 307 insertions(+), 271 deletions(-) create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index cbb8e871e..c6ed3d731 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -1,6 +1,6 @@ package asn1scala -import stainless.lang.{None => None, Option => Option, _} +import stainless.lang.{None => None, Option => Option, ghost => ghostExpr, _} import stainless.annotation._ import StaticChecks.* @@ -122,92 +122,6 @@ def asn1Real_Initialize(): asn1Real = { 0.0 } -object BitStream { - @pure @inline - def invariant(pBitStrm: BitStream): Boolean = { - BitStream.invariant(pBitStrm.currentByte, pBitStrm.currentBit, pBitStrm.buf.length) - } - - @pure @inline - def invariant(currentByte: Int, currentBit: Int, buf_length: Int): Boolean = { - 0 <= currentBit && currentBit <= 7 &&& - 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) - } - - @ghost - def validate_offset_bit(pBitStrm: BitStream): Boolean = { -// var new_currentBit: Int = pBitStrm.currentBit + 1 -// var new_currentByte: Int = pBitStrm.currentByte -// -// if new_currentBit > 7 then -// new_currentBit = new_currentBit % 8 -// new_currentByte += 1 -// -// 0 <= new_currentBit -// && new_currentBit <= 7 -// && 0 <= new_currentByte -// && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && pBitStrm.currentByte <= pBitStrm.buf.length)) - pBitStrm.currentByte < pBitStrm.buf.length - } - - @ghost - def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { - require(0 <= bits) - val nBits = bits % 8 - val nBytes = bits / 8 - - var new_currentByte: Long = pBitStrm.currentByte.toLong + nBytes - var new_currentBit: Long = pBitStrm.currentBit.toLong + nBits - - if new_currentBit > 7 then - new_currentBit = new_currentBit % 8 - new_currentByte += 1 - - 0 <= new_currentBit - && new_currentBit <= 7 - && 0 <= new_currentByte - && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) - } - - @ghost - def validate_offset_bytes(pBitStrm: BitStream, bytes: Int = 0): Boolean = { - val new_currentByte: Long = pBitStrm.currentByte.toLong + bytes - new_currentByte < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && new_currentByte <= pBitStrm.buf.length) - } -} - - -case class BitStream( - var buf: Array[Byte], - var currentByte: Int, - var currentBit: Int, - ) { // all BisStream instances satisfy the following: - require(BitStream.invariant(currentByte, currentBit, buf.length)) - - def bitIndex(): Long = { - currentByte.toLong * 8 + currentBit.toLong - }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) - - def increaseBitIndex(): Unit = { - require(currentByte < buf.length) - if currentBit < 7 then - currentBit += 1 - else - currentBit = 0 - currentByte += 1 - }.ensuring {_ => - val oldBitStrm = old(this) - oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& - BitStream.invariant(this) - } - - @inlineOnce @opaque @ghost - def ensureInvariant(): Unit = { - }.ensuring(_ => - BitStream.invariant(currentByte, currentBit, buf.length) - ) -} // BitStream class - case class ByteStream ( var buf: Array[Byte], // UByte var currentByte: Int, diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala new file mode 100644 index 000000000..fde42cb3a --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -0,0 +1,276 @@ +package asn1scala + +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +object BitStream { + @pure @inline + def invariant(pBitStrm: BitStream): Boolean = { + BitStream.invariant(pBitStrm.currentByte, pBitStrm.currentBit, pBitStrm.buf.length) + } + + @pure @inline + def invariant(currentByte: Int, currentBit: Int, buf_length: Int): Boolean = { + 0 <= currentBit && currentBit <= 7 &&& + 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) + } + + @ghost + def validate_offset_bit(pBitStrm: BitStream): Boolean = { + // var new_currentBit: Int = pBitStrm.currentBit + 1 + // var new_currentByte: Int = pBitStrm.currentByte + // + // if new_currentBit > 7 then + // new_currentBit = new_currentBit % 8 + // new_currentByte += 1 + // + // 0 <= new_currentBit + // && new_currentBit <= 7 + // && 0 <= new_currentByte + // && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && pBitStrm.currentByte <= pBitStrm.buf.length)) + pBitStrm.currentByte < pBitStrm.buf.length + } + + @ghost + def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { + require(0 <= bits) + val nBits = bits % 8 + val nBytes = bits / 8 + + var new_currentByte: Long = pBitStrm.currentByte.toLong + nBytes + var new_currentBit: Long = pBitStrm.currentBit.toLong + nBits + + if new_currentBit > 7 then + new_currentBit = new_currentBit % 8 + new_currentByte += 1 + + 0 <= new_currentBit + && new_currentBit <= 7 + && 0 <= new_currentByte + && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) + } + + @ghost + def validate_offset_bytes(pBitStrm: BitStream, bytes: Int = 0): Boolean = { + val new_currentByte: Long = pBitStrm.currentByte.toLong + bytes + new_currentByte < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && new_currentByte <= pBitStrm.buf.length) + } +} + +case class BitStream( + var buf: Array[Byte], + var currentByte: Int, // marks the currentByte that gets accessed + var currentBit: Int, // marks the next bit that gets accessed + ) { // all BisStream instances satisfy the following: + require(BitStream.invariant(currentByte, currentBit, buf.length)) + + private val BitAccessMasks: Array[UByte] = Array( + -0x80, // -128 / 1000 0000 / x80 + 0x40, // 64 / 0100 0000 / x40 + 0x20, // 32 / 0010 0000 / x20 + 0x10, // 16 / 0001 0000 / x10 + 0x08, // 8 / 0000 1000 / x08 + 0x04, // 4 / 0000 0100 / x04 + 0x02, // 2 / 0000 0010 / x02 + 0x01, // 1 / 0000 0001 / x01 + ) + + def bitIndex(): Long = { + currentByte.toLong * 8 + currentBit.toLong + }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) + + def increaseBitIndex(): Unit = { + require(currentByte < buf.length) + if currentBit < 7 then + currentBit += 1 + else + currentBit = 0 + currentByte += 1 + }.ensuring {_ => + val oldBitStrm = old(this) + oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& + BitStream.invariant(this) + } + + @inlineOnce @opaque @ghost + def ensureInvariant(): Unit = { + }.ensuring(_ => + BitStream.invariant(currentByte, currentBit, buf.length) + ) + + /** + * Set new internal buffer + * @param buf Byte array that should be attached to this BitStream + */ + + @extern + def attachBuffer(buf: Array[UByte]): Unit = { + this.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... + currentByte = 0 + currentBit = 0 + }.ensuring(_ => this.buf == buf && currentByte == 0 && currentBit == 0) + + /** + * + * Return count of bytes that got already fully or partially written + * Example: + * Currentbyte = 4, currentBit = 2 --> 5 + * Currentbyte = 14, currentBit = 0 --> 14 + * + * @return the number of used bytes so far + * + */ + def getLength(): Int = { + var ret: Int = currentByte + if currentBit > 0 then + ret += 1 + ret + } + + @ghost + @pure + private def readBitPure(): (BitStream, Option[Boolean]) = { + require(BitStream.validate_offset_bit(this)) + val cpy = snapshot(this) + (cpy, cpy.readBit()) + } + + @opaque + @inlineOnce + def appendBitOne(): Unit = { + require(BitStream.validate_offset_bit(this)) + @ghost val oldpBitStrm = snapshot(this) + + val newB = (buf(currentByte) | BitAccessMasks(currentBit)).toByte + buf(currentByte) = newB + + ghostExpr { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte, newB) + } + + increaseBitIndex() + + }.ensuring { _ => + val w1 = old(this) + val w2 = this + w2.bitIndex() == w1.bitIndex() + 1 + &&& isValidPair(w1, w2) + &&& { + val (r1, r2) = reader(w1, w2) + val (r2Got, bitGot) = readBitPure() + bitGot.get == true && r2Got == r2 + } + &&& BitStream.invariant(this) + } + + /** + * Append zero bit. + * + * Example + * cur bit = 3 + * x x x | + * |_|_|_|_|_|_|_|_| + * 0 1 2 3 4 5 6 7 + * + * x x x y ? ? ? ? + * and 1 1 1 0 1 1 1 1 + * ---------------- + * --> x x x 0 ? ? ? ? + * */ + + // TODO replace with addBit(false)? + def appendBitZero(): Unit = { + require(BitStream.validate_offset_bits(this, 1)) + val negMask = ~BitAccessMasks(currentBit) + buf(currentByte) = (buf(currentByte) & negMask).toByte + + increaseBitIndex() + }.ensuring(_ => BitStream.invariant(this)) + + + // TODO what are you? it does not append even though it has append in the name + // TODO replace with loop that calls appendBitZero + def appendNBitZero(nBitsVal: Int): Unit = { + require(0 <= nBitsVal) + require(BitStream.validate_offset_bits(this, nBitsVal)) + + val nBits = nBitsVal % 8 + val nBytes = nBitsVal / 8 + + var new_currentBit: Int = currentBit + nBits + var new_currentByte: Int = currentByte + nBytes + + if new_currentBit > 7 then + new_currentBit = new_currentBit % 8 + new_currentByte += 1 + + currentBit = new_currentBit + currentByte = new_currentByte + + }.ensuring(_ => BitStream.invariant(this)) + + + def appendNBitOne(nBitsVal: Int): Unit = { + require(0 <= nBitsVal) + require(BitStream.validate_offset_bits(this, nBitsVal)) + var nBits = nBitsVal + + (while nBits > 0 do + decreases(nBits) + appendBitOne() + nBits -= 1 + ).invariant(nBits >= 0 &&& BitStream.validate_offset_bits(this, nBits)) + } + + def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { + require(0 <= nBits && nBits / 8 < srcBuffer.length) + require(BitStream.validate_offset_bits(this, nBits)) + var lastByte: UByte = 0 + + val bytesToEncode: Int = nBits / 8 + val remainingBits: UByte = (nBits % 8).toByte + + BitStream_EncodeOctetString_no_length(this, srcBuffer, bytesToEncode) + + if remainingBits > 0 then + lastByte = ((srcBuffer(bytesToEncode) & 0xFF) >>> (8 - remainingBits)).toByte + BitStream_AppendPartialByte(this, lastByte, remainingBits, false) + } + + def appendBit(v: Boolean): Unit = { + require(BitStream.validate_offset_bits(this, 1)) + if v then + buf(currentByte) = (buf(currentByte) | BitAccessMasks(currentBit)).toByte + else + val negMask = ~BitAccessMasks(currentBit) + buf(currentByte) = (buf(currentByte) & negMask).toByte + + increaseBitIndex() + }.ensuring(_ => BitStream.invariant(this)) + + // TODO check if needs Marios implementation + + def readBit(): Option[Boolean] = { + require(BitStream.validate_offset_bit(this)) + val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 + + increaseBitIndex() + + if currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8 then + Some(ret) + else + None() + }.ensuring(_ => BitStream.invariant(this)) + + def peekBit(): Boolean = { + require(currentByte < buf.length) + ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 + } + + +} // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index eb1b4e81b..0d45b9002 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -8,17 +8,6 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* -val masks: Array[UByte] = Array( - -0x80, // -128 / 1000 0000 / x80 - 0x40, // 64 / 0100 0000 / x40 - 0x20, // 32 / 0010 0000 / x20 - 0x10, // 16 / 0001 0000 / x10 - 0x08, // 8 / 0000 1000 / x08 - 0x04, // 4 / 0000 0100 / x04 - 0x02, // 2 / 0000 0010 / x02 - 0x01, // 1 / 0000 0001 / x01 -) - val masksb: Array[UByte] = Array( 0x00, // 0 / 0000 0000 / x00 0x01, // 1 / 0000 0001 / x01 @@ -73,21 +62,6 @@ def BitStream_Init(count: Int): BitStream = { BitStream(Array.fill(count)(0), 0, 0) } -@extern -def BitStream_AttachBuffer(pBitStrm: BitStream, buf: Array[UByte]): Unit = { - pBitStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... - pBitStrm.currentByte = 0 - pBitStrm.currentBit = 0 -}.ensuring(_ => pBitStrm.buf == buf && pBitStrm.currentByte == 0 && pBitStrm.currentBit == 0) - - -def BitStream_GetLength(pBitStrm: BitStream): Int = { - var ret: Int = pBitStrm.currentByte - if pBitStrm.currentBit > 0 then - ret += 1 - ret -} - /** Append bit one. @@ -103,6 +77,8 @@ or 00010000 xxx1???? **/ + +// TODO should be part of BitStream def isPrefix(b1: BitStream, b2: BitStream): Boolean = { b1.buf.length <= b2.buf.length && b1.bitIndex() <= b2.bitIndex() && @@ -118,138 +94,7 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) (r1, r2) } - -@ghost @pure -def BitStream_ReadBitPure(pBitStrm: BitStream): (BitStream, Option[Boolean]) = { - require(BitStream.validate_offset_bit(pBitStrm)) - val cpy = snapshot(pBitStrm) - (cpy , BitStream_ReadBit(cpy)) -} - -@opaque @inlineOnce -def BitStream_AppendBitOne(pBitStrm: BitStream): Unit = { - require(BitStream.validate_offset_bit(pBitStrm)) - @ghost val oldpBitStrm = snapshot(pBitStrm) - - val newB = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte - pBitStrm.buf(pBitStrm.currentByte) = newB - - ghostExpr { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, newB) - } - - pBitStrm.increaseBitIndex() - -}.ensuring { _ => - val w1 = old(pBitStrm) - val w2 = pBitStrm - w2.bitIndex() == w1.bitIndex() + 1 - &&& isValidPair(w1, w2) - &&& { - val (r1, r2) = reader(w1, w2) - val (r2Got, bitGot) = BitStream_ReadBitPure(r1) - bitGot.get == true && r2Got == r2 - } - &&& BitStream.invariant(pBitStrm) -} - -/** - Append bit zero. - - Example - cur bit = 3 - x x x | - |_|_|_|_|_|_|_|_| - 0 1 2 3 4 5 6 7 - - xxxy???? - and 11101111 - -------- - xxx0???? -**/ -def BitStream_AppendBitZero(pBitStrm: BitStream): Unit = { - require(BitStream.validate_offset_bits(pBitStrm, 1)) - val nmask = ~masks(pBitStrm.currentBit) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - - pBitStrm.increaseBitIndex() -}.ensuring(_ => BitStream.invariant(pBitStrm)) - -def BitStream_AppendNBitZero(pBitStrm: BitStream, nbits: Int): Unit = { - require(0 <= nbits) - require(BitStream.validate_offset_bits(pBitStrm, nbits)) - - val nBits = nbits % 8 - val nBytes = nbits / 8 - - var new_currentBit: Int = pBitStrm.currentBit + nBits - var new_currentByte: Int = pBitStrm.currentByte + nBytes - - if new_currentBit > 7 then - new_currentBit = new_currentBit % 8 - new_currentByte += 1 - - pBitStrm.currentBit = new_currentBit - pBitStrm.currentByte = new_currentByte - -}.ensuring(_ => BitStream.invariant(pBitStrm)) - -def BitStream_AppendNBitOne(pBitStrm: BitStream, nbitsVal: Int): Unit = { - require(0 <= nbitsVal) - require(BitStream.validate_offset_bits(pBitStrm, nbitsVal)) - var nbits = nbitsVal - - (while nbits > 0 do - decreases(nbits) - BitStream_AppendBitOne(pBitStrm) - nbits -= 1 - ).invariant(nbits >= 0 &&& BitStream.validate_offset_bits(pBitStrm, nbits)) - () -} - -def BitStream_AppendBits(pBitStrm: BitStream, srcBuffer: Array[UByte], nbits: Int): Unit = { - require(0 <= nbits && nbits/8 < srcBuffer.length) - require(BitStream.validate_offset_bits(pBitStrm, nbits)) - var lastByte: UByte = 0 - - val bytesToEncode: Int = nbits / 8 - val remainingBits: UByte = (nbits % 8).toByte - - BitStream_EncodeOctetString_no_length(pBitStrm, srcBuffer, bytesToEncode) - - if remainingBits > 0 then - lastByte = ((srcBuffer(bytesToEncode) & 0xFF) >>> (8 - remainingBits)).toByte - BitStream_AppendPartialByte(pBitStrm, lastByte, remainingBits, false) -} - -def BitStream_AppendBit(pBitStrm: BitStream, v: Boolean): Unit = { - require(BitStream.validate_offset_bits(pBitStrm, 1)) - if v then - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | masks(pBitStrm.currentBit)).toByte - else - val nmask = ~masks(pBitStrm.currentBit) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & nmask).toByte - - pBitStrm.increaseBitIndex() -}.ensuring(_ => BitStream.invariant(pBitStrm)) - -// TODO check if needs Marios implementation -def BitStream_ReadBit(pBitStrm: BitStream): Option[Boolean] = { - require(BitStream.validate_offset_bit(pBitStrm)) - val ret = (pBitStrm.buf(pBitStrm.currentByte) & masks(pBitStrm.currentBit)) != 0 - - pBitStrm.increaseBitIndex() - - if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8 then - Some(ret) - else - None() -}.ensuring(_ => BitStream.invariant(pBitStrm)) - -def BitStream_PeekBit(pBitStrm: BitStream): Boolean = { - require(pBitStrm.currentByte < pBitStrm.buf.length) - ((pBitStrm.buf(pBitStrm.currentByte) & 0xFF) & (masks(pBitStrm.currentBit) & 0xFF)) > 0 -} +// END TODO should be part of BitStream /** Append byte. @@ -615,7 +460,7 @@ def BitStream_EncodeNonNegativeInteger(pBitStrm: BitStream, v: ULong): Unit = { BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, hi, false) val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? - BitStream_AppendNBitZero(pBitStrm, 32 - nBits) + pBitStrm.appendNBitZero(32 - nBits) BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, lo, false) //else // BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v.toInt, false) @@ -658,7 +503,7 @@ def BitStream_EncodeNonNegativeIntegerNeg(pBitStrm: BitStream, v: ULong, negate: if negate then lo = ~lo val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) - BitStream_AppendNBitZero(pBitStrm, 32 - nBits) + pBitStrm.appendNBitZero( 32 - nBits) BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, lo, false) //else // BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v, negate) @@ -719,7 +564,7 @@ def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Lon val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) - BitStream_AppendNBitZero(pBitStrm, nRangeBits - nBits); + pBitStrm.appendNBitZero(nRangeBits - nBits); BitStream_EncodeNonNegativeInteger(pBitStrm, (v - min)) } @@ -734,7 +579,7 @@ def BitStream_EncodeConstraintPosWholeNumber(pBitStrm: BitStream, v: ULong, min: return val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - BitStream_AppendNBitZero(pBitStrm, nRangeBits - nBits) + pBitStrm.appendNBitZero(nRangeBits - nBits) BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) } @@ -824,7 +669,7 @@ def BitStream_EncodeSemiConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: BitStream_EncodeConstraintWholeNumber(pBitStrm, nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ - BitStream_AppendNBitZero(pBitStrm, nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) + pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) /*Encode number */ BitStream_EncodeNonNegativeInteger(pBitStrm, (v - min)) } @@ -837,7 +682,7 @@ def BitStream_EncodeSemiConstraintPosWholeNumber(pBitStrm: BitStream, v: ULong, BitStream_EncodeConstraintWholeNumber(pBitStrm, nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ - BitStream_AppendNBitZero(pBitStrm, nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) + pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) /*Encode number */ BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) } @@ -897,10 +742,10 @@ def BitStream_EncodeUnConstraintWholeNumber(pBitStrm: BitStream, v: Long): Unit /*8 bits, first bit is always 0*/ if v >= 0 then - BitStream_AppendNBitZero(pBitStrm, nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) + pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) BitStream_EncodeNonNegativeInteger(pBitStrm, v) else - BitStream_AppendNBitOne(pBitStrm, nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) + pBitStrm.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) BitStream_EncodeNonNegativeIntegerNeg(pBitStrm, (-v - 1), true) } @@ -913,7 +758,7 @@ def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = case None() => return None() case Some(l) => nBytes = l - val valIsNegative: Boolean = BitStream_PeekBit(pBitStrm) + val valIsNegative: Boolean = pBitStrm.peekBit() var v: Long = if valIsNegative then Long.MaxValue else 0 @@ -1078,13 +923,13 @@ def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { /* encode exponent */ if exponent >= 0 then // fill with zeros to have a whole byte - BitStream_AppendNBitZero(pBitStrm, nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) + pBitStrm.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) BitStream_EncodeNonNegativeInteger(pBitStrm, exponent) else BitStream_EncodeNonNegativeInteger(pBitStrm, compactExp) /* encode mantissa */ - BitStream_AppendNBitZero(pBitStrm, nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) + pBitStrm.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) BitStream_EncodeNonNegativeInteger(pBitStrm, mantissa) } @@ -1160,7 +1005,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt return None() // decode exponent - val expIsNegative = BitStream_PeekBit(pBitStrm) + val expIsNegative = pBitStrm.peekBit() var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 var i: Int = 0 @@ -1247,10 +1092,10 @@ def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_patter checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do decreases(nMaxReadBits - bitsRead) - BitStream_ReadBit(pBitStrm) match + pBitStrm.readBit() match case None() => return NoneMut() case Some(bitVal) => - BitStream_AppendBit(tmpStrm, bitVal) + tmpStrm.appendBit(bitVal) bitsRead += 1 if bitsRead < nMaxReadBits then @@ -1337,7 +1182,7 @@ def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UB if nRemainingItemsVar1 <= 0x7F then BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1.toLong, 0, 0xFF) else - BitStream_AppendBit(pBitStrm, true) + pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1.toLong, 0, 0x7FFF) @@ -1481,7 +1326,8 @@ def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: In if asn1SizeMin != asn1SizeMax then BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount.toLong, asn1SizeMin, asn1SizeMax) - BitStream_AppendBits(pBitStrm, arr, nCount) + pBitStrm.appendBits(arr, nCount) + else var nRemainingItemsVar1: Long = nCount.toLong var nCurBlockSize1: Long = 0 @@ -1504,7 +1350,7 @@ def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: In BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF) val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0)// STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) - BitStream_AppendBits(pBitStrm, t, nCurBlockSize1.toInt) + pBitStrm.appendBits(t, nCurBlockSize1.toInt) nCurOffset1 += nCurBlockSize1 nRemainingItemsVar1 -= nCurBlockSize1 @@ -1512,13 +1358,13 @@ def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: In if nRemainingItemsVar1 <= 0x7F then BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1, 0, 0xFF) else - BitStream_AppendBit(pBitStrm, true) + pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1, 0, 0x7FFF) val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) - BitStream_AppendBits(pBitStrm, t, nRemainingItemsVar1.toInt) + pBitStrm.appendBits(t, nRemainingItemsVar1.toInt) - return true + true } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index e88e1189b..f53d5ac99 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -45,7 +45,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, intVal: ULong, en /* Get number of bits*/ val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) /* put required zeros*/ - BitStream_AppendNBitZero(pBitStrm, encodedSizeInBits - nBits) + pBitStrm.appendNBitZero(encodedSizeInBits - nBits) /*Encode number */ BitStream_EncodeNonNegativeInteger(pBitStrm, intVal) @@ -253,11 +253,11 @@ def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream): Opt def Acn_Enc_Int_TwosComplement_ConstSize(pBitStrm: BitStream, intVal: Long, encodedSizeInBits: Int): Unit = { if intVal >= 0 then - BitStream_AppendNBitZero(pBitStrm, encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) + pBitStrm.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) BitStream_EncodeNonNegativeInteger(pBitStrm, intVal) else - BitStream_AppendNBitOne(pBitStrm, encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) + pBitStrm.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) BitStream_EncodeNonNegativeIntegerNeg(pBitStrm, -intVal - 1, true) CHECK_BIT_STREAM(pBitStrm) @@ -301,7 +301,7 @@ def Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm: BitStream, i def Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm: BitStream, encodedSizeInBits: Int): Option[Long] = { - val valIsNegative: Boolean = BitStream_PeekBit(pBitStrm) + val valIsNegative: Boolean = pBitStrm.peekBit() val nBytes: Int = encodedSizeInBits / 8 val rstBits: Int = encodedSizeInBits % 8 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index 8930be41b..8ef2d5b97 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -44,7 +44,7 @@ def ObjectIdentifier_uper_encode(pBitStrm: BitStream, pVal: Asn1ObjectIdentifier if totalSize <= 0x7F then BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0xFF) else - BitStream_AppendBit(pBitStrm, true) + pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0x7FFF) i = 0 @@ -70,7 +70,7 @@ def RelativeOID_uper_encode (pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): U if totalSize <= 0x7F then BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0xFF) else - BitStream_AppendBit(pBitStrm, true) + pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0x7FFF) i = 0 From 941cab2840ad31ee06ee788d30ca9bf31f9ccb59 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Sat, 28 Oct 2023 00:04:54 +0200 Subject: [PATCH 052/174] appendbyte & appendbyte0 --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 112 ++++++++++++++++ .../scala/asn1scala/asn1jvm_encoding.scala | 121 +----------------- .../asn1scala/asn1jvm_encoding_acn.scala | 50 ++++---- .../asn1scala/asn1jvm_encoding_uper.scala | 4 +- 4 files changed, 144 insertions(+), 143 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index fde42cb3a..a3927133a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -272,5 +272,117 @@ case class BitStream( ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 } + /** + * Append byte. + * + * Example + * cur bit = 3 + * | + * x x x b b b b b b b b + * |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| + * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 + * + * first byte + * xxx????? + * and 11100000 (mask) + * -------------- + * xxx00000 + * or 000bbbbb + * -------------- + * xxxbbbbb + * + * */ + + @opaque + @inlineOnce + def appendByte(value: Byte, negate: Boolean): Unit = { + require(BitStream.validate_offset_bytes(this, 1)) + @ghost val oldpBitStrm = snapshot(this) + val cb = currentBit.toByte + val ncb = (8 - cb).toByte + var mask = (~masksb(ncb)).toByte + + var v = value + if negate then + v = (~v).toByte + + buf(currentByte) = (buf(currentByte) & mask).toByte // set bits right of currentbit to zero (where our value will be inserted) + buf(currentByte) = (buf(currentByte) | (v >>>> cb)).toByte // set value into bits right of currentbit, but keep bits to the left + currentByte += 1 + + ghostExpr { + check( + (oldpBitStrm.currentByte < oldpBitStrm.buf.length) ==> + bytePrefix( + oldpBitStrm.buf(oldpBitStrm.currentByte), + buf(oldpBitStrm.currentByte), + 0, oldpBitStrm.currentBit)) + } + @ghost val old2pBitStrm = snapshot(this) + + if cb > 0 then + mask = (~mask).toByte + buf(currentByte) = (buf(currentByte) & mask).toByte // set bits to the left of currentbit in next byte to zero (where the rest of our value will be inserted) + buf(currentByte) = (buf(currentByte) | (v <<<< ncb)).toByte // set value into the bits left of currentbit, but keep the bits to the right + + ghostExpr { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte - 1, buf(currentByte - 1)) + assert(arrayPrefix(oldpBitStrm.buf, old2pBitStrm.buf, 0, currentByte - 1)) + + if (cb > 0) { + arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte, buf(currentByte)) + arrayUpdatedAtPrefixLemma(old2pBitStrm.buf, currentByte, buf(currentByte)) + arrayPrefixTransitive( + oldpBitStrm.buf, + old2pBitStrm.buf, + buf,0, currentByte - 1, currentByte + ) + check(arrayPrefix( + oldpBitStrm.buf, + buf, + 0, + oldpBitStrm.currentByte + )) + } else { + check(arrayPrefix( + oldpBitStrm.buf, + buf,0, + oldpBitStrm.currentByte + )) + } + } + }.ensuring { _ => + val w1 = old(this) + val w2 = this + w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { + val (r1, r2) = reader(w1, w2) + val (r2Got, vGot) = BitStream_ReadBytePure(r1) + ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 + } &&& BitStream.invariant(this) + } + + def appendByte0(v: UByte): Boolean = { + require(BitStream.validate_offset_bytes(this, 1)) + val cb: UByte = currentBit.toByte + val ncb: UByte = (8 - cb).toByte + + var mask = ~masksb(ncb) + + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v >>>> cb)).toByte + currentByte += 1 + + if cb > 0 then + if currentByte >= buf.length then + return false + mask = ~mask + ghostExpr { + ensureInvariant() + } + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v <<<< ncb)).toByte + + true + }.ensuring(_ => BitStream.invariant(this)) } // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index 0d45b9002..a93b80b15 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -8,6 +8,7 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* +// TODO move to Bitstream if only used there val masksb: Array[UByte] = Array( 0x00, // 0 / 0000 0000 / x00 0x01, // 1 / 0000 0001 / x01 @@ -96,119 +97,7 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { } // END TODO should be part of BitStream -/** -Append byte. - -Example -cur bit = 3 - | - x x x b b b b b b b b -|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| - 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 - -first byte - xxx????? -and 11100000 (mask) --------------- - xxx00000 -or 000bbbbb --------------- - xxxbbbbb - -**/ - -@opaque @inlineOnce -def BitStream_AppendByte(pBitStrm: BitStream, value: Byte, negate: Boolean): Unit = { - require(BitStream.validate_offset_bytes(pBitStrm, 1)) - @ghost val oldpBitStrm = snapshot(pBitStrm) - val cb = pBitStrm.currentBit.toByte - val ncb = (8 - cb).toByte - var mask = (~masksb(ncb)).toByte - - var v = value - if negate then - v = (~v).toByte - - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte // set bits right of currentbit to zero (where our value will be inserted) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>>> cb)).toByte // set value into bits right of currentbit, but keep bits to the left - pBitStrm.currentByte += 1 - - ghostExpr { - check( - (oldpBitStrm.currentByte < oldpBitStrm.buf.length) ==> - bytePrefix( - oldpBitStrm.buf(oldpBitStrm.currentByte), - pBitStrm.buf(oldpBitStrm.currentByte), - 0, oldpBitStrm.currentBit)) - } - @ghost val old2pBitStrm = snapshot(pBitStrm) - if cb > 0 then - mask = (~mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte // set bits to the left of currentbit in next byte to zero (where the rest of our value will be inserted) - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v <<<< ncb)).toByte // set value into the bits left of currentbit, but keep the bits to the right - - ghostExpr { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte - 1, pBitStrm.buf(pBitStrm.currentByte - 1)) - assert(arrayPrefix(oldpBitStrm.buf, old2pBitStrm.buf, 0, pBitStrm.currentByte - 1)) - - if (cb > 0) { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, pBitStrm.currentByte, pBitStrm.buf(pBitStrm.currentByte)) - arrayUpdatedAtPrefixLemma(old2pBitStrm.buf, pBitStrm.currentByte, pBitStrm.buf(pBitStrm.currentByte)) - arrayPrefixTransitive( - oldpBitStrm.buf, - old2pBitStrm.buf, - pBitStrm.buf, - 0, pBitStrm.currentByte - 1, pBitStrm.currentByte - ) - check(arrayPrefix( - oldpBitStrm.buf, - pBitStrm.buf, - 0, - oldpBitStrm.currentByte - )) - } else { - check(arrayPrefix( - oldpBitStrm.buf, - pBitStrm.buf, - 0, - oldpBitStrm.currentByte - )) - } - } -}.ensuring { _ => - val w1 = old(pBitStrm) - val w2 = pBitStrm - w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { - val (r1, r2) = reader(w1, w2) - val (r2Got, vGot) = BitStream_ReadBytePure(r1) - ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 - } &&& BitStream.invariant(pBitStrm) -} - -def BitStream_AppendByte0(pBitStrm: BitStream, v: UByte): Boolean = { - require(BitStream.validate_offset_bytes(pBitStrm, 1)) - val cb: UByte = pBitStrm.currentBit.toByte - val ncb: UByte = (8-cb).toByte - - var mask = ~masksb(ncb) - - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>>> cb)).toByte - pBitStrm.currentByte += 1 - - if cb > 0 then - if pBitStrm.currentByte >= pBitStrm.buf.length then - return false - mask = ~mask - ghostExpr { - pBitStrm.ensureInvariant() - } - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v <<<< ncb)).toByte - - true -}.ensuring(_ => BitStream.invariant(pBitStrm)) def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { require(0 <= arr_len && arr_len <= arr.length) @@ -220,7 +109,7 @@ def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: I var i: Int = 0 (while i < arr_len do decreases(arr_len - i) - BitStream_AppendByte0(pBitStrm, arr(i)) + pBitStrm.appendByte0(arr(i)) i += 1 ).invariant(0 <= i &&& i <= arr_len &&& BitStream.validate_offset_bytes(pBitStrm, arr_len-i)) @@ -420,7 +309,7 @@ def BitStream_EncodeNonNegativeInteger32Neg(pBitStrm: BitStream, v: Int, negate: decreases(cc) val t1: UInt = v.toInt & masks2(cc >>> 3) cc -= 8 - BitStream_AppendByte(pBitStrm, (t1 >>> cc).toByte, negate) + pBitStrm.appendByte((t1 >>> cc).toByte, negate) } def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): Option[UInt] = { @@ -1172,7 +1061,7 @@ def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UB var i1: Int = nCurOffset1 while i1 < nCurBlockSize1 + nCurOffset1 && ret do decreases(nCurBlockSize1 + nCurOffset1 - i1) - ret = BitStream_AppendByte0(pBitStrm, arr(i1)) + ret = pBitStrm.appendByte0(arr(i1)) i1 += 1 nCurOffset1 += nCurBlockSize1 @@ -1189,7 +1078,7 @@ def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UB var i1: Int = nCurOffset1 while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do decreases(nCurOffset1 + nRemainingItemsVar1 - i1) - ret = BitStream_AppendByte0(pBitStrm, arr(i1)) + ret = pBitStrm.appendByte0(arr(i1)) i1 += 1 return ret diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index f53d5ac99..073e49411 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -54,7 +54,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, intVal: ULong, en def Acn_Enc_Int_PositiveInteger_ConstSize_8(pBitStrm: BitStream, intVal: ULong): Unit = { - BitStream_AppendByte0(pBitStrm, intVal.toByte) + pBitStrm.appendByte0(intVal.toByte) CHECK_BIT_STREAM(pBitStrm) } @@ -67,7 +67,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm: BitStream, intV var i: Int = 0 while i < size do val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - BitStream_AppendByte0(pBitStrm, ByteToEncode) + pBitStrm.appendByte0(ByteToEncode) mask >>>= 8 i += 1 @@ -96,7 +96,7 @@ def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, i var i: Int = 0 while i < size do val ByteToEncode: Byte = tmp.toByte - BitStream_AppendByte0(pBitStrm, ByteToEncode) + pBitStrm.appendByte0(ByteToEncode) tmp >>>= 8 i += 1 @@ -213,7 +213,7 @@ def Encode_UnsignedInteger(pBitStrm: BitStream, v: ULong, nBytes: Byte): Unit = var i: Int = 0 while i < nBytes do val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - BitStream_AppendByte0(pBitStrm, ByteToEncode) + pBitStrm.appendByte0(ByteToEncode) vv <<= 8 i += 1 } @@ -224,7 +224,7 @@ def Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream, intV val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte /* encode length */ - BitStream_AppendByte0(pBitStrm, nBytes) + pBitStrm.appendByte0(nBytes) /* Encode integer data*/ Encode_UnsignedInteger(pBitStrm, intVal, nBytes) @@ -380,7 +380,7 @@ def Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream, intVa val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte /* encode length */ - BitStream_AppendByte0(pBitStrm, nBytes) + pBitStrm.appendByte0(nBytes) /* Encode integer data*/ Encode_UnsignedInteger(pBitStrm, int2uint(intVal), nBytes) @@ -473,7 +473,7 @@ def Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): { val nNibbles: Int = Acn_Get_Int_Size_BCD(intVal) /* encode length */ - BitStream_AppendByte0(pBitStrm, nNibbles.toByte) + pBitStrm.appendByte0(nNibbles.toByte) /* Encode Number */ Acn_Enc_Int_BCD_ConstSize(pBitStrm, intVal, nNibbles) @@ -539,7 +539,7 @@ def Acn_Enc_UInt_ASCII_ConstSize(pBitStrm: BitStream, intVal: ULong, encodedSize var i = encodedSizeInBytes - 1 while i >= 0 do - BitStream_AppendByte0(pBitStrm, (tmp(i) + '0').toByte) + pBitStrm.appendByte0((tmp(i) + '0').toByte) i -= 1 CHECK_BIT_STREAM(pBitStrm) @@ -551,7 +551,7 @@ def Acn_Enc_SInt_ASCII_ConstSize(pBitStrm: BitStream, intVal: Long, encodedSizeI val absIntVal: ULong = if intVal >= 0 then intVal else -intVal /* encode sign */ - BitStream_AppendByte0(pBitStrm, if intVal >= 0 then '+' else '-') + pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') Acn_Enc_UInt_ASCII_ConstSize(pBitStrm, absIntVal, encodedSizeInBytes-1) } @@ -626,15 +626,15 @@ def Acn_Enc_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: Long) val (digitsArray100, nChars) = getIntegerDigits(absIntVal) /* encode length, plus 1 for sign */ - BitStream_AppendByte0(pBitStrm, (nChars + 1).toByte) + pBitStrm.appendByte0((nChars + 1).toByte) /* encode sign */ - BitStream_AppendByte0(pBitStrm, if intVal >= 0 then '+' else '-') + pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - BitStream_AppendByte0(pBitStrm, digitsArray100(i)) + pBitStrm.appendByte0(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(pBitStrm) @@ -645,11 +645,11 @@ def Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong val (digitsArray100, nChars) = getIntegerDigits(intVal) /* encode length */ - BitStream_AppendByte0(pBitStrm, nChars) + pBitStrm.appendByte0(nChars) /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - BitStream_AppendByte0(pBitStrm, digitsArray100(i)) + pBitStrm.appendByte0(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(pBitStrm) @@ -677,12 +677,12 @@ def Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, intVal: ULong var i: Int = 0 // TODO: size_t? while i < 100 && digitsArray100(i) != 0x0 do - BitStream_AppendByte0(pBitStrm, digitsArray100(i)) + pBitStrm.appendByte0(digitsArray100(i)) i += 1 i = 0 while i < null_characters_size do - BitStream_AppendByte0(pBitStrm, null_characters(i)) + pBitStrm.appendByte0(null_characters(i)) i += 1 CHECK_BIT_STREAM(pBitStrm) @@ -691,7 +691,7 @@ def Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, intVal: ULong def Acn_Enc_SInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { val absValue: ULong = if intVal >= 0 then intVal else -intVal - BitStream_AppendByte0(pBitStrm, if intVal >= 0 then '+' else '-') + pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm, absValue, null_characters, null_characters_size) } @@ -838,7 +838,7 @@ def Acn_Enc_Real_IEEE754_32_big_endian(pBitStrm: BitStream, realValue: Float): U var i: Int = 0 while i < 4 do - BitStream_AppendByte0(pBitStrm, b(i)) + pBitStrm.appendByte0(b(i)) i += 1 } @@ -877,7 +877,7 @@ def Acn_Enc_Real_IEEE754_64_big_endian(pBitStrm: BitStream, realValue: Double): var i: Int = 0 while i < 8 do - BitStream_AppendByte0(pBitStrm, b(i)) + pBitStrm.appendByte0(b(i)) i += 1 } @@ -902,7 +902,7 @@ def Acn_Enc_Real_IEEE754_32_little_endian(pBitStrm: BitStream, realValue: Double var i: Int = 3 while i >= 0 do - BitStream_AppendByte0(pBitStrm, b(i)) + pBitStrm.appendByte0(b(i)) i -= 1 } @@ -940,7 +940,7 @@ def Acn_Enc_Real_IEEE754_64_little_endian(pBitStrm: BitStream, realValue: Double var i: Int = 7 while i >= 0 do - BitStream_AppendByte0(pBitStrm, b(i)) + pBitStrm.appendByte0(b(i)) i -= 1 } @@ -966,14 +966,14 @@ def Acn_Enc_String_Ascii_FixSize(pBitStrm: BitStream, max: Long, strVal: Array[A { var i: Long = 0 while i < max do - BitStream_AppendByte(pBitStrm, strVal(i.toInt), false) + pBitStrm.appendByte(strVal(i.toInt), false) i += 1 } def Acn_Enc_String_Ascii_private(pBitStrm: BitStream, max: Long, strVal: Array[ASCIIChar]): Long = { var i: Long = 0 while (i < max) && (strVal(i.toInt) != '\u0000') do - BitStream_AppendByte(pBitStrm, strVal(i.toInt), false) + pBitStrm.appendByte(strVal(i.toInt), false) i += 1 i @@ -982,7 +982,7 @@ def Acn_Enc_String_Ascii_private(pBitStrm: BitStream, max: Long, strVal: Array[A def Acn_Enc_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) - BitStream_AppendByte(pBitStrm, null_character.toByte, false) + pBitStrm.appendByte(null_character.toByte, false) } def Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = @@ -990,7 +990,7 @@ def Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, nul Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) var i: Int = 0 while i < null_character_size do - BitStream_AppendByte(pBitStrm, null_character(i), false) + pBitStrm.appendByte(null_character(i), false) i += 1 } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index 8ef2d5b97..d96f1ac1b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -50,7 +50,7 @@ def ObjectIdentifier_uper_encode(pBitStrm: BitStream, pVal: Asn1ObjectIdentifier i = 0 while i < totalSize do decreases(totalSize - i) - BitStream_AppendByte0(pBitStrm, tmp(i)); + pBitStrm.appendByte0(tmp(i)) i += 1 } def RelativeOID_uper_encode (pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): Unit = { @@ -76,7 +76,7 @@ def RelativeOID_uper_encode (pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): U i = 0 while i < totalSize do decreases(totalSize - i) - BitStream_AppendByte0(pBitStrm, tmp(i)) + pBitStrm.appendByte0(tmp(i)) i += 1 } From f9b0c60f3310fa9fc15d8e7d9567ed87a50f8a97 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 30 Oct 2023 09:29:58 +0100 Subject: [PATCH 053/174] add asn1jvm_Bitstream to solution --- asn1scc/GenerateRTL.fs | 1 + asn1scc/asn1scc.fsproj | 3 +++ 2 files changed, 4 insertions(+) diff --git a/asn1scc/GenerateRTL.fs b/asn1scc/GenerateRTL.fs index ad1abf724..2a20a54ce 100644 --- a/asn1scc/GenerateRTL.fs +++ b/asn1scc/GenerateRTL.fs @@ -99,6 +99,7 @@ let exportRTL (di:DirInfo) (l:ProgrammingLanguage) (args:CommandLineSettings)= writeTextFile (Path.Combine(rootDir, "build.sbt")) (getResourceAsString "build.sbt") writeResource di "asn1jvm.scala" None + writeResource di "asn1jvm_Bitstream.scala" None //let intSize = sprintf "#define WORD_SIZE %d" (int args.integerSizeInBytes) //let fpSize = sprintf "#define FP_WORD_SIZE %d" (int args.floatingPointSizeInBytes) diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index 8dcfbf2ad..c8fb804a7 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -106,6 +106,9 @@ asn1jvm_unsigned.scala + + asn1jvm_Bitstream.scala + From 252c92fa50a405fce44fbb0d1ba9e1b049536670 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 30 Oct 2023 09:46:04 +0100 Subject: [PATCH 054/174] adapt changed functions of bitstream in STG files --- StgScala/acn_scala.stg | 24 +++++++++++------------ StgScala/test_cases_scala.stg | 2 +- StgScala/uper_scala.stg | 36 +++++++++++++++++------------------ 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index bb4299516..50ae36040 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -345,7 +345,7 @@ Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse { var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - BitStream_AppendBits(pBitStrm, if

then true_data else false_data, ) + pBitStrm.appendBits(if

then true_data else false_data, ) } >> @@ -370,7 +370,7 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - BitStream_AppendBits(pBitStrm, tmp, ) + pBitStrm.appendBits(tmp, ) } >> @@ -570,7 +570,7 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -BitStream_AppendBits(pBitStrm, (byte[]){}, ) +pBitStrm.appendBits((byte[]){}, ) >> oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << @@ -594,7 +594,7 @@ if (ret && (checkBitPatternPresentResult == 0)) { >> bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -BitStream_AppendBits(pBitStrm,

arr,

nCount) +pBitStrm.appendBits(

arr,

nCount) >> bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << @@ -608,7 +608,7 @@ if (\<=) && (\<=) t >> bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -BitStream_AppendBits(pBitStrm,

arr, ) +pBitStrm.appendBits(

arr, ) >> bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << @@ -621,8 +621,8 @@ if (\<=) && (\<=) t >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -BitStream_AppendBits(pBitStrm,

arr,

nCount) -BitStream_AppendBits(pBitStrm, (byte[]){}, ) +pBitStrm.appendBits(

arr,

nCount) +pBitStrm.appendBits((byte[]){}, ) >> bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << @@ -650,9 +650,9 @@ ret = _ACN_Decode(

, pBitStrm, pErrCode,

exist. = bit case None() => @@ -1048,7 +1048,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -BitStream_AppendBits(pBitStrm, arr, .asInstanceOf[Int]) +pBitStrm.appendBits(arr, .asInstanceOf[Int]) >> bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << @@ -1143,11 +1143,11 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit if ret.isRight then val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - BitStream_AppendBits(pBitStrm, bitStrm.buf, nCount); + pBitStrm.appendBits(bitStrm.buf, nCount); BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount, , ) - BitStream_AppendBits(pBitStrm, bitStrm.buf, nCount) + pBitStrm.appendBits(bitStrm.buf, nCount) } diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 6867216d1..6f106cbf7 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -60,7 +60,7 @@ Codec_Encode(sModName, sFuncName, sVal) ::= << Codec_Decode(sModName, sFuncName, sTasName, sEnc, sAmber) ::= << // test_cases_scala.stg:62 -BitStream_AttachBuffer(bitStrm, bitStrm.buf) // TODO: reset curBit, curByte instead? +bitStrm.attachBuffer(bitStrm.buf) // TODO: reset curBit, curByte instead? // Decode value (bitStrm) match case Left(_) => return Left(2) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 5848f60c1..5d77c5abf 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -75,7 +75,7 @@ def (@annotation.unused pBitStrm: BitSt >> InternalItem_oct_str_encode(p, sAcc, i, sErrCode) ::=<< -BitStream_AppendByte0(pBitStrm,

arr()) +pBitStrm.appendByte0(

arr()) >> InternalItem_oct_str_decode(p, sAcc, i, sErrCode) ::=<< @@ -181,7 +181,7 @@ IntNoneRequired_decode(p, nConst, sErrCode) ::= << /*case: A:: = INTEGER (5..40,...) */ IntRootExt_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< -BitStream_AppendBitZero(pBitStrm) /* write extension bit*/ +pBitStrm.appendBitZero() /* write extension bit*/ >> @@ -190,7 +190,7 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< extBit: Ref[Boolean] = Ref(false) /* read extension bit*/ - val success = BitStream_ReadBit(pBitStrm, extBit)) + val success = pBitStrm.readBit(extBit) if success then if extBit == false then /* ext bit is zero ==> value is expecteted with root range*/ @@ -204,11 +204,11 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< /*case: A:: = INTEGER (5..40,..., 60..70) */ IntRootExt2_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< if then - BitStream_AppendBitZero(pBitStrm) /* write extension bit, value within root range, so ext bit is zero */ + pBitStrm.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ else /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ - BitStream_AppendBitOne(pBitStrm) + pBitStrm.appendBitOne() >> @@ -218,11 +218,11 @@ IntRootExt2_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=") +pBitStrm.appendBit(

) >> Boolean_decode(p, sErrCode) ::= << -BitStream_ReadBit(pBitStrm) match +pBitStrm.readBit() match case Some(bit) =>

= bit case None() => @@ -327,16 +327,16 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match /* CHOICE END*/ /* SEQUENCE START */ -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "BitStream_AppendBit(pBitStrm,

exist.);" +sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "pBitStrm.appendBit(

exist.);" sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << -BitStream_ReadBit(pBitStrm) match +pBitStrm.readBit() match case Some(bit) =>

exist. = bit case None() => return Left() >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "BitStream_AppendBit(pBitStrm, )" +sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "pBitStrm.appendBit( )" sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << @@ -490,7 +490,7 @@ BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int /* BIT STRING*/ bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast -BitStream_AppendBits(pBitStrm,

arr, .asInstanceOf[Int]) +pBitStrm.appendBits(

arr, .asInstanceOf[Int]) >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << BitStream_ReadBits(pBitStrm, .asInstanceOf[Int]) match @@ -524,7 +524,7 @@ while( \< ) { BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF) - BitStream_AppendBits(pBitStrm, &

arr[/8], (int)) + pBitStrm.appendBits(&

arr[/8], (int)) val =(int) @@ -544,7 +544,7 @@ FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize = ; BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) -BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); +pBitStrm.appendBits(&

arr[/8], (int)); for(=(int); \< (int)( + ); ++) @@ -562,12 +562,12 @@ FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingIt BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) -BitStream_AppendBit(pBitStrm, true) +pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0x7FFF) -BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); +pBitStrm.appendBits(&

arr[/8], (int)); for(=(int); \< (int)( + ); ++) @@ -603,7 +603,7 @@ while ( >= 0x4000 && \< (a BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF) - BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); + pBitStrm.appendBits(&

arr[/8], (int)); =.asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -620,11 +620,11 @@ while ( >= 0x4000 && \< (a if \<= 0x7F then BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) else - BitStream_AppendBit(pBitStrm, true) + pBitStrm.appendBit(true) BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0x7FFF) -BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); +pBitStrm.appendBits(&

arr[/8], (int)); = .asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) From 20d6a0c57d37e69067922b4af72b20d797c8fa40 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 30 Oct 2023 10:16:07 +0100 Subject: [PATCH 055/174] moved to BitStream: readPartialByte, appendPartialByte, readBits, readByteArray, appendByteArray, readBytePure, readByte --- StgScala/acn_scala.stg | 13 +- StgScala/uper_scala.stg | 12 +- .../scala/asn1scala/asn1jvm_Bitstream.scala | 192 ++++++++++++++- .../scala/asn1scala/asn1jvm_encoding.scala | 222 ++---------------- .../asn1scala/asn1jvm_encoding_acn.scala | 76 +++--- .../asn1scala/asn1jvm_encoding_uper.scala | 2 +- 6 files changed, 260 insertions(+), 257 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 50ae36040..34d8004de 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -600,7 +600,7 @@ pBitStrm.appendBits(

arr,

nCount) bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then

nCount = .asInstanceOf[Int] - BitStream_ReadBits(pBitStrm,

nCount) match + pBitStrm.readBits(

nCount) match case NoneMut() => return Left() case SomeMut(arr) =>

arr = arr @@ -613,7 +613,7 @@ pBitStrm.appendBits(

arr, ) bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then - BitStream_ReadBits(pBitStrm, ) match + pBitStrm.readBits() match case NoneMut() => return Left() case SomeMut(arr) =>

arr = arr @@ -626,8 +626,7 @@ pBitStrm.appendBits((byte[]){}, > bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -// TODO acn:620 - wrong ret value? reads bits untill 0 termination, but only length is returned, not the data -BitStream_ReadBits_nullterminated(pBitStrm, (byte[]){}, ,

arr, ) match +// TODO acn:620 - wrong ret value? reads bits untill 0 termination, but only length is returned, not the datanullterminated.rReadBits_BitStrm, (byte[]){}, ,

arr, ) match case None() => return Left() case Some(x) => @@ -1057,7 +1056,7 @@ bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncodi /* decode to a temporary bitstream */ val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then - BitStream_ReadBits(pBitStrm, (int)) match + pBitStrm.readBits((int)) match case NoneMut() => return Left() case SomeMut(arr) => @@ -1160,7 +1159,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit val bitStrm: BitStream = BitStream_Init() - BitStream_ReadBits(pBitStrm, ) match + pBitStrm.readBits() match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1178,7 +1177,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit nCount = x ret = Right(0) - BitStream_ReadBits(pBitStrm, nCount) match + pBitStrm.readBits(nCount) match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 5d77c5abf..ef79ab672 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -493,7 +493,7 @@ assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast pBitStrm.appendBits(

arr, .asInstanceOf[Int]) >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << -BitStream_ReadBits(pBitStrm, .asInstanceOf[Int]) match +pBitStrm.readBits(.asInstanceOf[Int]) match case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -647,7 +647,7 @@ for( = 0; ret && \< ; ++) { ret = if (check) then Right(0) else Left() if ret == 0 then - ret = BitStream_ReadBits(pBitStrm, &

arr[/8], ).asInstanceOf[Int] + ret = pBitStrm.readBits(&

arr[/8], ).asInstanceOf[Int] ret = if (ret == 0) 0 else ; @@ -673,7 +673,7 @@ val check = (ret == 0) && ( == ); ret = if (check) then Right(0) else Left() if ret.isRight then - ret = BitStream_ReadBits(pBitStrm, &

arr[/8], .asInstanceOf[Int]); // TODO call wrong + ret = pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong ret = if (ret == 0) then Right(0) else Left() @@ -700,7 +700,7 @@ ret = ret && ((0x8000 & ) > 0) && ( (0x7FFF & if ret == 0 then - ret = BitStream_ReadBits(pBitStrm, &

arr[/8], .asInstanceOf[Int]); // TODO call wrong + ret = pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong ret = if (ret.isRight) then Right(0) else Left() @@ -752,7 +752,7 @@ while(( & 0xC0) == 0xC0) { return Left() - if !BitStream_ReadBits(pBitStrm, &

arr[/8], ) then + if !pBitStrm.readBits(&

arr[/8], ) then return = @@ -790,7 +790,7 @@ if ( + \<= ) then return Left() -if(!BitStream_ReadBits(pBitStrm, &

arr[/8], .asInstanceOf[Int])) // TODO remove adress of operator +if(!pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int])) // TODO remove adress of operator return diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index a3927133a..dd66fe97e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -8,6 +8,26 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* + +// TODO should be part of BitStream +def isPrefix(b1: BitStream, b2: BitStream): Boolean = { + b1.buf.length <= b2.buf.length && + b1.bitIndex() <= b2.bitIndex() && + (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex()) +} + +def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) + +@ghost +def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { + require(isValidPair(w1, w2)) + val r1 = BitStream(snapshot(w2.buf), w1.currentByte, w1.currentBit) + val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) + (r1, r2) +} +// END TODO should be part of BitStream + + object BitStream { @pure @inline def invariant(pBitStrm: BitStream): Boolean = { @@ -239,7 +259,7 @@ case class BitStream( if remainingBits > 0 then lastByte = ((srcBuffer(bytesToEncode) & 0xFF) >>> (8 - remainingBits)).toByte - BitStream_AppendPartialByte(this, lastByte, remainingBits, false) + this.appendPartialByte(lastByte, remainingBits, false) } def appendBit(v: Boolean): Unit = { @@ -356,7 +376,7 @@ case class BitStream( val w2 = this w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { val (r1, r2) = reader(w1, w2) - val (r2Got, vGot) = BitStream_ReadBytePure(r1) + val (r2Got, vGot) = r1.readBytePure() ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 } &&& BitStream.invariant(this) } @@ -385,4 +405,172 @@ case class BitStream( true }.ensuring(_ => BitStream.invariant(this)) + def readByte(): Option[UByte] = { + require(BitStream.validate_offset_bytes(this, 1)) + + val cb: UByte = currentBit.toByte + val ncb: UByte = (8 - cb).toByte + + var v: UByte = buf(currentByte) <<<< cb + currentByte += 1 + + if cb > 0 then + v = (v | (buf(currentByte) >>>> ncb)).toByte + + if BitStream.invariant(this) then + Some(v) + else + None() + } + + @ghost + @pure + def readBytePure(): (BitStream, Option[Byte]) = { + require(BitStream.validate_offset_bytes(this, 1)) + val cpy = snapshot(this) + (cpy, this.readByte()) + } + + + def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { + require(0 <= arr_len && arr_len <= arr.length) + require(BitStream.validate_offset_bytes(this, arr_len)) + + if !(currentByte.toLong + arr_len < buf.length || (currentBit == 0 && currentByte.toLong + arr_len <= buf.length)) then + return false + + var i: Int = 0 + (while i < arr_len do + decreases(arr_len - i) + this.appendByte0(arr(i)) + i += 1 + ).invariant(0 <= i &&& i <= arr_len &&& BitStream.validate_offset_bytes(this, arr_len - i)) + + true + }.ensuring(_ => BitStream.invariant(this)) + + + def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { + require(0 < arr_len && arr_len <= buf.length) + require(BitStream.validate_offset_bytes(this, arr_len)) + val arr: Array[UByte] = Array.fill(arr_len)(0) + + val cb = currentBit + val ncb = 8 - cb + + if !(currentByte.toLong + arr_len < buf.length || (currentBit == 0 && currentByte.toLong + arr_len <= buf.length)) then + return NoneMut() + + var i: Int = 0 + (while i < arr_len do + decreases(arr_len - i) + this.readByte() match + case Some(v) => arr(i) = v + case None() => return NoneMut() + i += 1 + ).invariant(0 <= i &&& i <= arr_len &&& i <= arr.length &&& BitStream.validate_offset_bytes(this, arr_len - i) &&& BitStream.invariant(this)) + + SomeMut(arr) + } + + def readBits(nbits: Int): OptionMut[Array[UByte]] = { + val bytesToRead: Int = nbits / 8 + val remainingBits: UByte = (nbits % 8).toByte + + BitStream_DecodeOctetString_no_length(this, bytesToRead) match + case NoneMut() => return NoneMut() + case SomeMut(arr) => + if remainingBits > 0 then + this.readPartialByte(remainingBits) match + case None() => return NoneMut() + case Some(ub) => arr(bytesToRead) = ub + arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte + SomeMut(arr) + else + SomeMut(arr) + } + + + /* nbits 1..7*/ + def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { + val cb: UByte = currentBit.toByte + val totalBits: UByte = (cb + nbits).toByte + val ncb: UByte = (8 - cb).toByte + + var v = vVal + if negate then + v = (masksb(nbits) & (~v)).toByte + + val mask1: UByte = (~masksb(ncb)).toByte + + if (totalBits <= 8) { + //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; + val mask2: UByte = masksb(8 - totalBits) + val mask: UByte = (mask1 | mask2).toByte + //e.g. current bit = 3 --> mask = 1110 0000 + //nbits = 3 --> totalBits = 6 + // mask= 1110 0000 + // and 0000 0011 <- masks[totalBits - 1] + // ----------- + // final mask 1110 0011 + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v << (8 - totalBits))).toByte + currentBit += nbits.toInt + if currentBit == 8 then + currentBit = 0 + currentByte += 1 + + } else { + val totalBitsForNextByte: UByte = (totalBits - 8).toByte + buf(currentByte) = (buf(currentByte) & mask1).toByte + buf(currentByte) = (buf(currentByte) | (v >>> totalBitsForNextByte)).toByte + currentByte += 1 + val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v << (8 - totalBitsForNextByte))).toByte + currentBit = totalBitsForNextByte.toInt + } + + assert(currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8) + } + + /* nbits 1..7*/ + def readPartialByte(nbits: UByte): Option[UByte] = { + require(0 <= nbits && nbits < 8) + require(BitStream.validate_offset_bits(this, nbits)) + + var v: UByte = 0 + val cb: UByte = currentBit.toByte + val totalBits: UByte = (cb + nbits).toByte + + if (totalBits <= 8) { + + ghostExpr { + BitStream.invariant(this) + } + v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nbits)).toByte + ghostExpr { + BitStream.validate_offset_bits(this, nbits) + } + if currentBit + nbits >= 8 then + currentBit = (currentBit + nbits) % 8 + currentByte += 1 + else + currentBit += nbits.toInt + + } else { + var totalBitsForNextByte: UByte = (totalBits - 8).toByte + v = (buf(currentByte) <<<< totalBitsForNextByte) + currentByte += 1 + v = (v | buf(currentByte) >>>> (8 - totalBitsForNextByte)).toByte + v = (v & masksb(nbits)).toByte + currentBit = totalBitsForNextByte.toInt + } + + if BitStream.invariant(this) then + Some(v) + else + None() + } + } // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala index a93b80b15..44fb27b0e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala @@ -79,190 +79,6 @@ or 00010000 **/ -// TODO should be part of BitStream -def isPrefix(b1: BitStream, b2: BitStream): Boolean = { - b1.buf.length <= b2.buf.length && - b1.bitIndex() <= b2.bitIndex() && - (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex()) -} - -def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) - -@ghost -def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { - require(isValidPair(w1, w2)) - val r1 = BitStream(snapshot(w2.buf), w1.currentByte, w1.currentBit) - val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) - (r1, r2) -} -// END TODO should be part of BitStream - - - -def BitStream_AppendByteArray(pBitStrm: BitStream, arr: Array[UByte], arr_len: Int): Boolean = { - require(0 <= arr_len && arr_len <= arr.length) - require(BitStream.validate_offset_bytes(pBitStrm, arr_len)) - - if !(pBitStrm.currentByte.toLong + arr_len < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && pBitStrm.currentByte.toLong + arr_len <= pBitStrm.buf.length)) then - return false - - var i: Int = 0 - (while i < arr_len do - decreases(arr_len - i) - pBitStrm.appendByte0(arr(i)) - i += 1 - ).invariant(0 <= i &&& i <= arr_len &&& BitStream.validate_offset_bytes(pBitStrm, arr_len-i)) - - true -}.ensuring(_ => BitStream.invariant(pBitStrm)) - -def BitStream_ReadByte(pBitStrm: BitStream): Option[UByte] = { - require(BitStream.validate_offset_bytes(pBitStrm, 1)) - - val cb: UByte = pBitStrm.currentBit.toByte - val ncb: UByte = (8 - cb).toByte - - var v: UByte = (pBitStrm.buf(pBitStrm.currentByte) <<<< cb) - pBitStrm.currentByte += 1 - - if cb > 0 then - v = (v | (pBitStrm.buf(pBitStrm.currentByte) >>>> ncb)).toByte - - if BitStream.invariant(pBitStrm) then - Some(v) - else - None() -} - -@ghost @pure -def BitStream_ReadBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { - require(BitStream.validate_offset_bytes(pBitStrm, 1)) - val cpy = snapshot(pBitStrm) - (cpy, BitStream_ReadByte(cpy)) -} - -def BitStream_ReadByteArray(pBitStrm: BitStream, arr_len: Int): OptionMut[Array[UByte]] = { - require(0 < arr_len && arr_len <= pBitStrm.buf.length) - require(BitStream.validate_offset_bytes(pBitStrm, arr_len)) - val arr: Array[UByte] = Array.fill(arr_len)(0) - - val cb = pBitStrm.currentBit - val ncb = 8 - cb - - if !(pBitStrm.currentByte.toLong + arr_len < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && pBitStrm.currentByte.toLong + arr_len <= pBitStrm.buf.length)) then - return NoneMut() - - var i: Int = 0 - (while i < arr_len do - decreases(arr_len - i) - BitStream_ReadByte(pBitStrm) match - case Some(v) => arr(i) = v - case None() => return NoneMut() - i += 1 - ).invariant(0 <= i &&& i <= arr_len &&& i <= arr.length &&& BitStream.validate_offset_bytes(pBitStrm, arr_len-i) &&& BitStream.invariant(pBitStrm)) - - SomeMut(arr) -} - -def BitStream_ReadBits(pBitStrm: BitStream, nbits: Int): OptionMut[Array[UByte]] = { - val bytesToRead: Int = nbits / 8 - val remainingBits: UByte = (nbits % 8).toByte - - BitStream_DecodeOctetString_no_length(pBitStrm, bytesToRead) match - case NoneMut() => return NoneMut() - case SomeMut(arr) => - if remainingBits > 0 then - BitStream_ReadPartialByte(pBitStrm, remainingBits) match - case None() => return NoneMut() - case Some(ub) => arr(bytesToRead) = ub - arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte - SomeMut(arr) - else - SomeMut(arr) -} - - -/* nbits 1..7*/ -def BitStream_AppendPartialByte(pBitStrm: BitStream, vVal: UByte, nbits: UByte, negate: Boolean): Unit = { - val cb: UByte = pBitStrm.currentBit.toByte - val totalBits: UByte = (cb + nbits).toByte - val ncb: UByte = (8 - cb).toByte - - var v = vVal - if negate then - v = (masksb(nbits) & (~v)).toByte - - val mask1: UByte = (~masksb(ncb)).toByte - - if (totalBits <= 8) { - //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; - val mask2: UByte = masksb(8 - totalBits) - val mask: UByte = (mask1 | mask2).toByte - //e.g. current bit = 3 --> mask = 1110 0000 - //nbits = 3 --> totalBits = 6 - // mask= 1110 0000 - // and 0000 0011 <- masks[totalBits - 1] - // ----------- - // final mask 1110 0011 - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v << (8 - totalBits))).toByte - pBitStrm.currentBit += nbits.toInt - if pBitStrm.currentBit == 8 then - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 - - } else { - val totalBitsForNextByte: UByte = (totalBits - 8).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask1).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v >>> totalBitsForNextByte)).toByte - pBitStrm.currentByte += 1 - val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) & mask).toByte - pBitStrm.buf(pBitStrm.currentByte) = (pBitStrm.buf(pBitStrm.currentByte) | (v << (8 - totalBitsForNextByte))).toByte - pBitStrm.currentBit = totalBitsForNextByte.toInt - } - - assert(pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong*8) -} - -/* nbits 1..7*/ -def BitStream_ReadPartialByte(pBitStrm: BitStream, nbits: UByte): Option[UByte] = { - require(0 <= nbits && nbits < 8) - require(BitStream.validate_offset_bits(pBitStrm, nbits)) - - var v: UByte = 0 - val cb: UByte = pBitStrm.currentBit.toByte - val totalBits: UByte = (cb + nbits).toByte - - if (totalBits <= 8) { - - ghostExpr { - BitStream.invariant(pBitStrm) - } - v = ((pBitStrm.buf(pBitStrm.currentByte) >>>> (8 - totalBits)) & masksb(nbits)).toByte - ghostExpr { - BitStream.validate_offset_bits(pBitStrm, nbits) - } - if pBitStrm.currentBit + nbits >= 8 then - pBitStrm.currentBit = (pBitStrm.currentBit + nbits) % 8 - pBitStrm.currentByte += 1 - else - pBitStrm.currentBit += nbits.toInt - - } else { - var totalBitsForNextByte: UByte = (totalBits - 8).toByte - v = (pBitStrm.buf(pBitStrm.currentByte) <<<< totalBitsForNextByte) - pBitStrm.currentByte += 1 - v = (v | pBitStrm.buf(pBitStrm.currentByte) >>>> (8 - totalBitsForNextByte)).toByte - v = (v & masksb(nbits)).toByte - pBitStrm.currentBit = totalBitsForNextByte.toInt - } - - if BitStream.invariant(pBitStrm) then - Some(v) - else - None() -} /***********************************************************************************************/ @@ -303,7 +119,7 @@ def BitStream_EncodeNonNegativeInteger32Neg(pBitStrm: BitStream, v: Int, negate: pbits = cc % 8 if pbits > 0 then cc -= pbits - BitStream_AppendPartialByte(pBitStrm, (v >>> cc).toByte, pbits.toByte, negate) + pBitStrm.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) while cc > 0 do decreases(cc) @@ -320,7 +136,7 @@ def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): decreases(nBits) v = v << 8 - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) @@ -331,7 +147,7 @@ def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): if nBits != 0 then v = v << nBits - BitStream_ReadPartialByte(pBitStrm, nBits.toByte) match + pBitStrm.readPartialByte(nBits.toByte) match case None() => return None() case Some(ub) => v = v | (ub & 0xFF) @@ -590,7 +406,7 @@ def BitStream_DecodeSemiConstraintWholeNumber(pBitStrm:BitStream, min: Long): Op while i < nBytes do decreases(nBytes - i) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -614,7 +430,7 @@ def BitStream_DecodeSemiConstraintPosWholeNumber(pBitStrm:BitStream, min: ULong) while i < nBytes do decreases(nBytes - i) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -655,7 +471,7 @@ def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = while i < nBytes do decreases(nBytes - i) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -832,7 +648,7 @@ def BitStream_DecodeReal(pBitStrm: BitStream): Option[Double] = { } def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(length) => // 8.5.2 Plus Zero @@ -843,7 +659,7 @@ def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { if length < 0 || length > DoubleMaxLengthOfSentBytes then return None() - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(header) => // 8.5.6 a) @@ -901,7 +717,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt (while i < expLen do decreases(expLen - i) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) @@ -915,7 +731,7 @@ def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByt (while j < length do decreases(length - j) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) @@ -944,7 +760,7 @@ def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern while bit_terminated_pattern_size_in_bits >= 8 do decreases(bit_terminated_pattern_size_in_bits) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return 0 case Some(ub) => tmp_byte = ub @@ -956,7 +772,7 @@ def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern i += 1 if bit_terminated_pattern_size_in_bits > 0 then - BitStream_ReadPartialByte(pBitStrm, bit_terminated_pattern_size_in_bits) match + pBitStrm.readPartialByte(bit_terminated_pattern_size_in_bits) match case None() => return 0 case Some(ub) => tmp_byte = ub @@ -1011,7 +827,7 @@ def BitStream_EncodeOctetString_no_length(pBitStrm: BitStream, arr: Array[UByte] pBitStrm.currentByte += nCount else - ret = BitStream_AppendByteArray(pBitStrm, arr, nCount) + ret = pBitStrm.appendByteArray(arr, nCount) ret } @@ -1029,7 +845,7 @@ def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): Opt pBitStrm.currentByte += nCount else - BitStream_ReadByteArray(pBitStrm, nCount) match + pBitStrm.readByteArray(nCount) match case NoneMut() => return NoneMut() case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) @@ -1120,7 +936,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: var i1: Int = nCurOffset1.toInt while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 @@ -1152,7 +968,7 @@ def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: // fill last payload fragment into dest while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 @@ -1269,7 +1085,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa else nCount = asn1SizeMin - return BitStream_ReadBits(pBitStrm, nCount.toInt) + return pBitStrm.readBits(nCount.toInt) } else { var nRemainingItemsVar1: Long = 0 @@ -1299,7 +1115,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa return NoneMut() /*COVERAGE_IGNORE*/ - BitStream_ReadBits(pBitStrm, nCurBlockSize1.toInt) match + pBitStrm.readBits(nCurBlockSize1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) @@ -1319,7 +1135,7 @@ def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMa if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - BitStream_ReadBits(pBitStrm, nRemainingItemsVar1.toInt) match + pBitStrm.readBits(nRemainingItemsVar1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala index 073e49411..f0d06b929 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala @@ -129,7 +129,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, encodedSizeInBits def Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm: BitStream): Option[ULong] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(ub) => Some(ub & 0xFF) } @@ -140,7 +140,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm: BitStream, Size var i: Int = 0 while i < SizeInBytes do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => ret <<= 8 @@ -174,7 +174,7 @@ def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, S var i: Int = 0 while i < SizeInBytes do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => tmp = ub & 0xFF @@ -235,12 +235,12 @@ def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream): Opt { var v: ULong = 0 - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(nBytes) => var i: Int = 0 while i < nBytes do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF) @@ -309,14 +309,14 @@ def Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm: BitStream, encodedSizeInBits: var i: Int = 0 while i < nBytes do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => pIntVal = (pIntVal << 8) | (ub & 0xFF) i += 1 if rstBits > 0 then - BitStream_ReadPartialByte(pBitStrm, rstBits.toByte) match + pBitStrm.readPartialByte(rstBits.toByte) match case None() => return None() case Some(ub) => pIntVal = (pIntVal << rstBits) | (ub & 0xFF) @@ -393,12 +393,12 @@ def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream): Opti var v: ULong = 0 var isNegative: Boolean = false - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(nBytes) => var i: Int = 0 while i < nBytes do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => if i == 0 && (ub & 0x80) > 0 then @@ -445,7 +445,7 @@ def Acn_Enc_Int_BCD_ConstSize(pBitStrm: BitStream, intVal: ULong, encodedSizeInN var i: Int = encodedSizeInNibbles - 1 while i >= 0 do - BitStream_AppendPartialByte(pBitStrm, tmp(i).toByte, 4,false) + pBitStrm.appendPartialByte(tmp(i).toByte, 4,false) i -= 1 CHECK_BIT_STREAM(pBitStrm) @@ -458,7 +458,7 @@ def Acn_Dec_Int_BCD_ConstSize(pBitStrm: BitStream, encodedSizeInNibbles: Int): O var encodedSizeInNibblesVar = encodedSizeInNibbles while encodedSizeInNibblesVar > 0 do - BitStream_ReadPartialByte(pBitStrm, 4) match + pBitStrm.readPartialByte(4) match case None() => return None() case Some(digit) => ret *= 10 @@ -484,7 +484,7 @@ def Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): def Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(nNibbles) => Acn_Dec_Int_BCD_ConstSize(pBitStrm, nNibbles) } @@ -499,7 +499,7 @@ def Acn_Enc_Int_BCD_VarSize_NullTerminated(pBitStrm: BitStream, intVal: ULong): /* Encode Number */ Acn_Enc_Int_BCD_ConstSize(pBitStrm, intVal, nNibbles) - BitStream_AppendPartialByte(pBitStrm, 0xF, 4, false) + pBitStrm.appendPartialByte(0xF, 4, false) CHECK_BIT_STREAM(pBitStrm) } @@ -509,7 +509,7 @@ def Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm: BitStream): Option[ULong] = var ret: ULong = 0 while true do - BitStream_ReadPartialByte(pBitStrm, 4) match + pBitStrm.readPartialByte(4) match case None() => return None() case Some(digit) => if (digit > 9) @@ -562,7 +562,7 @@ def Acn_Dec_UInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): var ret: ULong = 0 while encodedSizeInBytesVar > 0 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(digit) => assert(digit >= '0' && digit <= '9') @@ -577,7 +577,7 @@ def Acn_Dec_UInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): def Acn_Dec_SInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Long] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(digit) => var sign: Int = 1 @@ -658,14 +658,14 @@ def Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong def Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(nChars) => Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, nChars) } def Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[Long] = { - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(nChars) => Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, nChars) } @@ -705,7 +705,7 @@ val tmp: Array[Byte] = Array.fill(10)(0) memset(strVal, 0x0, (size_t)max + 1); //read null_character_size characters into the tmp buffer for (int j = 0; j < (int)null_character_size; j++) { -if (!BitStream_ReadByte(pBitStrm, &(tmp[j]))) +if (!pBitStrm.readByte(, &(tmp[j]))) return FALSE; } @@ -715,7 +715,7 @@ strVal[i] = tmp[0]; i++; for (int j = 0; j < (int)null_character_size - 1; j++) tmp[j] = tmp[j + 1]; -if (!BitStream_ReadByte(pBitStrm, &(tmp[null_character_size - 1]))) +if (!pBitStrm.readByte(, &(tmp[null_character_size - 1]))) return FALSE; } @@ -739,7 +739,7 @@ def Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte //read null_character_size characters into the tmp buffer var j: Int = 0 while j < null_characters_size do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -754,7 +754,7 @@ def Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte tmp(j) = tmp(j + 1) j += 1 - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => tmp(null_characters_size - 1) = ub @@ -771,7 +771,7 @@ def Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characte { var isNegative: Boolean = false - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => None() case Some(digit) => assert(digit == '-' || digit == '+') @@ -794,7 +794,7 @@ def BitStream_ReadBitPattern(pBitStrm: BitStream, patternToRead: Array[Byte], nB var pBoolValue: Boolean = true var i: Int = 0 while i < nBytesToRead do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(curByte) => if curByte != patternToRead(i) then @@ -802,7 +802,7 @@ def BitStream_ReadBitPattern(pBitStrm: BitStream, patternToRead: Array[Byte], nB i += 1 if nRemainingBitsToRead > 0 then - BitStream_ReadPartialByte(pBitStrm, nRemainingBitsToRead.toByte) match + pBitStrm.readPartialByte(nRemainingBitsToRead.toByte) match case None() => return None() case Some(curByte) => if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then @@ -819,12 +819,12 @@ def BitStream_ReadBitPattern_ignore_value(pBitStrm: BitStream, nBitsToRead: Int) var i: Int = 0 while i < nBytesToRead do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return Left(FAILED_READ_ERR_CODE) case Some(_) => i += 1 if nRemainingBitsToRead > 0 then - if BitStream_ReadPartialByte(pBitStrm, nRemainingBitsToRead.toByte).isEmpty then + if pBitStrm.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then return Left(FAILED_READ_ERR_CODE) Right(0) @@ -847,7 +847,7 @@ def Acn_Dec_Real_IEEE754_32_big_endian(pBitStrm: BitStream): Option[Double] = val b: Array[Byte] = Array.fill(4)(0) var i: Int = 0 while i < 4 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -861,7 +861,7 @@ def Acn_Dec_Real_IEEE754_32_big_endian_fp32(pBitStrm: BitStream): Option[Float] val b: Array[Byte] = Array.fill(4)(0) var i: Int = 0 while i < 4 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -886,7 +886,7 @@ def Acn_Dec_Real_IEEE754_64_big_endian(pBitStrm: BitStream): Option[Double] = val b: Array[Byte] = Array.fill(8)(0) var i: Int = 0 while i < 8 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -911,7 +911,7 @@ def Acn_Dec_Real_IEEE754_32_little_endian(pBitStrm: BitStream): Option[Double] = val b: Array[Byte] = Array.fill(4)(0) var i: Int = 3 while i >= 0 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -925,7 +925,7 @@ def Acn_Dec_Real_IEEE754_32_little_endian_fp32(pBitStrm: BitStream): Option[Floa val b: Array[Byte] = Array.fill(4)(0) var i: Int = 3 while i >= 0 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -949,7 +949,7 @@ def Acn_Dec_Real_IEEE754_64_little_endian(pBitStrm: BitStream): Option[Double] = val b: Array[Byte] = Array.fill(8)(0) var i: Int = 7 while i >= 0 do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -1090,7 +1090,7 @@ def Acn_Dec_String_Ascii_private(pBitStrm: BitStream, max: Long, charactersToDec val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) var i: Int = 0 while i < charactersToDecode do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(decodedCharacter) => strVal(i) = decodedCharacter @@ -1135,7 +1135,7 @@ assert(null_characters_size<128); memset(last_dec_bytes, 0x0, sizeof(last_dec_bytes)); memset(strVal, 0x0, (size_t)max+1); while (i<=max) { -if (!BitStream_ReadByte(pBitStrm, &decodedCharacter)) +if (!pBitStrm.readByte(, &decodedCharacter)) return FALSE; ret = put_byte_in_last_dec_bytes(last_dec_bytes, &cur_size_of_last_dec_bytes, null_characters_size, decodedCharacter, &characterToAppendInString); @@ -1162,7 +1162,7 @@ def Acn_Dec_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_cha val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) var i: Int = 0 while i <= max do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(decodedCharacter) => if decodedCharacter != null_character then @@ -1183,7 +1183,7 @@ def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, nul //read null_character_size characters into the tmp buffer var j: Int = 0 while j < null_character_size do - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -1198,7 +1198,7 @@ def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, nul tmp(j) = tmp(j + 1) j += 1 - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(ub) => tmp(null_character_size - 1) = ub diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala index d96f1ac1b..4c63e03a3 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala @@ -87,7 +87,7 @@ def ObjectIdentifier_subidentifiers_uper_decode(pBitStrm: BitStream, pRemainingO var pRemainingOctets: Long = pRemainingOctetsVal while pRemainingOctets > 0 && !bLastOctet do decreases(pRemainingOctets) - BitStream_ReadByte(pBitStrm) match + pBitStrm.readByte() match case None() => return None() case Some(curByte) => pRemainingOctets -= 1 From 9fd9929985a3ed4572a0e9599ba79a47310cefc6 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 30 Oct 2023 12:50:14 +0100 Subject: [PATCH 056/174] validate readPartialByte --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 46 +++++++++---------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index dd66fe97e..97510e08c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -25,6 +25,14 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) (r1, r2) } + +@ghost @pure +def readBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { + require(BitStream.validate_offset_bytes(pBitStrm, 1)) + val cpy = snapshot(pBitStrm) + (cpy, cpy.readByte()) +} + // END TODO should be part of BitStream @@ -82,6 +90,17 @@ object BitStream { } } +private val BitAccessMasks: Array[UByte] = Array( + -0x80, // -128 / 1000 0000 / x80 + 0x40, // 64 / 0100 0000 / x40 + 0x20, // 32 / 0010 0000 / x20 + 0x10, // 16 / 0001 0000 / x10 + 0x08, // 8 / 0000 1000 / x08 + 0x04, // 4 / 0000 0100 / x04 + 0x02, // 2 / 0000 0010 / x02 + 0x01, // 1 / 0000 0001 / x01 +) + case class BitStream( var buf: Array[Byte], var currentByte: Int, // marks the currentByte that gets accessed @@ -89,16 +108,6 @@ case class BitStream( ) { // all BisStream instances satisfy the following: require(BitStream.invariant(currentByte, currentBit, buf.length)) - private val BitAccessMasks: Array[UByte] = Array( - -0x80, // -128 / 1000 0000 / x80 - 0x40, // 64 / 0100 0000 / x40 - 0x20, // 32 / 0010 0000 / x20 - 0x10, // 16 / 0001 0000 / x10 - 0x08, // 8 / 0000 1000 / x08 - 0x04, // 4 / 0000 0100 / x04 - 0x02, // 2 / 0000 0010 / x02 - 0x01, // 1 / 0000 0001 / x01 - ) def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong @@ -245,6 +254,7 @@ case class BitStream( appendBitOne() nBits -= 1 ).invariant(nBits >= 0 &&& BitStream.validate_offset_bits(this, nBits)) + () } def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { @@ -376,7 +386,7 @@ case class BitStream( val w2 = this w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { val (r1, r2) = reader(w1, w2) - val (r2Got, vGot) = r1.readBytePure() + val (r2Got, vGot) = readBytePure(r1) ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 } &&& BitStream.invariant(this) } @@ -423,14 +433,6 @@ case class BitStream( None() } - @ghost - @pure - def readBytePure(): (BitStream, Option[Byte]) = { - require(BitStream.validate_offset_bytes(this, 1)) - val cpy = snapshot(this) - (cpy, this.readByte()) - } - def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { require(0 <= arr_len && arr_len <= arr.length) @@ -536,7 +538,7 @@ case class BitStream( /* nbits 1..7*/ def readPartialByte(nbits: UByte): Option[UByte] = { - require(0 <= nbits && nbits < 8) + require(0 < nbits && nbits < 8) require(BitStream.validate_offset_bits(this, nbits)) var v: UByte = 0 @@ -544,10 +546,6 @@ case class BitStream( val totalBits: UByte = (cb + nbits).toByte if (totalBits <= 8) { - - ghostExpr { - BitStream.invariant(this) - } v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nbits)).toByte ghostExpr { BitStream.validate_offset_bits(this, nbits) From d56d046d1ce322188a6363a9cf0f9667bb655540 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 30 Oct 2023 16:34:06 +0100 Subject: [PATCH 057/174] OOP refactoring & renaming --- .../src/main/scala/asn1scala/asn1jvm.scala | 6 +- .../scala/asn1scala/asn1jvm_Bitstream.scala | 23 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 1004 +++++++++ .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 1580 ++++++++++++++ .../scala/asn1scala/asn1jvm_Codec_PER.scala | 13 + .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 199 ++ .../main/scala/asn1scala/asn1jvm_Helper.scala | 196 ++ ...utils.scala => asn1jvm_Verification.scala} | 4 - .../scala/asn1scala/asn1jvm_encoding.scala | 1147 ---------- .../asn1scala/asn1jvm_encoding_acn.scala | 1837 ----------------- .../asn1scala/asn1jvm_encoding_uper.scala | 182 -- .../scala/asn1scala/asn1jvm_unsigned.scala | 69 - asn1scc/GenerateRTL.fs | 12 +- asn1scc/asn1jvm_Codec.scala | 1004 +++++++++ asn1scc/asn1jvm_Codec_ACN.scala | 1580 ++++++++++++++ asn1scc/asn1jvm_Codec_PER.scala | 13 + asn1scc/asn1jvm_Codec_UPER.scala | 199 ++ asn1scc/asn1jvm_Helper.scala | 196 ++ asn1scc/asn1jvm_Verification.scala | 193 ++ asn1scc/asn1scc.fsproj | 21 +- 20 files changed, 6209 insertions(+), 3269 deletions(-) create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala create mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala rename asn1scala/src/main/scala/asn1scala/{stainless_utils.scala => asn1jvm_Verification.scala} (95%) delete mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala delete mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala delete mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala delete mode 100644 asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala create mode 100644 asn1scc/asn1jvm_Codec.scala create mode 100644 asn1scc/asn1jvm_Codec_ACN.scala create mode 100644 asn1scc/asn1jvm_Codec_PER.scala create mode 100644 asn1scc/asn1jvm_Codec_UPER.scala create mode 100644 asn1scc/asn1jvm_Helper.scala create mode 100644 asn1scc/asn1jvm_Verification.scala diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index c6ed3d731..a0dea3587 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -28,6 +28,8 @@ type asn1Real = Double val NO_OF_BITS_IN_BYTE = 8 val NO_OF_BITS_IN_LONG = 64 +val NO_OF_BYTES_IN_JVM_SHORT = 2 +val NO_OF_BYTES_IN_JVM_INT = 4 val NO_OF_BYTES_IN_JVM_LONG = 8 val OBJECT_IDENTIFIER_MAX_LENGTH = 20 @@ -290,7 +292,3 @@ def ObjectIdentifier_equal (pVal1: Asn1ObjectIdentifier, pVal2: Asn1ObjectIdenti return ret } - -def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { - assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) -} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 97510e08c..258fb739e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -103,8 +103,8 @@ private val BitAccessMasks: Array[UByte] = Array( case class BitStream( var buf: Array[Byte], - var currentByte: Int, // marks the currentByte that gets accessed - var currentBit: Int, // marks the next bit that gets accessed + var currentByte: Int = 0, // marks the currentByte that gets accessed + var currentBit: Int = 0, // marks the next bit that gets accessed ) { // all BisStream instances satisfy the following: require(BitStream.invariant(currentByte, currentBit, buf.length)) @@ -169,6 +169,20 @@ case class BitStream( (cpy, cpy.readBit()) } + /** + * Append bit one. + * + * Example + * cur bit = 3 + * x x x | + * |_|_|_|_|_|_|_|_| + * 0 1 2 3 4 5 6 7 + * + * xxxy???? + * or 00010000 + * ------------- + * xxx1???? + * */ @opaque @inlineOnce def appendBitOne(): Unit = { @@ -265,7 +279,7 @@ case class BitStream( val bytesToEncode: Int = nBits / 8 val remainingBits: UByte = (nBits % 8).toByte - BitStream_EncodeOctetString_no_length(this, srcBuffer, bytesToEncode) + appendByteArray(srcBuffer, bytesToEncode) if remainingBits > 0 then lastByte = ((srcBuffer(bytesToEncode) & 0xFF) >>> (8 - remainingBits)).toByte @@ -479,7 +493,7 @@ case class BitStream( val bytesToRead: Int = nbits / 8 val remainingBits: UByte = (nbits % 8).toByte - BitStream_DecodeOctetString_no_length(this, bytesToRead) match + readByteArray(bytesToRead) match case NoneMut() => return NoneMut() case SomeMut(arr) => if remainingBits > 0 then @@ -492,7 +506,6 @@ case class BitStream( SomeMut(arr) } - /* nbits 1..7*/ def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { val cb: UByte = currentBit.toByte diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala new file mode 100644 index 000000000..c17ba0ec8 --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -0,0 +1,1004 @@ +package asn1scala + +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +// TODO move to Bitstream if only used there +val masksb: Array[UByte] = Array( + 0x00, // 0 / 0000 0000 / x00 + 0x01, // 1 / 0000 0001 / x01 + 0x03, // 3 / 0000 0011 / x03 + 0x07, // 7 / 0000 0111 / x07 + 0x0F, // 15 / 0000 1111 / x0F + 0x1F, // 31 / 0001 1111 / x1F + 0x3F, // 63 / 0011 1111 / x3F + 0x7F, // 127 / 0111 1111 / x7F + -0x1, // -1 / 1111 1111 / xFF +) + +val masks2: Array[UInt] = Array( + 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 + 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF + 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000 FF00 + 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF 0000 + 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 +) + + +/***********************************************************************************************/ +/** Byte Stream Functions **/ +/***********************************************************************************************/ +def ByteStream_Init(count: Int): ByteStream = { + ByteStream(Array.fill(count)(0), 0, false) +} + +@extern +def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { + pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... + pStrm.currentByte = 0 +}.ensuring(_ => pStrm.buf == buf && pStrm.currentByte == 0 && pStrm.EncodeWhiteSpace == old(pStrm).EncodeWhiteSpace) + +def ByteStream_GetLength(pStrm: ByteStream): Int = { + pStrm.currentByte +} + +/***********************************************************************************************/ +/** Bit Stream Functions **/ +/***********************************************************************************************/ +def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { + arraySameElements(arr1, arr2) + //return + // (nBitsLength1 == nBitsLength2) && + // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && + // (nBitsLength1 % 8 > 0 ? (arr1[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8) == arr2[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8)): TRUE); +} + + +// TODO remove +def BitStream_Init(count: Int): BitStream = { + BitStream(Array.fill(count)(0), 0, 0) +} + +/** + * Parent class for the PER Codec that is used by ACN and UPER + * + * @param count represents the number of bytes in the internal buffer + */ +@mutable +trait Codec { + + def bitStream: BitStream + + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** Integer Functions * */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + + /** ******************************************************************************************** */ + def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { + var cc: UInt = 0 + var curMask: UInt = 0 + var pbits: UInt = 0 + + if v == 0 then + return () + + if v >>> 8 == 0 then + cc = 8 + curMask = 0x80 + else if v >>> 16 == 0 then + cc = 16 + curMask = 0x8000 + else if v >>> 24 == 0 then + cc = 24 + curMask = 0x800000 + else + cc = 32 + curMask = 0x80000000 + + while (v & curMask) == 0 do + decreases(cc) + curMask >>>= 1 + cc -= 1 + + pbits = cc % 8 + if pbits > 0 then + cc -= pbits + bitStream.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) + + while cc > 0 do + decreases(cc) + val t1: UInt = v.toInt & masks2(cc >>> 3) + cc -= 8 + bitStream.appendByte((t1 >>> cc).toByte, negate) + } + + def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { + + var v: UInt = 0 + + var nBits = nBitsVal + while nBits >= 8 do + decreases(nBits) + v = v << 8 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => + // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) + // will be casted to an Int -1 (1111 ... 1111) + v = v | (ub & 0xFF) + + nBits -= 8 + + if nBits != 0 then + v = v << nBits + bitStream.readPartialByte(nBits.toByte) match + case None() => return None() + case Some(ub) => v = v | (ub & 0xFF) + + Some(v) + } + + def encodeNonNegativeInteger(v: ULong): Unit = { + if v >>> 32 == 0 then + encodeNonNegativeInteger32Neg(v.toInt, false) + else + val hi = (v >>> 32).toInt + val lo = v.toInt + encodeNonNegativeInteger32Neg(hi, false) + + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? + bitStream.appendNBitZero(32 - nBits) + encodeNonNegativeInteger32Neg(lo, false) + } + + def decodeNonNegativeInteger(nBits: Int): Option[ULong] = { + if nBits <= 32 then + decodeNonNegativeInteger32Neg(nBits) match + case None() => return None() + case Some(lo) => + return Some(lo & 0xFFFFFFFFL) + + val hi_ret = decodeNonNegativeInteger32Neg(32) + val lo_ret = decodeNonNegativeInteger32Neg(nBits - 32) + + (hi_ret, lo_ret) match + case (Some(hi), Some(lo)) => + var v: ULong = hi & 0xFFFFFFFFL + v = v << nBits - 32L + v |= lo & 0xFFFFFFFFL + return Some(v) + case _ => return None() + //else + // return decodeNonNegativeInteger32Neg(v, nBits) + } + + def encodeNonNegativeIntegerNeg(v: ULong, negate: Boolean): Unit = { + if v >>> 32 == 0 then + encodeNonNegativeInteger32Neg(v.toInt, negate) + else + // TODO: Check Int/Long + val hi = (v >>> 32).toInt + var lo = v.toInt + encodeNonNegativeInteger32Neg(hi, negate) + + /*bug !!!!*/ + if negate then + lo = ~lo + val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) + bitStream.appendNBitZero(32 - nBits) + encodeNonNegativeInteger32Neg(lo, false) + } + + def BitStream_EncodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { + require(min <= max) + require(min <= v && v <= max) + + val range = max - min + if range == 0 then + return + + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) + bitStream.appendNBitZero(nRangeBits - nBits); + encodeNonNegativeInteger((v - min)) + } + + def BitStream_EncodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) + require(min <= v && v <= max) + + val range: ULong = (max - min) + if range == 0 then + return + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) + bitStream.appendNBitZero(nRangeBits - nBits) + encodeNonNegativeInteger(v - min) + } + + def BitStream_DecodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { + + val range: ULong = (max - min) + + // ASSERT_OR_RETURN_FALSE(min <= max); + + if range == 0 then + return Some(min) + + val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) + + decodeNonNegativeInteger(nRangeBits) match + case None() => return None() + case Some(ul) => return Some(ul + min) + } + + def BitStream_DecodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + + BitStream_DecodeConstraintWholeNumber(min.toLong, max.toLong) match + case None() => None() + case Some(l) => Some(l.toByte) + } + + def BitStream_DecodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { + + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(l) => Some(l.toShort) + } + + def BitStream_DecodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { + + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(l) => Some(l.toInt) + } + + def BitStream_DecodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toByte) + } + + def BitStream_DecodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toShort) + } + + def BitStream_DecodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toInt) + } + + def BitStream_DecodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) + + val range: ULong = max - min + + if range == 0 then + return Some(min) + + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + + decodeNonNegativeInteger(nRangeBits) match + case None() => None() + case Some(uv) => Some(uv + min) + } + + def BitStream_EncodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { + assert(v >= min) + val nBytes: Int = GetLengthInBytesOfUInt((v - min)) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + /* put required zeros*/ + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) + /*Encode number */ + encodeNonNegativeInteger((v - min)) + } + + def BitStream_EncodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { + assert(v >= min) + val nBytes: Int = GetLengthInBytesOfUInt(v - min) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + /* put required zeros*/ + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) + /*Encode number */ + encodeNonNegativeInteger(v - min) + } + + def BitStream_DecodeSemiConstraintWholeNumber(min: Long): Option[Long] = { + + var nBytes: Long = 0 + var v: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + + v += min + + return Some(v) + } + + def BitStream_DecodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { + + var nBytes: Long = 0 + var v: ULong = 0 + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + v += min + return Some(v) + } + + def BitStream_EncodeUnConstraintWholeNumber(v: Long): Unit = { + val nBytes: Int = GetLengthInBytesOfSInt(v) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + + if v >= 0 then + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) + encodeNonNegativeInteger(v) + else + bitStream.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) + encodeNonNegativeIntegerNeg((-v - 1), true) + } + + + def BitStream_DecodeUnConstraintWholeNumber(): Option[Long] = { + + var nBytes: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + val valIsNegative: Boolean = bitStream.peekBit() + + var v: Long = if valIsNegative then Long.MaxValue else 0 + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + + return Some(v) + } + + @extern + def BitStream_EncodeReal(vVal: Double): Unit = { + BitStream_EncodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) + } + + private def BitStream_EncodeRealBitString(vVal: Long): Unit = { + // according to T-REC-X.690 2021 + + var v = vVal + + // 8.5.2 Plus Zero + if v == DoublePosZeroBitString then + BitStream_EncodeConstraintWholeNumber(0, 0, 0xFF) + return; + + // 8.5.3 Minus Zero + if v == DoubleNegZeroBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x43, 0, 0xFF) + return; + + // 8.5.9 SpecialRealValues (2021 standard) + if (v & ExpoBitMask) == ExpoBitMask then + + // 8.5.9 PLUS-INFINITY + if v == DoublePosInfBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x40, 0, 0xFF) + return; + + // 8.5.9 MINUS-INFINITY + else if v == DoubleNegInfBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x41, 0, 0xFF) + return; + + // 8.5.9 NOT-A-NUMBER + else + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x42, 0, 0xFF) + return; + + // 8.5.6 a) + // fixed encoding style to binary + // 8.5.7.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 + // 8.5.7.3 F value is always zero - bit 0x08 and 0x04 are always 0 + var header = 0x80 + + // 8.5.7.1 + if ((v & SignBitMask) == SignBitMask) { // check sign bit + header |= 0x40 + v &= InverseSignBitMask // clear sign bit + } + + val (exponent, mantissa) = CalculateMantissaAndExponent(v) + + val nManLen: Int = GetLengthInBytesOfUInt(mantissa) + assert(nManLen <= 7) // 52 bit + + val compactExp = RemoveLeadingFFBytesIfNegative(exponent) + val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) + assert(nExpLen >= 1 && nExpLen <= 2) + + // 8.5.7.4 + if nExpLen == 2 then + header |= 0x01 + else if nExpLen == 3 then // this will never happen with this implementation + header |= 0x02 + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) + + /* encode header */ + BitStream_EncodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) + + /* encode exponent */ + if exponent >= 0 then + // fill with zeros to have a whole byte + bitStream.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) + encodeNonNegativeInteger(exponent) + else + encodeNonNegativeInteger(compactExp) + + /* encode mantissa */ + bitStream.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) + encodeNonNegativeInteger(mantissa) + } + + @extern + def BitStream_DecodeReal(): Option[Double] = { + BitStream_DecodeRealBitString() match + case None() => + None() + case Some(ll) => + Some(java.lang.Double.longBitsToDouble(ll)) + } + + private def BitStream_DecodeRealBitString(): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(length) => + // 8.5.2 Plus Zero + if length == 0 then + return Some(0) + + // invalid state + if length < 0 || length > DoubleMaxLengthOfSentBytes then + return None() + + bitStream.readByte() match + case None() => None() + case Some(header) => + // 8.5.6 a) + if (header.unsignedToInt & 0x80) != 0x80 then + return None() + + // 8.5.9 PLUS-INFINITY + if header == 0x40 then + Some(DoublePosInfBitString) + + // 8.5.9 MINUS-INFINITY + else if header == 0x41 then + Some(DoubleNegInfBitString) + + // 8.5.9 NOT-A-NUMBER + else if header == 0x42 then + Some(DoubleNotANumber) + + // 8.5.3 Minus Zero + else if header == 0x43 then + Some(DoubleNegZeroBitString) + + // Decode 8.5.7 + else + DecodeRealAsBinaryEncoding(length.toInt - 1, header) + } + + private def DecodeRealAsBinaryEncoding(lengthVal: Int, header: UByte): Option[Long] = { + require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte + require((header.unsignedToInt & 0x80) == 0x80) + require(bitStream.buf.length > lengthVal) + require(bitStream.currentByte < bitStream.buf.length - lengthVal) + + // 8.5.7.2 Base + val expFactor: Int = header.unsignedToInt match + case x if (x & 0x10) > 0 => 3 // 2^3 = 8 + case x if (x & 0x20) > 0 => 4 // 2^4 = 16 + case _ => 1 // 2^1 = 2 + + // 8.5.7.3 Factor F + val factor = 1 << ((header & 0x0C) >>> 2) + + // 8.5.7.4 Length of Exponent + val expLen = (header & 0x03) + 1 + + // sanity check + if expLen > lengthVal then + return None() + + // decode exponent + val expIsNegative = bitStream.peekBit() + var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 + + var i: Int = 0 + (while i < expLen do + decreases(expLen - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) + + i += 1 + ).invariant(i >= 0 && i <= expLen) + + // decode mantissa + val length = lengthVal - expLen + var N: ULong = 0 + var j: Int = 0 + (while j < length do + decreases(length - j) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) + + j += 1 + ).invariant(j >= 0 && j <= length) + + var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) + + // 8.5.7.1 Set Sign bit + if (header & 0x40) > 0 then + v |= SignBitMask + + Some(v) + } + + def BitStream_checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { + var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal + val tmp_currentByte: Int = bitStream.currentByte + val tmp_currentBit: Int = bitStream.currentBit + var tmp_byte: UByte = 0 + + if bitStream.currentByte.toLong * 8 + bitStream.currentBit + bit_terminated_pattern_size_in_bits.toInt > bitStream.buf.length.toLong * 8 then + return 0 + + var i: Int = 0 + while bit_terminated_pattern_size_in_bits >= 8 do + decreases(bit_terminated_pattern_size_in_bits) + + bitStream.readByte() match + case None() => return 0 + case Some(ub) => tmp_byte = ub + + bit_terminated_pattern_size_in_bits = 8 + if bit_terminated_pattern(i) != tmp_byte then + bitStream.currentByte = tmp_currentByte + bitStream.currentBit = tmp_currentBit + return 1 + i += 1 + + if bit_terminated_pattern_size_in_bits > 0 then + bitStream.readPartialByte(bit_terminated_pattern_size_in_bits) match + case None() => return 0 + case Some(ub) => tmp_byte = ub + + tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte + + if bit_terminated_pattern(i) != tmp_byte then + bitStream.currentByte = tmp_currentByte + bitStream.currentBit = tmp_currentBit + return 1 + + return 2 + } + + def BitStream_ReadBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { + var checkBitPatternPresentResult: Int = 0 + + var bitsRead: Int = 0 + + val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) + + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do + decreases(nMaxReadBits - bitsRead) + bitStream.readBit() match + case None() => return NoneMut() + case Some(bitVal) => + tmpStrm.appendBit(bitVal) + bitsRead += 1 + + if bitsRead < nMaxReadBits then + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + if checkBitPatternPresentResult != 2 then + return NoneMut() + + return SomeMut((tmpStrm.buf, bitsRead)) + } + + def BitStream_EncodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { + val cb = bitStream.currentBit + var ret: Boolean = false + + if cb == 0 then + ret = bitStream.currentByte + nCount <= bitStream.buf.length + if ret then + copyToArray(arr, bitStream.buf, bitStream.currentByte, nCount) + bitStream.currentByte += nCount + + else + ret = bitStream.appendByteArray(arr, nCount) + + ret + } + + def BitStream_DecodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { + val cb: Int = bitStream.currentBit + val arr: Array[UByte] = Array.fill(nCount + 1)(0) + + if cb == 0 then + if bitStream.currentByte + nCount > bitStream.buf.length then + return NoneMut() + + arrayCopyOffset(bitStream.buf, arr, bitStream.currentByte, bitStream.currentByte + nCount, 0) + bitStream.currentByte += nCount + + else + bitStream.readByteArray(nCount) match + case NoneMut() => return NoneMut() + case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) + + SomeMut(arr) + } + + def BitStream_EncodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { + var nRemainingItemsVar1: Int = nCount + var nCurBlockSize1: Int = 0 + var nCurOffset1: Int = 0 + var ret: Boolean = nCount >= 0 + + while nRemainingItemsVar1 >= 0x4000 && ret do + decreases(nRemainingItemsVar1) + if nRemainingItemsVar1 >= 0x10000 then + nCurBlockSize1 = 0x10000 + BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + else if nRemainingItemsVar1 >= 0xC000 then + nCurBlockSize1 = 0xC000 + BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + else if nRemainingItemsVar1 >= 0x8000 then + nCurBlockSize1 = 0x8000 + BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + else + nCurBlockSize1 = 0x4000 + BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + + var i1: Int = nCurOffset1 + while i1 < nCurBlockSize1 + nCurOffset1 && ret do + decreases(nCurBlockSize1 + nCurOffset1 - i1) + ret = bitStream.appendByte0(arr(i1)) + i1 += 1 + + nCurOffset1 += nCurBlockSize1 + nRemainingItemsVar1 -= nCurBlockSize1 + + if ret then + if nRemainingItemsVar1 <= 0x7F then + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) + + + var i1: Int = nCurOffset1 + while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do + decreases(nCurOffset1 + nRemainingItemsVar1 - i1) + ret = bitStream.appendByte0(arr(i1)) + i1 += 1 + + return ret + } + + def BitStream_DecodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) + + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + var nCount: Int = 0 + + var nLengthTmp1: Long = 0 + var nRemainingItemsVar1: Long = 0 + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + + // get header data + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + // 11xx_xxxx header, there is a next fragment + while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + + // get current block size + if nRemainingItemsVar1 == 0xC4 then + nCurBlockSize1 = 0x10000 + else if nRemainingItemsVar1 == 0xC3 then + nCurBlockSize1 = 0xC000 + else if nRemainingItemsVar1 == 0xC2 then + nCurBlockSize1 = 0x8000 + else if nRemainingItemsVar1 == 0xC1 then + nCurBlockSize1 = 0x4000 + else + return NoneMut() + + // fill current payload fragment into dest + var i1: Int = nCurOffset1.toInt + while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do + decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) + bitStream.readByte() match + case None() => return NoneMut() + case Some(ub) => arr(i1) = ub + i1 += 1 + + // sum combined length + nLengthTmp1 += nCurBlockSize1 + // set offset for next run + nCurOffset1 += nCurBlockSize1 + + // get next header + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower + if (nRemainingItemsVar1 & 0x80) > 0 then + + nRemainingItemsVar1 <<= 8 // put upper at correct position + // get size (lower byte) + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => + nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size + nRemainingItemsVar1 &= 0x7FFF // clear the control bit + + if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then + var i1: Int = nCurOffset1.toInt + + // fill last payload fragment into dest + while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do + decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) + bitStream.readByte() match + case None() => return NoneMut() + case Some(ub) => arr(i1) = ub + i1 += 1 + + // add remainingSize to already written size - this var holds the absolut number in all fragments + nLengthTmp1 += nRemainingItemsVar1 + + // resize output array and copy data + if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then + val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) + arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) + return SomeMut(newArr) + else + return NoneMut() + + NoneMut() + } + + def BitStream_EncodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax + + if ret then + if asn1SizeMax < 65536 then + if asn1SizeMin != asn1SizeMax then + BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + ret = BitStream_EncodeOctetString_no_length(arr, nCount) + + else + ret = BitStream_EncodeOctetString_fragmentation(arr, nCount) + + return ret + } + + def BitStream_DecodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + + if asn1SizeMax < 65536 then + var nCount: Int = 0 + if asn1SizeMin != asn1SizeMax then + BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + case None() => return NoneMut() + case Some(l) => nCount = l.toInt + else + nCount = asn1SizeMin.toInt + + if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then + return BitStream_DecodeOctetString_no_length(nCount) + else + return NoneMut() + + else + return BitStream_DecodeOctetString_fragmentation(asn1SizeMax) + + } + + def BitStream_EncodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + if asn1SizeMax < 65536 then + if asn1SizeMin != asn1SizeMax then + BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + + bitStream.appendBits(arr, nCount) + + else + var nRemainingItemsVar1: Long = nCount.toLong + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + while nRemainingItemsVar1 >= 0x4000 do + decreases(nRemainingItemsVar1) + + if nRemainingItemsVar1 >= 0x10000 then + nCurBlockSize1 = 0x10000 + BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + + else if nRemainingItemsVar1 >= 0xC000 then + nCurBlockSize1 = 0xC000 + BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + else if nRemainingItemsVar1 >= 0x8000 then + nCurBlockSize1 = 0x8000 + BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + else + nCurBlockSize1 = 0x4000 + BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + + val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) + bitStream.appendBits(t, nCurBlockSize1.toInt) + nCurOffset1 += nCurBlockSize1 + nRemainingItemsVar1 -= nCurBlockSize1 + + + if nRemainingItemsVar1 <= 0x7F then + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) + + val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) + bitStream.appendBits(t, nRemainingItemsVar1.toInt) + + true + } + + def BitStream_DecodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax <= Int.MaxValue) + + if (asn1SizeMax < 65536) { + var nCount: Long = 0 + if asn1SizeMin != asn1SizeMax then + BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + case None() => return NoneMut() + case Some(l) => nCount = l + else + nCount = asn1SizeMin + + return bitStream.readBits(nCount.toInt) + + } else { + var nRemainingItemsVar1: Long = 0 + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + var nLengthTmp1: Long = 0 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + if nRemainingItemsVar1 == 0xC4 then + nCurBlockSize1 = 0x10000 + else if nRemainingItemsVar1 == 0xC3 then + nCurBlockSize1 = 0xC000 + else if nRemainingItemsVar1 == 0xC2 then + nCurBlockSize1 = 0x8000 + else if nRemainingItemsVar1 == 0xC1 then + nCurBlockSize1 = 0x4000 + else + return NoneMut() + + /*COVERAGE_IGNORE*/ + if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then + return NoneMut() + /*COVERAGE_IGNORE*/ + + bitStream.readBits(nCurBlockSize1.toInt) match + case NoneMut() => return NoneMut() + case SomeMut(t) => + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) + nLengthTmp1 += nCurBlockSize1 + nCurOffset1 += nCurBlockSize1 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + if (nRemainingItemsVar1 & 0x80) > 0 then + nRemainingItemsVar1 <<= 8 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => + nRemainingItemsVar1 |= l + nRemainingItemsVar1 &= 0x7FFF + + if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then + + bitStream.readBits(nRemainingItemsVar1.toInt) match + case NoneMut() => return NoneMut() + case SomeMut(t) => + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) + nLengthTmp1 += nRemainingItemsVar1 + if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then + return SomeMut(arr) + } + return NoneMut() + } +} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala new file mode 100644 index 000000000..b95b75fe1 --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -0,0 +1,1580 @@ +package asn1scala + +import stainless.lang.StaticChecks.assert +import stainless.lang.{None, Option, Some} + +val FAILED_READ_ERR_CODE = 5400 + +// TODO remove / replace by invariant +def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { + assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) +} + +/** + * Get an instance of a ACN coded bitstream + * @param count of elements in underlaying buffer + * @return ACN coded bitstream + */ +def initACNCodec(count: Int): ACN = { + ACN(BitStream(Array.fill(count)(0))) +} + +case class ACN(bitStream: BitStream) extends Codec { + + def alignToByte(): Unit = { + if bitStream.currentBit != 0 then + bitStream.currentBit = 0 + bitStream.currentByte += 1 + CHECK_BIT_STREAM(bitStream) + } + + def alignToShort(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + CHECK_BIT_STREAM(bitStream) + } + + def alignToInt(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + CHECK_BIT_STREAM(bitStream) + } + + /*ACN Integer functions*/ + def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { + if encodedSizeInBits == 0 then + return + + /* Get number of bits*/ + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) + /* put required zeros*/ + // TODO what if nBits > encodedSizeInBits ?? + bitStream.appendNBitZero(encodedSizeInBits - nBits) + /*Encode number */ + encodeNonNegativeInteger(intVal) + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { + bitStream.appendByte0(intVal.toByte) + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { + val tmp: ULong = intVal + var mask: ULong = 0xFF + mask <<= (size - 1) * 8 + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + mask >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_SHORT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_INT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal: ULong, size: Int): Unit = { + var tmp: ULong = intVal + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = tmp.toByte + bitStream.appendByte0(ByteToEncode) + tmp >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 2) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 4) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + + def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { + decodeNonNegativeInteger(encodedSizeInBits) match + case None() => None() + case Some(ul) => Some(ul) + } + + + def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(ub) => Some(ub & 0xFF) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + ret <<= 8 + ret |= (ub & 0xFF) + i += 1 + + Some(ret) + } + + // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly + def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + var tmp: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + tmp = ub & 0xFF + tmp <<= i * 8 + ret |= tmp + i += 1 + + Some(ret) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(2) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(4) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { + val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) + bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) + ret + } + + + def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { + val MAX_BYTE_MASK = 0xFF00000000000000L + assert(nBytes <= 8) + + var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 - nBytes * 8) + + var i: Int = 0 + while i < nBytes do + val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + vv <<= 8 + i += 1 + } + + + def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte + + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(intVal, nBytes) + + CHECK_BIT_STREAM(bitStream) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { + var v: ULong = 0 + + bitStream.readByte() match + case None() => return None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + v = (v << 8) | (ub & 0xFF) + i += 1 + + Some(v) + } + + + def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { + if intVal >= 0 then + bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) + encodeNonNegativeInteger(intVal) + + else + bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) + encodeNonNegativeIntegerNeg(-intVal - 1, true) + + CHECK_BIT_STREAM(bitStream) + } + + + def enc_Int_TwosComplement_ConstSize_8(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_8(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_16(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_32(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_64(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_16(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_32(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) + } + + def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { + val valIsNegative: Boolean = bitStream.peekBit() + val nBytes: Int = encodedSizeInBits / 8 + val rstBits: Int = encodedSizeInBits % 8 + + var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 + + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << 8) | (ub & 0xFF) + i += 1 + + if rstBits > 0 then + bitStream.readPartialByte(rstBits.toByte) match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << rstBits) | (ub & 0xFF) + + Some(pIntVal) + } + + + def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 1)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + + def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { + val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte + + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(int2uint(intVal), nBytes) + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { + var v: ULong = 0 + var isNegative: Boolean = false + + bitStream.readByte() match + case None() => None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + if i == 0 && (ub & 0x80) > 0 then + v = Long.MaxValue + isNegative = true + + v = (v << 8) | (ub & 0xFF) + i += 1 + + if isNegative then + Some(-(~v) - 1) + else + Some(v) + } + + + //return values is in nibbles + def get_Int_Size_BCD(intVal: ULong): Int = { + var intVar = intVal + var ret: Int = 0 + while intVar > 0 do + intVar /= 10 + ret += 1 + + ret + } + + + def enc_Int_BCD_ConstSize(intVal: ULong, encodedSizeInNibbles: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) + + assert(100 >= encodedSizeInNibbles) + + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 + + assert(encodedSizeInNibbles >= totalNibbles) + + var i: Int = encodedSizeInNibbles - 1 + while i >= 0 do + bitStream.appendPartialByte(tmp(i).toByte, 4, false) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { + var ret: ULong = 0 + + var encodedSizeInNibblesVar = encodedSizeInNibbles + while encodedSizeInNibblesVar > 0 do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + ret *= 10 + ret += digit + encodedSizeInNibblesVar -= 1 + + Some(ret) + } + + + def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nNibbles: Int = get_Int_Size_BCD(intVal) + /* encode length */ + bitStream.appendByte0(nNibbles.toByte) + + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) + } + + + //encoding puts an 'F' at the end + def enc_Int_BCD_VarSize_NullTerminated(intVal: ULong): Unit = { + + val nNibbles: Int = get_Int_Size_BCD(intVal) + + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) + + bitStream.appendPartialByte(0xF, 4, false) + + CHECK_BIT_STREAM(bitStream) + } + + def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { + var ret: ULong = 0 + + while true do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + if (digit > 9) + return Some(ret) + + ret *= 10 + ret += digit + + Some(ret) + } + + + def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) + + assert(100 >= encodedSizeInBytes) + + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 + + assert(encodedSizeInBytes >= totalNibbles) + + var i = encodedSizeInBytes - 1 + while i >= 0 do + bitStream.appendByte0((tmp(i) + '0').toByte) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def enc_SInt_ASCII_ConstSize(intVal: Long, encodedSizeInBytes: Int): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) + } + + def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { + var encodedSizeInBytesVar = encodedSizeInBytes + var ret: ULong = 0 + + while encodedSizeInBytesVar > 0 do + bitStream.readByte() match + case None() => return None() + case Some(digit) => + assert(digit >= '0' && digit <= '9') + + ret *= 10 + ret += (digit.toInt - '0').toByte + + encodedSizeInBytesVar -= 1 + + Some(ret) + } + + def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(digit) => + var sign: Int = 1 + if digit == '+' then + sign = 1 + else if digit == '-' then + sign = -1 + else + assert(false) + + dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match + case None() => None() + case Some(ul) => Some(sign * ul) + } + + + def getIntegerDigits(intVal: ULong): (Array[Byte], Byte) = { + var intVar = intVal + val digitsArray100: Array[Byte] = Array.fill(100)(0) + val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) + var totalDigits: Byte = 0 + + + if intVar > 0 then + while intVar > 0 && totalDigits < 100 do + reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte + totalDigits = (totalDigits + 1).toByte + intVar /= 10 + + var i: Int = totalDigits - 1 + while i >= 0 do + digitsArray100(totalDigits - 1 - i) = reversedDigitsArray(i) + i -= 1 + + else + digitsArray100(0) = '0' + totalDigits = 1 + + (digitsArray100, totalDigits) + } + + + def enc_SInt_ASCII_VarSize_LengthEmbedded(intVal: Long): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + val (digitsArray100, nChars) = getIntegerDigits(absIntVal) + + /* encode length, plus 1 for sign */ + bitStream.appendByte0((nChars + 1).toByte) + + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) + + /* encode length */ + bitStream.appendByte0(nChars) + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) + } + + def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) + } + + + def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) + + var i: Int = 0 // TODO: size_t? + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + i = 0 + while i < null_characters_size do + bitStream.appendByte0(null_characters(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val absValue: ULong = if intVal >= 0 then intVal else -intVal + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) + } + + def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { + var digit: Byte = 0 + var ret: ULong = 0 + val tmp: Array[Byte] = Array.fill(10)(0) + + val sz: Int = if null_characters_size < 10 then null_characters_size else 10 + + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_characters_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 + + var i: Long = 0 + while !null_characters.sameElements(tmp) do + digit = tmp(0) + i += 1 + + j = 0 + while j < null_characters_size - 1 do + tmp(j) = tmp(j + 1) + j += 1 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_characters_size - 1) = ub + + digit = (digit - '0').toByte + + ret *= 10 + ret += digit + + Some(ret) + } + + + def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { + var isNegative: Boolean = false + + bitStream.readByte() match + case None() => None() + case Some(digit) => + assert(digit == '-' || digit == '+') + if digit == '-' then + isNegative = true + + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(ul) => Some(if isNegative then -ul else ul) + } + + + /* Boolean Decode */ + // TODO move to codec? + def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var pBoolValue: Boolean = true + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return None() + case Some(curByte) => + if curByte != patternToRead(i) then + pBoolValue = false + i += 1 + + if nRemainingBitsToRead > 0 then + bitStream.readPartialByte(nRemainingBitsToRead.toByte) match + case None() => return None() + case Some(curByte) => + if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then + pBoolValue = false + + Some(pBoolValue) + } + + // TODO move to codec? + def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return Left(FAILED_READ_ERR_CODE) + case Some(_) => i += 1 + + if nRemainingBitsToRead > 0 then + if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then + return Left(FAILED_READ_ERR_CODE) + + Right(0) + } + + + /*Real encoding functions*/ + def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array + + var i: Int = 0 + while i < 4 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_32_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1).toDouble) + } + + def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + + def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 0 + while i < 8 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_64_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 0 + while i < 8 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array + + var i: Int = 3 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_32_little_endian(): Option[Double] = { + dec_Real_IEEE754_32_little_endian_fp32() match + case None() => None() + case Some(f) => Some(f.toDouble) + } + + def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 3 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 7 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_64_little_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 7 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + /* String functions*/ + def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { + var i: Long = 0 + while i < max do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + } + + def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { + var i: Long = 0 + while (i < max) && (strVal(i.toInt) != '\u0000') do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + + i + } + + def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + bitStream.appendByte(null_character.toByte, false) + } + + def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + var i: Int = 0 + while i < null_character_size do + bitStream.appendByte(null_character(i), false) + i += 1 + } + + + def enc_String_Ascii_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + } + + def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_Ascii_private(max, strVal) + } + + def enc_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + var i: Int = 0 + while i < max do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + } + + def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { + var i: Int = 0 + while (i < max) && (strVal(i) != '\u0000') do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + + i + } + + + def enc_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def enc_IA5String_CharIndex_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + strVal(i) = decodedCharacter + i += 1 + Some(strVal) + } + + + def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, max) + } + + def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i <= max do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + if decodedCharacter != null_character then + strVal(i) = decodedCharacter + i += 1 + else + strVal(i) = 0x0 + return Some(strVal) + + None() + + } + + def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { + val sz: Int = if null_character_size < 10 then null_character_size else 10 + val tmp: Array[Byte] = Array.fill(10)(0) + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_character_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 + + + var i: Int = 0 + while i <= max && !null_character.sameElements(tmp) do + strVal(i) = tmp(0) + i += 1 + j = 0 + while j < null_character_size - 1 do + tmp(j) = tmp(j + 1) + j += 1 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_character_size - 1) = ub + + strVal(i) = 0x0 + + if !null_character.sameElements(tmp) then + return None() + + Some(strVal) + } + + + def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) + } + + def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_Ascii_private(max, if nCount <= max then nCount else max) + } + + def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match + case None() => return None() + case Some(charIndex) => + strVal(i) = allowedCharSet(charIndex.toInt) + i += 1 + + Some(strVal) + } + + def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, max, allowedCharSet) + } + + def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + + def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + /* Length Determinant functions*/ + def enc_Length(lengthValue: ULong, lengthSizeInBits: Int): Unit = { + /* encode length */ + enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) + } + + def dec_Length(lengthSizeInBits: Int): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) + } + + def milbus_encode(v: Long): Long = { + if v == 32 then 0 else v + } + + def milbus_decode(v: Long): Long = { + if v == 0 then 32 else v + } + + def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } +} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala new file mode 100644 index 000000000..8a497030c --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala @@ -0,0 +1,13 @@ +package asn1scala + + +/** + * Get an instance of a PER coded bitstream + * @param count of elements in underlaying buffer + * @return PER coded bitstream + */ +def initPERCodec(count: Int): PER = { + PER(BitStream(Array.fill(count)(0))) +} + +case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala new file mode 100644 index 000000000..1683265dd --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -0,0 +1,199 @@ +package asn1scala + +import stainless.math.BitVectors._ +import stainless.lang.{None => None, Option => Option, Some => Some, _} + +/** + * Get an instance of a UPER coded bitstream + * @param count of elements in underlaying buffer + * @return UPER coded bitstream + */ +def initUPERCodec(count: Int): UPER = { + UPER(BitStream(Array.fill(count)(0))) +} + +case class UPER(bitStream: BitStream) extends Codec { + + def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { + var lastOctet: Boolean = false + val tmp: Array[UByte] = Array.fill(16)(0) + var nSize: Int = 0 + + var siValue = siValueVal + var pSize = pSizeVal + + while !lastOctet do + decreases(siValue) + val curByte: UByte = (siValue % 128).toByte + siValue = siValue / 128 + lastOctet = siValue.toInt == 0 + tmp(nSize) = curByte + nSize += 1 + + var i: Int = 0 + while i < nSize do + decreases(nSize - i) + val curByte: UByte = if i == nSize - 1 then tmp(nSize - i - 1) else (tmp(nSize - i - 1) | 0x80).toByte + encodingBuf(pSize) = curByte + pSize += 1 + i += 1 + return pSize + } + + def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) + + i = 0 + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def relativeOID_encode(pVal: Asn1ObjectIdentifier): Unit = { + //a subIdentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded + //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { + var bLastOctet: Boolean = false + var curOctetValue: ULong = 0 + var siValue: ULong = 0 + var pRemainingOctets: Long = pRemainingOctetsVal + while pRemainingOctets > 0 && !bLastOctet do + decreases(pRemainingOctets) + bitStream.readByte() match + case None() => return None() + case Some(curByte) => + pRemainingOctets -= 1 + + bLastOctet = (curByte & 0x80) == 0 + curOctetValue = (curByte & 0x7F).toLong + siValue = siValue << 7 + siValue |= curOctetValue + + return Some((pRemainingOctets, siValue)) + } + + + def objectIdentifier_decode_length(): Option[Long] = { + var totalSize: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => totalSize = l + + if totalSize > 0x7F then + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => + totalSize <<= 8 + totalSize |= l + totalSize &= 0x7FFF + + return Some(totalSize) + } + + def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + + val pVal = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + + pVal.nCount = 2 + pVal.values(0) = si / 40 + pVal.values(1) = si % 40 + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + + } + + def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + } +} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala new file mode 100644 index 000000000..aee7187ad --- /dev/null +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -0,0 +1,196 @@ +package asn1scala + +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +// all bits of the integer +val MASK_BYTE = 0xFF +val MASK_BYTE_L = 0xFFL +val MASK_SHORT_L = 0xFF_FFL +val MASK_INT_L = 0xFF_FF_FF_FFL + +// MSBs (neg bits of the integer) +val MASK_MSB_BYTE = 0x80L +val MASK_MSB_INT = 0x80_00_00_00L + +// pos bits of the integer +val MASK_POS_BYTE = 0x7FL +val MASK_POS_INT = 0x7F_FF_FF_FFL + +/* +* Meths to upcast unsigned integer data types on the JVM +*/ +extension (ub: UByte) { + def unsignedToLong: Long = ub & MASK_BYTE_L + def unsignedToInt: Int = ub.toInt & MASK_BYTE +} + +extension (us: UShort) { + def unsignedToLong: Long = us & MASK_SHORT_L +} + +extension (ui: UInt) { + def unsignedToLong: Long = ui & MASK_INT_L +} + +extension (i: Int) { + def toUnsignedByte: UByte = { + require(i >= 0 && i <= MASK_BYTE) + + if(i == MASK_MSB_BYTE) + (-MASK_MSB_BYTE).toByte + else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) + ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte + else + i.toByte + } +} + +extension (l: Long) { + def toUnsignedInt: UInt = { + require(l >= 0 && l <= MASK_INT_L) + + if(l == MASK_MSB_INT) + (-MASK_MSB_INT).toInt + else if ((l & MASK_MSB_INT) == MASK_MSB_INT) + ((l & MASK_POS_INT) - MASK_MSB_INT).toInt + else + l.toInt + } +} + +extension (b: Byte) { + def >>>>(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte + } + + def <<<<(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt << i) & MASK_BYTE).toUnsignedByte + } +} + + +def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { + if v >>> 8 == 0 then + (v, 0) + else if v >>> 16 == 0 then + (v >>> 8, 8) + else if v >>> 24 == 0 then + (v >>> 16, 16) + else + (v >>> 24, 24) +}.ensuring((v, n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24) + +def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { + require(vVal >= 0 && vVal <= 0xFF) + require(n >= 0 && n <= 8) + require(1<<(8-n) > vVal) + decreases(8-n) + + if(vVal == 0) then + n + else + GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) +} + +def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { + val (v, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) + n + GetNumberOfBitsInLastByteRec(v, 0) +} + +def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { + if v >>> 32 == 0 then + GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) + else + val h = (v >>> 32).toUnsignedInt + 32 + GetNumberOfBitsForNonNegativeInteger32(h) +}.ensuring(n => n >= 0 && n <= 64) + +def GetLengthInBytesOfUInt (v: ULong): Int = { + GetLengthInBytesOfSInt(v) // just call signed, is signed anyway +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) + +def GetLengthInBytesOfSInt (v: Long): Int = { + max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) + +/** +Binary encoding will be used +REAL = M*B^E +where +M = S*N*2^F + +ENCODING is done within three parts +part 1 is 1 byte header +part 2 is 1 or more byte for exponent +part 3 is 3 or more byte for mantissa (N) + +First byte +S :0-->+, S:1-->-1 +Base will be always be 2 (implied by 6th and 5th bit which are zero) +ab: F (0..3) +cd:00 --> 1 byte for exponent as 2's complement +cd:01 --> 2 byte for exponent as 2's complement +cd:10 --> 3 byte for exponent as 2's complement +cd:11 --> 1 byte for encoding the length of the exponent, then the exponent + +8 7 6 5 4 3 2 1 ++-+-+-+-+-+-+-+-+ +|1|S|0|0|a|b|c|d| ++-+-+-+-+-+-+-+-+ + **/ + +def CalculateMantissaAndExponent(doubleAsLong64: Long): (UInt, ULong) = { + require({ + val rawExp = (doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits + rawExp >= 0 &&& rawExp <= ((1 << 11) - 2) // 2046, 2047 is the infinity case - never end up here with infinity + }) + + val exponent: UInt = ((doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt + var mantissa: ULong = doubleAsLong64 & MantissaBitMask + mantissa = mantissa | MantissaExtraBit + + (exponent, mantissa) + +}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) + &&& m >= 0 &&& m <= MantissaBitMask) + +def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { + ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) +} + +/** +Helper function for REAL encoding + +Negative Ints always need 4 bytes of space, the ASN.1 standard compacts those numbers down +to 8, 16 or 24 bits depending on the leading bytes full of 1s. + +Example: +-4 in Int: 0b1111_..._1111_1100 +--> compacted to 0b1111_1100 + +The ASN.1 header holds the detail on how to interpret this number + **/ +def RemoveLeadingFFBytesIfNegative(v: Int): Int = { + if v >= 0 then + v + else if v >= Byte.MinValue then + v & 0xFF + else if v >= Short.MinValue then + v & 0xFF_FF + else if v >= -8_388_608 then + v & 0xFF_FF_FF + else + v +} + +sealed trait OptionMut[@mutable A] +case class NoneMut[@mutable A]() extends OptionMut[A] +case class SomeMut[@mutable A](v: A) extends OptionMut[A] diff --git a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala similarity index 95% rename from asn1scala/src/main/scala/asn1scala/stainless_utils.scala rename to asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala index 94f99ee4d..6d232572d 100644 --- a/asn1scala/src/main/scala/asn1scala/stainless_utils.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala @@ -191,7 +191,3 @@ def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int } rec(from) }.ensuring(_ => arrayPrefix(a1, a3, from, mid)) - -sealed trait OptionMut[@mutable A] -case class NoneMut[@mutable A]() extends OptionMut[A] -case class SomeMut[@mutable A](v: A) extends OptionMut[A] diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala deleted file mode 100644 index 44fb27b0e..000000000 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding.scala +++ /dev/null @@ -1,1147 +0,0 @@ -package asn1scala - -import stainless.* -import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} -import stainless.collection.* -import stainless.annotation.* -import stainless.proof.* -import stainless.math.* -import StaticChecks.* - -// TODO move to Bitstream if only used there -val masksb: Array[UByte] = Array( - 0x00, // 0 / 0000 0000 / x00 - 0x01, // 1 / 0000 0001 / x01 - 0x03, // 3 / 0000 0011 / x03 - 0x07, // 7 / 0000 0111 / x07 - 0x0F, // 15 / 0000 1111 / x0F - 0x1F, // 31 / 0001 1111 / x1F - 0x3F, // 63 / 0011 1111 / x3F - 0x7F, // 127 / 0111 1111 / x7F - -0x1, // -1 / 1111 1111 / xFF -) - -val masks2: Array[UInt] = Array( - 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 - 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF - 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000 FF00 - 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF 0000 - 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 -) - - -/***********************************************************************************************/ -/** Byte Stream Functions **/ -/***********************************************************************************************/ -def ByteStream_Init(count: Int): ByteStream = { - ByteStream(Array.fill(count)(0), 0, false) -} - -@extern -def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { - pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... - pStrm.currentByte = 0 -}.ensuring(_ => pStrm.buf == buf && pStrm.currentByte == 0 && pStrm.EncodeWhiteSpace == old(pStrm).EncodeWhiteSpace) - -def ByteStream_GetLength(pStrm: ByteStream): Int = { - pStrm.currentByte -} - -/***********************************************************************************************/ -/** Bit Stream Functions **/ -/***********************************************************************************************/ -def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { - arraySameElements(arr1, arr2) - //return - // (nBitsLength1 == nBitsLength2) && - // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && - // (nBitsLength1 % 8 > 0 ? (arr1[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8) == arr2[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8)): TRUE); -} - - -def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), 0, 0) -} - -/** -Append bit one. - -Example - cur bit = 3 - x x x | - |_|_|_|_|_|_|_|_| - 0 1 2 3 4 5 6 7 - - xxxy???? -or 00010000 -------------- - xxx1???? -**/ - - - - -/***********************************************************************************************/ -/***********************************************************************************************/ -/***********************************************************************************************/ -/***********************************************************************************************/ -/** Integer Functions **/ -/***********************************************************************************************/ -/***********************************************************************************************/ -/***********************************************************************************************/ -/***********************************************************************************************/ -def BitStream_EncodeNonNegativeInteger32Neg(pBitStrm: BitStream, v: Int, negate: Boolean): Unit = { - var cc: UInt = 0 - var curMask: UInt = 0 - var pbits: UInt = 0 - - if v == 0 then - return () - - if v >>> 8 == 0 then - cc = 8 - curMask = 0x80 - else if v >>> 16 == 0 then - cc = 16 - curMask = 0x8000 - else if v >>> 24 == 0 then - cc = 24 - curMask = 0x800000 - else - cc = 32 - curMask = 0x80000000 - - while (v & curMask) == 0 do - decreases(cc) - curMask >>>= 1 - cc -= 1 - - pbits = cc % 8 - if pbits > 0 then - cc -= pbits - pBitStrm.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) - - while cc > 0 do - decreases(cc) - val t1: UInt = v.toInt & masks2(cc >>> 3) - cc -= 8 - pBitStrm.appendByte((t1 >>> cc).toByte, negate) -} -def BitStream_DecodeNonNegativeInteger32Neg(pBitStrm: BitStream, nBitsVal: Int): Option[UInt] = { - - var v: UInt = 0 - - var nBits = nBitsVal - while nBits >= 8 do - decreases(nBits) - v = v << 8 - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) - // will be casted to an Int -1 (1111 ... 1111) - v = v | (ub & 0xFF) - - nBits -= 8 - - if nBits != 0 then - v = v << nBits - pBitStrm.readPartialByte(nBits.toByte) match - case None() => return None() - case Some(ub) => v = v | (ub & 0xFF) - - Some(v) -} -def BitStream_EncodeNonNegativeInteger(pBitStrm: BitStream, v: ULong): Unit = { - // TODO: support WORD_SIZE=4? - //if WORD_SIZE == 8 then - if v >>> 32 == 0 then - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v.toInt, false) - else - // TODO: Check Int/Long - val hi = (v >>> 32).toInt - val lo = v.toInt - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, hi, false) - - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? - pBitStrm.appendNBitZero(32 - nBits) - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, lo, false) - //else - // BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v.toInt, false) -} - -def BitStream_DecodeNonNegativeInteger(pBitStrm: BitStream, nBits: Int): Option[ULong] = { - // TODO: support WORD_SIZE=4? - // if WORD_SIZE == 8 then - if nBits <= 32 then - BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, nBits) match - case None() => return None() - case Some(lo) => - return Some(lo & 0xFFFFFFFFL) - - val hi_ret = BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, 32) - val lo_ret = BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, nBits - 32) - - (hi_ret, lo_ret) match - case (Some(hi), Some(lo)) => - var v: ULong = hi & 0xFFFFFFFFL - v = v << nBits - 32L - v |= lo & 0xFFFFFFFFL - return Some(v) - case _ => return None() - //else - // return BitStream_DecodeNonNegativeInteger32Neg(pBitStrm, v, nBits) -} - -def BitStream_EncodeNonNegativeIntegerNeg(pBitStrm: BitStream, v: ULong, negate: Boolean): Unit = { - //if WORD_SIZE == 8 then - if v >>> 32 == 0 then - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v.toInt, negate) - else - // TODO: Check Int/Long - val hi = (v >>> 32).toInt - var lo = v.toInt - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, hi, negate) - - /*bug !!!!*/ - if negate then - lo = ~lo - val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) - pBitStrm.appendNBitZero( 32 - nBits) - BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, lo, false) - //else - // BitStream_EncodeNonNegativeInteger32Neg(pBitStrm, v, negate) - -} - -def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { - if v >>> 8 == 0 then - (v, 0) - else if v >>> 16 == 0 then - (v >>> 8, 8) - else if v >>> 24 == 0 then - (v >>> 16, 16) - else - (v >>> 24, 24) -}.ensuring((v, n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24) - -def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { - require(vVal >= 0 && vVal <= 0xFF) - require(n >= 0 && n <= 8) - require(1<<(8-n) > vVal) - decreases(8-n) - - if(vVal == 0) then - n - else - GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) -} - -def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { - val (v, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) - n + GetNumberOfBitsInLastByteRec(v, 0) -} - -def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { - if v >>> 32 == 0 then - GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) - else - val h = (v >>> 32).toUnsignedInt - 32 + GetNumberOfBitsForNonNegativeInteger32(h) -}.ensuring(n => n >= 0 && n <= 64) - -def GetLengthInBytesOfUInt (v: ULong): Int = { - GetLengthInBytesOfSInt(v) // just call signed, is signed anyway -}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) - -def GetLengthInBytesOfSInt (v: Long): Int = { - max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte -}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) - -def BitStream_EncodeConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long, max: Long): Unit = { - require(min <= max) - require(min <= v && v <= max) - - val range = max - min - if range == 0 then - return - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) - pBitStrm.appendNBitZero(nRangeBits - nBits); - BitStream_EncodeNonNegativeInteger(pBitStrm, (v - min)) -} - - -def BitStream_EncodeConstraintPosWholeNumber(pBitStrm: BitStream, v: ULong, min: ULong, max: ULong): Unit = { - require(max >= 0 && max <= Long.MaxValue) - require(min >= 0 && min <= max) - require(min <= v && v <= max) - - val range: ULong = (max - min) - if range == 0 then - return - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - pBitStrm.appendNBitZero(nRangeBits - nBits) - BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) -} - -def BitStream_DecodeConstraintWholeNumber(pBitStrm: BitStream, min: Long, max: Long): Option[Long] = { - - val range: ULong = (max - min) - -// ASSERT_OR_RETURN_FALSE(min <= max); - - if range == 0 then - return Some(min) - - val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) - - BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None() => return None() - case Some(ul) => return Some(ul + min) -} - - -def BitStream_DecodeConstraintWholeNumberByte(pBitStrm: BitStream, min: Byte, max: Byte): Option[Byte] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.toLong, max.toLong) match - case None() => None() - case Some(l) => Some(l.toByte) -} - - -def BitStream_DecodeConstraintWholeNumberShort(pBitStrm: BitStream, min: Short, max: Short): Option[Short] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None() => None() - case Some(l) => Some(l.toShort) -} - - -def BitStream_DecodeConstraintWholeNumberInt(pBitStrm: BitStream, min: Int, max: Int): Option[Int] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None() => None() - case Some(l) => Some(l.toInt) -} - - -def BitStream_DecodeConstraintWholeNumberUByte(pBitStrm: BitStream, min: UByte, max: UByte): Option[UByte] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toByte) -} - -def BitStream_DecodeConstraintWholeNumberUShort(pBitStrm: BitStream, min: UShort, max: UShort): Option[UShort] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toShort) -} - -def BitStream_DecodeConstraintWholeNumberUInt(pBitStrm: BitStream, min: UInt, max: UInt): Option[UInt] = { - - BitStream_DecodeConstraintWholeNumber(pBitStrm, min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toInt) -} - -def BitStream_DecodeConstraintPosWholeNumber(pBitStrm: BitStream, min: ULong, max: ULong): Option[ULong] = { - require(max >= 0 && max <= Long.MaxValue) - require(min >= 0 && min <= max) - - val range: ULong = max - min - - if range == 0 then - return Some(min) - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - - BitStream_DecodeNonNegativeInteger(pBitStrm, nRangeBits) match - case None() => None() - case Some(uv) => Some(uv + min) -} - -def BitStream_EncodeSemiConstraintWholeNumber(pBitStrm: BitStream, v: Long, min: Long): Unit = { - assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt((v - min)) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - /* put required zeros*/ - pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) - /*Encode number */ - BitStream_EncodeNonNegativeInteger(pBitStrm, (v - min)) -} - -def BitStream_EncodeSemiConstraintPosWholeNumber(pBitStrm: BitStream, v: ULong, min: ULong): Unit = { - assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt(v - min) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - /* put required zeros*/ - pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) - /*Encode number */ - BitStream_EncodeNonNegativeInteger(pBitStrm, v - min) -} - - -def BitStream_DecodeSemiConstraintWholeNumber(pBitStrm:BitStream, min: Long): Option[Long] = { - - var nBytes: Long = 0 - var v: Long = 0 - - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - - v += min - - return Some(v) -} - - -def BitStream_DecodeSemiConstraintPosWholeNumber(pBitStrm:BitStream, min: ULong): Option[ULong] = { - - var nBytes: Long = 0 - var v: ULong = 0 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - v += min - return Some(v) -} - -def BitStream_EncodeUnConstraintWholeNumber(pBitStrm: BitStream, v: Long): Unit = { - val nBytes: Int = GetLengthInBytesOfSInt(v) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - - if v >= 0 then - pBitStrm.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) - BitStream_EncodeNonNegativeInteger(pBitStrm, v) - else - pBitStrm.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) - BitStream_EncodeNonNegativeIntegerNeg(pBitStrm, (-v - 1), true) -} - - -def BitStream_DecodeUnConstraintWholeNumber(pBitStrm: BitStream): Option[Long] = { - - var nBytes: Long = 0 - - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - val valIsNegative: Boolean = pBitStrm.peekBit() - - var v: Long = if valIsNegative then Long.MaxValue else 0 - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - - return Some(v) -} - -/** -Binary encoding will be used -REAL = M*B^E -where -M = S*N*2^F - -ENCODING is done within three parts -part 1 is 1 byte header -part 2 is 1 or more byte for exponent -part 3 is 3 or more byte for mantissa (N) - -First byte -S :0-->+, S:1-->-1 -Base will be always be 2 (implied by 6th and 5th bit which are zero) -ab: F (0..3) -cd:00 --> 1 byte for exponent as 2's complement -cd:01 --> 2 byte for exponent as 2's complement -cd:10 --> 3 byte for exponent as 2's complement -cd:11 --> 1 byte for encoding the length of the exponent, then the exponent - -8 7 6 5 4 3 2 1 -+-+-+-+-+-+-+-+-+ -|1|S|0|0|a|b|c|d| -+-+-+-+-+-+-+-+-+ -**/ - -def CalculateMantissaAndExponent(dAsll: Long): (UInt, ULong) = { - require({ - val rawExp = (dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits - rawExp >= 0 &&& rawExp <= ((1 << 11) - 2) // 2046, 2047 is the infinity case - never end up here with infinity - }) - - val exponent: UInt = ((dAsll & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt - var mantissa: ULong = dAsll & MantissaBitMask - mantissa = mantissa | MantissaExtraBit - - (exponent, mantissa) - -}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) - &&& m >= 0 &&& m <= MantissaBitMask) - -/** -Helper function for REAL encoding - -Negative Ints always need 4 bytes of space, the ASN.1 standard compacts those numbers down -to 8, 16 or 24 bits depending on the leading bytes full of 1s. - -Example: --4 in Int: 0b1111_..._1111_1100 ---> compacted to 0b1111_1100 - -The ASN.1 header holds the detail on how to interpret this number -**/ -def RemoveLeadingFFBytesIfNegative(v: Int): Int = { - if v >= 0 then - v - else if v >= Byte.MinValue then - v & 0xFF - else if v >= Short.MinValue then - v & 0xFF_FF - else if v >= -8_388_608 then - v & 0xFF_FF_FF - else - v -} - -def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { - ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) -} - -@extern -def BitStream_EncodeReal(pBitStrm: BitStream, vVal: Double): Unit = { - BitStream_EncodeRealBitString(pBitStrm, java.lang.Double.doubleToRawLongBits(vVal)) -} - -def BitStream_EncodeRealBitString(pBitStrm: BitStream, vVal: Long): Unit = { - // according to T-REC-X.690 2021 - - var v = vVal - - // 8.5.2 Plus Zero - if v == DoublePosZeroBitString then - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0, 0, 0xFF) - return; - - // 8.5.3 Minus Zero - if v == DoubleNegZeroBitString then - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x43, 0, 0xFF) - return; - - // 8.5.9 SpecialRealValues (2021 standard) - if (v & ExpoBitMask) == ExpoBitMask then - - // 8.5.9 PLUS-INFINITY - if v == DoublePosInfBitString then - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x40, 0, 0xFF) - return; - - // 8.5.9 MINUS-INFINITY - else if v == DoubleNegInfBitString then - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x41, 0, 0xFF) - return; - - // 8.5.9 NOT-A-NUMBER - else - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0x42, 0, 0xFF) - return; - - // 8.5.6 a) - // fixed encoding style to binary - // 8.5.7.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 - // 8.5.7.3 F value is always zero - bit 0x08 and 0x04 are always 0 - var header = 0x80 - - // 8.5.7.1 - if ((v & SignBitMask) == SignBitMask) { // check sign bit - header |= 0x40 - v &= InverseSignBitMask // clear sign bit - } - - val (exponent, mantissa) = CalculateMantissaAndExponent(v) - - val nManLen: Int = GetLengthInBytesOfUInt(mantissa) - assert(nManLen <= 7) // 52 bit - - val compactExp = RemoveLeadingFFBytesIfNegative(exponent) - val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) - assert(nExpLen >= 1 && nExpLen <= 2) - - // 8.5.7.4 - if nExpLen == 2 then - header |= 0x01 - else if nExpLen == 3 then // this will never happen with this implementation - header |= 0x02 - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, 1 + nExpLen + nManLen, 0, 0xFF) - - /* encode header */ - BitStream_EncodeConstraintWholeNumber(pBitStrm, header & 0xFF, 0, 0xFF) - - /* encode exponent */ - if exponent >= 0 then - // fill with zeros to have a whole byte - pBitStrm.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) - BitStream_EncodeNonNegativeInteger(pBitStrm, exponent) - else - BitStream_EncodeNonNegativeInteger(pBitStrm, compactExp) - - /* encode mantissa */ - pBitStrm.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) - BitStream_EncodeNonNegativeInteger(pBitStrm, mantissa) -} - -@extern -def BitStream_DecodeReal(pBitStrm: BitStream): Option[Double] = { - BitStream_DecodeRealBitString(pBitStrm) match - case None() => - None() - case Some(ll) => - Some(java.lang.Double.longBitsToDouble(ll)) -} - -def BitStream_DecodeRealBitString(pBitStrm: BitStream): Option[Long] = { - pBitStrm.readByte() match - case None() => None() - case Some(length) => - // 8.5.2 Plus Zero - if length == 0 then - return Some(0) - - // invalid state - if length < 0 || length > DoubleMaxLengthOfSentBytes then - return None() - - pBitStrm.readByte() match - case None() => None() - case Some(header) => - // 8.5.6 a) - if (header.unsignedToInt & 0x80) != 0x80 then - return None() - - // 8.5.9 PLUS-INFINITY - if header == 0x40 then - Some(DoublePosInfBitString) - - // 8.5.9 MINUS-INFINITY - else if header == 0x41 then - Some(DoubleNegInfBitString) - - // 8.5.9 NOT-A-NUMBER - else if header == 0x42 then - Some(DoubleNotANumber) - - // 8.5.3 Minus Zero - else if header == 0x43 then - Some(DoubleNegZeroBitString) - - // Decode 8.5.7 - else - DecodeRealAsBinaryEncoding(pBitStrm, length.toInt - 1, header) -} - -def DecodeRealAsBinaryEncoding(pBitStrm: BitStream, lengthVal: Int, header: UByte): Option[Long] = { - require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte - require((header.unsignedToInt & 0x80) == 0x80) - require(pBitStrm.buf.length > lengthVal) - require(pBitStrm.currentByte < pBitStrm.buf.length - lengthVal) - - // 8.5.7.2 Base - val expFactor: Int = header.unsignedToInt match - case x if (x & 0x10) > 0 => 3 // 2^3 = 8 - case x if (x & 0x20) > 0 => 4 // 2^4 = 16 - case _ => 1 // 2^1 = 2 - - // 8.5.7.3 Factor F - val factor = 1 << ((header & 0x0C) >>> 2) - - // 8.5.7.4 Length of Exponent - val expLen = (header & 0x03) + 1 - - // sanity check - if expLen > lengthVal then - return None() - - // decode exponent - val expIsNegative = pBitStrm.peekBit() - var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 - - var i: Int = 0 - (while i < expLen do - decreases(expLen - i) - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) - - i += 1 - ).invariant(i >= 0 && i <= expLen) - - // decode mantissa - val length = lengthVal - expLen - var N: ULong = 0 - var j: Int = 0 - (while j < length do - decreases(length - j) - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) - - j += 1 - ).invariant(j >= 0 && j <= length) - - var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) - - // 8.5.7.1 Set Sign bit - if (header & 0x40) > 0 then - v |= SignBitMask - - Some(v) -} - -def BitStream_checkBitPatternPresent(pBitStrm: BitStream, bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { - var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal - val tmp_currentByte: Int = pBitStrm.currentByte - val tmp_currentBit: Int = pBitStrm.currentBit - var tmp_byte: UByte = 0 - - if pBitStrm.currentByte.toLong*8 + pBitStrm.currentBit + bit_terminated_pattern_size_in_bits.toInt > pBitStrm.buf.length.toLong*8 then - return 0 - - var i: Int = 0 - while bit_terminated_pattern_size_in_bits >= 8 do - decreases(bit_terminated_pattern_size_in_bits) - - pBitStrm.readByte() match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - bit_terminated_pattern_size_in_bits = 8 - if bit_terminated_pattern(i) != tmp_byte then - pBitStrm.currentByte = tmp_currentByte - pBitStrm.currentBit = tmp_currentBit - return 1 - i += 1 - - if bit_terminated_pattern_size_in_bits > 0 then - pBitStrm.readPartialByte(bit_terminated_pattern_size_in_bits) match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte - - if bit_terminated_pattern(i) != tmp_byte then - pBitStrm.currentByte = tmp_currentByte - pBitStrm.currentBit = tmp_currentBit - return 1 - - return 2 -} - - -def BitStream_ReadBits_nullterminated(pBitStrm: BitStream, bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { - var checkBitPatternPresentResult: Int = 0 - - var bitsRead: Int = 0 - - val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) - - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do - decreases(nMaxReadBits - bitsRead) - pBitStrm.readBit() match - case None() => return NoneMut() - case Some(bitVal) => - tmpStrm.appendBit(bitVal) - bitsRead += 1 - - if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if checkBitPatternPresentResult != 2 then - return NoneMut() - - return SomeMut((tmpStrm.buf, bitsRead)) -} - - -def BitStream_EncodeOctetString_no_length(pBitStrm: BitStream, arr: Array[UByte], nCount: Int): Boolean = { - val cb = pBitStrm.currentBit - var ret: Boolean = false - - if cb == 0 then - ret = pBitStrm.currentByte + nCount <= pBitStrm.buf.length - if ret then - copyToArray(arr, pBitStrm.buf, pBitStrm.currentByte, nCount) - pBitStrm.currentByte += nCount - - else - ret = pBitStrm.appendByteArray(arr, nCount) - - ret -} - - -def BitStream_DecodeOctetString_no_length(pBitStrm: BitStream, nCount: Int): OptionMut[Array[UByte]] = { - val cb: Int = pBitStrm.currentBit - val arr: Array[UByte] = Array.fill(nCount+1)(0) - - if cb == 0 then - if pBitStrm.currentByte + nCount > pBitStrm.buf.length then - return NoneMut() - - arrayCopyOffset(pBitStrm.buf, arr, pBitStrm.currentByte, pBitStrm.currentByte+nCount, 0) - pBitStrm.currentByte += nCount - - else - pBitStrm.readByteArray(nCount) match - case NoneMut() => return NoneMut() - case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) - - SomeMut(arr) -} - - -def BitStream_EncodeOctetString_fragmentation(pBitStrm: BitStream, arr: Array[UByte], nCount: Int): Boolean = { - var nRemainingItemsVar1: Int = nCount - var nCurBlockSize1: Int = 0 - var nCurOffset1: Int = 0 - var ret: Boolean = nCount >= 0 - - while nRemainingItemsVar1 >= 0x4000 && ret do - decreases(nRemainingItemsVar1) - if nRemainingItemsVar1 >= 0x10000 then - nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF) - else if nRemainingItemsVar1 >= 0xC000 then - nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC3, 0, 0xFF) - else if nRemainingItemsVar1 >= 0x8000 then - nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC2, 0, 0xFF) - else - nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF) - - var i1: Int = nCurOffset1 - while i1 < nCurBlockSize1 + nCurOffset1 && ret do - decreases(nCurBlockSize1 + nCurOffset1 - i1) - ret = pBitStrm.appendByte0(arr(i1)) - i1 += 1 - - nCurOffset1 += nCurBlockSize1 - nRemainingItemsVar1 -= nCurBlockSize1 - - if ret then - if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1.toLong, 0, 0xFF) - else - pBitStrm.appendBit(true) - BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1.toLong, 0, 0x7FFF) - - - var i1: Int = nCurOffset1 - while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do - decreases(nCurOffset1 + nRemainingItemsVar1 - i1) - ret = pBitStrm.appendByte0(arr(i1)) - i1 += 1 - - return ret -} - -def BitStream_DecodeOctetString_fragmentation(pBitStrm: BitStream, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) - - val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) - var nCount: Int = 0 - - var nLengthTmp1: Long = 0 - var nRemainingItemsVar1: Long = 0 - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - - // get header data - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - // 11xx_xxxx header, there is a next fragment - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease - - // get current block size - if nRemainingItemsVar1 == 0xC4 then - nCurBlockSize1 = 0x10000 - else if nRemainingItemsVar1 == 0xC3 then - nCurBlockSize1 = 0xC000 - else if nRemainingItemsVar1 == 0xC2 then - nCurBlockSize1 = 0x8000 - else if nRemainingItemsVar1 == 0xC1 then - nCurBlockSize1 = 0x4000 - else - return NoneMut() - - // fill current payload fragment into dest - var i1: Int = nCurOffset1.toInt - while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do - decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) - pBitStrm.readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub - i1 += 1 - - // sum combined length - nLengthTmp1 += nCurBlockSize1 - // set offset for next run - nCurOffset1 += nCurBlockSize1 - - // get next header - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower - if (nRemainingItemsVar1 & 0x80) > 0 then - - nRemainingItemsVar1 <<= 8 // put upper at correct position - // get size (lower byte) - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size - nRemainingItemsVar1 &= 0x7FFF // clear the control bit - - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - var i1: Int = nCurOffset1.toInt - - // fill last payload fragment into dest - while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do - decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) - pBitStrm.readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub - i1 += 1 - - // add remainingSize to already written size - this var holds the absolut number in all fragments - nLengthTmp1 += nRemainingItemsVar1 - - // resize output array and copy data - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) - arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) - return SomeMut(newArr) - else - return NoneMut() - - NoneMut() -} - - -def BitStream_EncodeOctetString(pBitStrm: BitStream, arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { - var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax - - if ret then - if asn1SizeMax < 65536 then - if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount.toLong, asn1SizeMin, asn1SizeMax) - ret = BitStream_EncodeOctetString_no_length(pBitStrm, arr, nCount) - - else - ret = BitStream_EncodeOctetString_fragmentation(pBitStrm, arr, nCount) - - return ret -} - - -def BitStream_DecodeOctetString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - - if asn1SizeMax < 65536 then - var nCount: Int = 0 - if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l.toInt - else - nCount = asn1SizeMin.toInt - - if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then - return BitStream_DecodeOctetString_no_length(pBitStrm, nCount) - else - return NoneMut() - - else - return BitStream_DecodeOctetString_fragmentation(pBitStrm, asn1SizeMax) - -} - - -def BitStream_EncodeBitString(pBitStrm: BitStream, arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { - if asn1SizeMax < 65536 then - if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount.toLong, asn1SizeMin, asn1SizeMax) - - pBitStrm.appendBits(arr, nCount) - - else - var nRemainingItemsVar1: Long = nCount.toLong - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - while nRemainingItemsVar1 >= 0x4000 do - decreases(nRemainingItemsVar1) - - if nRemainingItemsVar1 >= 0x10000 then - nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF) - - else if nRemainingItemsVar1 >= 0xC000 then - nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC3, 0, 0xFF) - else if nRemainingItemsVar1 >= 0x8000 then - nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC2, 0, 0xFF) - else - nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF) - - val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0)// STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) - pBitStrm.appendBits(t, nCurBlockSize1.toInt) - nCurOffset1 += nCurBlockSize1 - nRemainingItemsVar1 -= nCurBlockSize1 - - - if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1, 0, 0xFF) - else - pBitStrm.appendBit(true) - BitStream_EncodeConstraintWholeNumber(pBitStrm, nRemainingItemsVar1, 0, 0x7FFF) - - val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) - pBitStrm.appendBits(t, nRemainingItemsVar1.toInt) - - true -} - - -def BitStream_DecodeBitString(pBitStrm: BitStream, asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - require(asn1SizeMax <= Int.MaxValue) - - if (asn1SizeMax < 65536) { - var nCount: Long = 0 - if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(pBitStrm, asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l - else - nCount = asn1SizeMin - - return pBitStrm.readBits(nCount.toInt) - - } else { - var nRemainingItemsVar1: Long = 0 - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - var nLengthTmp1: Long = 0 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease - if nRemainingItemsVar1 == 0xC4 then - nCurBlockSize1 = 0x10000 - else if nRemainingItemsVar1 == 0xC3 then - nCurBlockSize1 = 0xC000 - else if nRemainingItemsVar1 == 0xC2 then - nCurBlockSize1 = 0x8000 - else if nRemainingItemsVar1 == 0xC1 then - nCurBlockSize1 = 0x4000 - else - return NoneMut() - - /*COVERAGE_IGNORE*/ - if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then - return NoneMut() - /*COVERAGE_IGNORE*/ - - pBitStrm.readBits(nCurBlockSize1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) - nLengthTmp1 += nCurBlockSize1 - nCurOffset1 += nCurBlockSize1 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - if (nRemainingItemsVar1 & 0x80) > 0 then - nRemainingItemsVar1 <<= 8 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l - nRemainingItemsVar1 &= 0x7FFF - - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - - pBitStrm.readBits(nRemainingItemsVar1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) - nLengthTmp1 += nRemainingItemsVar1 - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return SomeMut(arr) - } - return NoneMut() -} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala deleted file mode 100644 index f0d06b929..000000000 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_acn.scala +++ /dev/null @@ -1,1837 +0,0 @@ -package asn1scala - -import stainless.lang.{None => None, Option => Option, Some => Some} - -val FAILED_READ_ERR_CODE = 5400 - -def Acn_AlignToNextByte(pBitStrm: BitStream, bEncode: Boolean): Unit = -{ - if pBitStrm.currentBit != 0 then - pBitStrm.currentBit = 0 - pBitStrm.currentByte += 1 - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_AlignToNextWord(pBitStrm: BitStream, bEncode: Boolean): Unit = -{ - Acn_AlignToNextByte(pBitStrm, bEncode) - - pBitStrm.currentByte += pBitStrm.currentByte % 2 - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_AlignToNextDWord(pBitStrm: BitStream, bEncode: Boolean): Unit = -{ - Acn_AlignToNextByte(pBitStrm, bEncode) - - //pBitStrm.currentByte += pBitStrm.currentByte % 4 - val totalBytes: Int = pBitStrm.currentByte % 4 - if pBitStrm.currentByte + totalBytes < pBitStrm.buf.length then - pBitStrm.currentByte += totalBytes - else - val extraBytes: Int = pBitStrm.currentByte + totalBytes - pBitStrm.buf.length - pBitStrm.currentByte = pBitStrm.buf.length - pBitStrm.currentByte = extraBytes - - CHECK_BIT_STREAM(pBitStrm) -} - -/*ACN Integer functions*/ -def Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, intVal: ULong, encodedSizeInBits: Int): Unit = -{ - if encodedSizeInBits == 0 then - return - - /* Get number of bits*/ - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) - /* put required zeros*/ - pBitStrm.appendNBitZero(encodedSizeInBits - nBits) - /*Encode number */ - BitStream_EncodeNonNegativeInteger(pBitStrm, intVal) - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_8(pBitStrm: BitStream, intVal: ULong): Unit = -{ - pBitStrm.appendByte0(intVal.toByte) - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm: BitStream, intVal: ULong, size: Int): Unit = -{ - val tmp: ULong = intVal - var mask: ULong = 0xFF - mask <<= (size - 1) * 8 - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - pBitStrm.appendByte0(ByteToEncode) - mask >>>= 8 - i += 1 - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm, intVal, 2) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm, intVal, 4) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_B(pBitStrm, intVal, NO_OF_BYTES_IN_JVM_LONG) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, intVal: ULong, size: Int): Unit = -{ - var tmp: ULong = intVal - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = tmp.toByte - pBitStrm.appendByte0(ByteToEncode) - tmp >>>= 8 - i += 1 - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, intVal, 2) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, intVal, 4) -} - -def Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm: BitStream, intVal: ULong): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, intVal, NO_OF_BYTES_IN_JVM_LONG) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm: BitStream, encodedSizeInBits: Int): Option[ULong] = -{ - BitStream_DecodeNonNegativeInteger(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(ul) => Some(ul) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm: BitStream): Option[ULong] = -{ - pBitStrm.readByte() match - case None() => None() - case Some(ub) => Some(ub & 0xFF) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm: BitStream, SizeInBytes: Int): Option[ULong] = -{ - var ret: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - ret <<= 8 - ret |= (ub & 0xFF) - i += 1 - - Some(ret) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm: BitStream): Option[ULong] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm, 2) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm: BitStream): Option[ULong] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm, 4) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm: BitStream): Option[ULong] = -{ - pBitStrm.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_N(pBitStrm, NO_OF_BYTES_IN_JVM_LONG) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm: BitStream, SizeInBytes: Int): Option[ULong] = -{ - var ret: ULong = 0 - var tmp: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - tmp = ub & 0xFF - tmp <<= i * 8 - ret |= tmp - i += 1 - - Some(ret) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm: BitStream): Option[ULong] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, 2) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm: BitStream): Option[ULong] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, 4) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm: BitStream): Option[ULong] = -{ - val ret = Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(pBitStrm, NO_OF_BYTES_IN_JVM_LONG) - pBitStrm.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - ret -} - - -def Encode_UnsignedInteger(pBitStrm: BitStream, v: ULong, nBytes: Byte): Unit = -{ - val MAX_BYTE_MASK = 0xFF00000000000000L - assert(nBytes <= 8) - - var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 -nBytes * 8) - - var i: Int = 0 - while i < nBytes do - val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - pBitStrm.appendByte0(ByteToEncode) - vv <<= 8 - i += 1 -} - - -def Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): Unit = -{ - val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte - - /* encode length */ - pBitStrm.appendByte0(nBytes) - /* Encode integer data*/ - Encode_UnsignedInteger(pBitStrm, intVal, nBytes) - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = -{ - var v: ULong = 0 - - pBitStrm.readByte() match - case None() => return None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - v = (v << 8) | (ub & 0xFF) - i += 1 - - Some(v) -} - - -def Acn_Enc_Int_TwosComplement_ConstSize(pBitStrm: BitStream, intVal: Long, encodedSizeInBits: Int): Unit = -{ - if intVal >= 0 then - pBitStrm.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) - BitStream_EncodeNonNegativeInteger(pBitStrm, intVal) - - else - pBitStrm.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) - BitStream_EncodeNonNegativeIntegerNeg(pBitStrm, -intVal - 1, true) - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Enc_Int_TwosComplement_ConstSize_8(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_8(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm, int2uint(intVal)) -} - -def Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm: BitStream, intVal: Long): Unit = -{ - Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm, int2uint(intVal)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm: BitStream, encodedSizeInBits: Int): Option[Long] = -{ - val valIsNegative: Boolean = pBitStrm.peekBit() - val nBytes: Int = encodedSizeInBits / 8 - val rstBits: Int = encodedSizeInBits % 8 - - var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 - - var i: Int = 0 - while i < nBytes do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << 8) | (ub & 0xFF) - i += 1 - - if rstBits > 0 then - pBitStrm.readPartialByte(rstBits.toByte) match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << rstBits) | (ub & 0xFF) - - Some(pIntVal) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, 1)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) -} - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm: BitStream): Option[Long] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) -} - - -def Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: Long): Unit = -{ - val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte - - /* encode length */ - pBitStrm.appendByte0(nBytes) - /* Encode integer data*/ - Encode_UnsignedInteger(pBitStrm, int2uint(intVal), nBytes) - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[Long] = -{ - var v: ULong = 0 - var isNegative: Boolean = false - - pBitStrm.readByte() match - case None() => None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => - if i == 0 && (ub & 0x80) > 0 then - v = Long.MaxValue - isNegative = true - - v = (v << 8) | (ub & 0xFF) - i += 1 - - if isNegative then - Some(-(~v) - 1) - else - Some(v) -} - - -//return values is in nibbles -def Acn_Get_Int_Size_BCD(intVal: ULong): Int = -{ - var intVar = intVal - var ret: Int = 0 - while intVar > 0 do - intVar /= 10 - ret += 1 - - ret -} - - -def Acn_Enc_Int_BCD_ConstSize(pBitStrm: BitStream, intVal: ULong, encodedSizeInNibbles: Int): Unit = -{ - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) - - assert(100 >= encodedSizeInNibbles) - - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 - - assert(encodedSizeInNibbles >= totalNibbles) - - var i: Int = encodedSizeInNibbles - 1 - while i >= 0 do - pBitStrm.appendPartialByte(tmp(i).toByte, 4,false) - i -= 1 - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Dec_Int_BCD_ConstSize(pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[ULong] = -{ - var ret: ULong = 0 - - var encodedSizeInNibblesVar = encodedSizeInNibbles - while encodedSizeInNibblesVar > 0 do - pBitStrm.readPartialByte(4) match - case None() => return None() - case Some(digit) => - ret *= 10 - ret += digit - encodedSizeInNibblesVar -= 1 - - Some(ret) -} - - -def Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): Unit = -{ - val nNibbles: Int = Acn_Get_Int_Size_BCD(intVal) - /* encode length */ - pBitStrm.appendByte0(nNibbles.toByte) - - /* Encode Number */ - Acn_Enc_Int_BCD_ConstSize(pBitStrm, intVal, nNibbles) - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = -{ - pBitStrm.readByte() match - case None() => None() - case Some(nNibbles) => Acn_Dec_Int_BCD_ConstSize(pBitStrm, nNibbles) -} - - -//encoding puts an 'F' at the end -def Acn_Enc_Int_BCD_VarSize_NullTerminated(pBitStrm: BitStream, intVal: ULong): Unit = -{ - - val nNibbles: Int = Acn_Get_Int_Size_BCD(intVal) - - /* Encode Number */ - Acn_Enc_Int_BCD_ConstSize(pBitStrm, intVal, nNibbles) - - pBitStrm.appendPartialByte(0xF, 4, false) - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm: BitStream): Option[ULong] = -{ - var ret: ULong = 0 - - while true do - pBitStrm.readPartialByte(4) match - case None() => return None() - case Some(digit) => - if (digit > 9) - return Some(ret) - - ret *= 10 - ret += digit - - Some(ret) -} - - -def Acn_Enc_UInt_ASCII_ConstSize(pBitStrm: BitStream, intVal: ULong, encodedSizeInBytes: Int): Unit = -{ - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) - - assert(100 >= encodedSizeInBytes) - - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 - - assert(encodedSizeInBytes >= totalNibbles) - - var i = encodedSizeInBytes - 1 - while i >= 0 do - pBitStrm.appendByte0((tmp(i) + '0').toByte) - i -= 1 - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Enc_SInt_ASCII_ConstSize(pBitStrm: BitStream, intVal: Long, encodedSizeInBytes: Int): Unit = -{ - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal - - /* encode sign */ - pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') - - Acn_Enc_UInt_ASCII_ConstSize(pBitStrm, absIntVal, encodedSizeInBytes-1) -} - -def Acn_Dec_UInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): Option[ULong] = -{ - var encodedSizeInBytesVar = encodedSizeInBytes - var ret: ULong = 0 - - while encodedSizeInBytesVar > 0 do - pBitStrm.readByte() match - case None() => return None() - case Some(digit) => - assert(digit >= '0' && digit <= '9') - - ret *= 10 - ret += (digit.toInt -'0').toByte - - encodedSizeInBytesVar -= 1 - - Some(ret) -} - -def Acn_Dec_SInt_ASCII_ConstSize(pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Long] = -{ - pBitStrm.readByte() match - case None() => None() - case Some(digit) => - var sign: Int = 1 - if digit == '+' then - sign = 1 - else if digit == '-' then - sign = -1 - else - assert(false) - - Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes - 1) match - case None() => None() - case Some(ul) => Some(sign * ul) -} - - -def getIntegerDigits (intVal: ULong): (Array[Byte], Byte) = { - var intVar = intVal - val digitsArray100: Array[Byte] = Array.fill(100)(0) - val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) - var totalDigits: Byte = 0 - - - if intVar > 0 then - while intVar > 0 && totalDigits < 100 do - reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte - totalDigits = (totalDigits + 1).toByte - intVar /= 10 - - var i: Int = totalDigits -1 - while i >= 0 do - digitsArray100(totalDigits-1 - i) = reversedDigitsArray(i) - i -= 1 - - else - digitsArray100(0) = '0' - totalDigits = 1 - - (digitsArray100, totalDigits) -} - - -def Acn_Enc_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: Long): Unit = -{ - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal - val (digitsArray100, nChars) = getIntegerDigits(absIntVal) - - /* encode length, plus 1 for sign */ - pBitStrm.appendByte0((nChars + 1).toByte) - - /* encode sign */ - pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') - - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - pBitStrm.appendByte0(digitsArray100(i)) - i += 1 - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream, intVal: ULong): Unit = -{ - val (digitsArray100, nChars) = getIntegerDigits(intVal) - - /* encode length */ - pBitStrm.appendByte0(nChars) - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - pBitStrm.appendByte0(digitsArray100(i)) - i += 1 - - CHECK_BIT_STREAM(pBitStrm) -} - - -def Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[ULong] = -{ - pBitStrm.readByte() match - case None() => None() - case Some(nChars) => Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, nChars) -} - -def Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm: BitStream): Option[Long] = -{ - pBitStrm.readByte() match - case None() => None() - case Some(nChars) => Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, nChars) -} - - -def Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = -{ - val (digitsArray100, nChars) = getIntegerDigits(intVal) - - var i: Int = 0 // TODO: size_t? - while i < 100 && digitsArray100(i) != 0x0 do - pBitStrm.appendByte0(digitsArray100(i)) - i += 1 - - i = 0 - while i < null_characters_size do - pBitStrm.appendByte0(null_characters(i)) - i += 1 - - CHECK_BIT_STREAM(pBitStrm) -} - -def Acn_Enc_SInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = -{ - val absValue: ULong = if intVal >= 0 then intVal else -intVal - pBitStrm.appendByte0(if intVal >= 0 then '+' else '-') - - Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm, absValue, null_characters, null_characters_size) -} - -/* -flag Acn_Dec_String_Ascii_Null_Teminated_mult(BitStream* pBitStrm, max: Long, null_character: Array[Byte], null_character_size: Int, char* strVal) -{ -byte tmp[10]; -size_t sz = null_character_size < 10 ? null_character_size : 10; -val tmp: Array[Byte] = Array.fill(10)(0) -memset(strVal, 0x0, (size_t)max + 1); -//read null_character_size characters into the tmp buffer -for (int j = 0; j < (int)null_character_size; j++) { -if (!pBitStrm.readByte(, &(tmp[j]))) -return FALSE; -} - -asn1SccSint i = 0; -while (i <= max && (memcmp(null_character, tmp, sz) != 0)) { -strVal[i] = tmp[0]; -i++; -for (int j = 0; j < (int)null_character_size - 1; j++) -tmp[j] = tmp[j + 1]; -if (!pBitStrm.readByte(, &(tmp[null_character_size - 1]))) -return FALSE; -} - -strVal[i] = 0x0; -return memcmp(null_character, tmp, sz) == 0; - -} - - -*/ - - -def Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = -{ - var digit: Byte = 0 - var ret: ULong = 0 - val tmp: Array[Byte] = Array.fill(10)(0) - - val sz: Int = if null_characters_size < 10 then null_characters_size else 10 - - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_characters_size do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub - j += 1 - - var i: Long = 0 - while !null_characters.sameElements(tmp) do - digit = tmp(0) - i += 1 - - j = 0 - while j < null_characters_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => tmp(null_characters_size - 1) = ub - - digit = (digit - '0').toByte - - ret *= 10 - ret += digit - - Some(ret) -} - - -def Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Long] = -{ - var isNegative: Boolean = false - - pBitStrm.readByte() match - case None() => None() - case Some(digit) => - assert(digit == '-' || digit == '+') - if digit == '-' then - isNegative = true - - Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(ul) => Some(if isNegative then -ul else ul) -} - - -/* Boolean Decode */ - -def BitStream_ReadBitPattern(pBitStrm: BitStream, patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = -{ - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var pBoolValue: Boolean = true - var i: Int = 0 - while i < nBytesToRead do - pBitStrm.readByte() match - case None() => return None() - case Some(curByte) => - if curByte != patternToRead(i) then - pBoolValue = false - i += 1 - - if nRemainingBitsToRead > 0 then - pBitStrm.readPartialByte(nRemainingBitsToRead.toByte) match - case None() => return None() - case Some(curByte) => - if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then - pBoolValue = false - - Some(pBoolValue) -} - - -def BitStream_ReadBitPattern_ignore_value(pBitStrm: BitStream, nBitsToRead: Int): Either[ErrorCode, Int] = -{ - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var i: Int = 0 - while i < nBytesToRead do - pBitStrm.readByte() match - case None() => return Left(FAILED_READ_ERR_CODE) - case Some(_) => i += 1 - - if nRemainingBitsToRead > 0 then - if pBitStrm.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then - return Left(FAILED_READ_ERR_CODE) - - Right(0) -} - - -/*Real encoding functions*/ -def Acn_Enc_Real_IEEE754_32_big_endian(pBitStrm: BitStream, realValue: Float): Unit = -{ - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array - - var i: Int = 0 - while i < 4 do - pBitStrm.appendByte0(b(i)) - i += 1 -} - -def Acn_Dec_Real_IEEE754_32_big_endian(pBitStrm: BitStream): Option[Double] = -{ - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1).toDouble) -} - -def Acn_Dec_Real_IEEE754_32_big_endian_fp32(pBitStrm: BitStream): Option[Float] = -{ - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) -} - - -def Acn_Enc_Real_IEEE754_64_big_endian(pBitStrm: BitStream, realValue: Double): Unit = -{ - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 0 - while i < 8 do - pBitStrm.appendByte0(b(i)) - i += 1 -} - -def Acn_Dec_Real_IEEE754_64_big_endian(pBitStrm: BitStream): Option[Double] = -{ - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 0 - while i < 8 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) -} - - -def Acn_Enc_Real_IEEE754_32_little_endian(pBitStrm: BitStream, realValue: Double): Unit = -{ - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array - - var i: Int = 3 - while i >= 0 do - pBitStrm.appendByte0(b(i)) - i -= 1 -} - -def Acn_Dec_Real_IEEE754_32_little_endian(pBitStrm: BitStream): Option[Double] = -{ - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 3 - while i >= 0 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1).toDouble) - -} -def Acn_Dec_Real_IEEE754_32_little_endian_fp32(pBitStrm: BitStream): Option[Float] = -{ - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 3 - while i >= 0 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) -} - -def Acn_Enc_Real_IEEE754_64_little_endian(pBitStrm: BitStream, realValue: Double): Unit = -{ - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 7 - while i >= 0 do - pBitStrm.appendByte0(b(i)) - i -= 1 -} - -def Acn_Dec_Real_IEEE754_64_little_endian(pBitStrm: BitStream): Option[Double] = -{ - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 7 - while i >= 0 do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) -} - - - - -/* String functions*/ -def Acn_Enc_String_Ascii_FixSize(pBitStrm: BitStream, max: Long, strVal: Array[ASCIIChar]): Unit = -{ - var i: Long = 0 - while i < max do - pBitStrm.appendByte(strVal(i.toInt), false) - i += 1 -} -def Acn_Enc_String_Ascii_private(pBitStrm: BitStream, max: Long, strVal: Array[ASCIIChar]): Long = -{ - var i: Long = 0 - while (i < max) && (strVal(i.toInt) != '\u0000') do - pBitStrm.appendByte(strVal(i.toInt), false) - i += 1 - - i -} - -def Acn_Enc_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = -{ - Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) - pBitStrm.appendByte(null_character.toByte, false) -} - -def Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = -{ - Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) - var i: Int = 0 - while i < null_character_size do - pBitStrm.appendByte(null_character(i), false) - i += 1 -} - - -def Acn_Enc_String_Ascii_External_Field_Determinant(pBitStrm: BitStream, max: Long, strVal: Array[ASCIIChar]): Unit = -{ - Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) -} - -def Acn_Enc_String_Ascii_Internal_Field_Determinant(pBitStrm: BitStream, max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = -{ - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(pBitStrm, if strLen <= max then strLen else max, min, max) - Acn_Enc_String_Ascii_private(pBitStrm, max, strVal) -} - -def Acn_Enc_String_CharIndex_FixSize(pBitStrm: BitStream, max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = -{ - var i: Int = 0 - while i < max do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(pBitStrm, charIndex, 0, allowedCharSet.length - 1) - i += 1 -} - -def Acn_Enc_String_CharIndex_private(pBitStrm: BitStream, max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = -{ - var i: Int = 0 - while (i < max) && (strVal(i) != '\u0000') do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(pBitStrm, charIndex, 0, allowedCharSet.length - 1) - i += 1 - - i -} - - -def Acn_Enc_String_CharIndex_External_Field_Determinant (pBitStrm: BitStream, max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = -{ - Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, strVal) -} - -def Acn_Enc_String_CharIndex_Internal_Field_Determinant (pBitStrm: BitStream, max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = -{ - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(pBitStrm, if strLen <= max then strLen else max, min, max) - Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, strVal) -} - - -def Acn_Enc_IA5String_CharIndex_External_Field_Determinant(pBitStrm: BitStream, max: Long, strVal: Array[ASCIIChar]): Unit = -{ - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - - Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, strVal) -} - -def Acn_Enc_IA5String_CharIndex_Internal_Field_Determinant(pBitStrm: BitStream, max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = -{ - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(pBitStrm, if strLen <= max then strLen else max, min, max) - Acn_Enc_String_CharIndex_private(pBitStrm, max, allowedCharSet, strVal) -} - - -def Acn_Dec_String_Ascii_private(pBitStrm: BitStream, max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = -{ - val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) - var i: Int = 0 - while i < charactersToDecode do - pBitStrm.readByte() match - case None() => return None() - case Some(decodedCharacter) => - strVal(i) = decodedCharacter - i += 1 - Some(strVal) -} - - -def Acn_Dec_String_Ascii_FixSize(pBitStrm: BitStream, max: Long): Option[Array[ASCIIChar]] = -{ - Acn_Dec_String_Ascii_private(pBitStrm, max, max) -} - -/* -int put_byte_in_last_dec_bytes(byte last_dec_bytes[], size_t* pCur_size, size_t null_characters_size, byte decodedCharacter, byte *pDiscardedCharacter) { -int i; -if (*pCur_size < null_characters_size) { -last_dec_bytes[*pCur_size] = decodedCharacter; -(*pCur_size)++; -*pDiscardedCharacter = NULL; -return 0; -} else { -*pDiscardedCharacter = last_dec_bytes[0]; -for (i = 1; i < null_characters_size; i++) { -last_dec_bytes[i - 1] = last_dec_bytes[i]; -} -last_dec_bytes[null_characters_size - 1] = decodedCharacter; -return 1; -} -} - -flag Acn_Dec_String_Ascii_Null_Teminated(BitStream* pBitStrm, max: Long, const byte null_characters[], size_t null_characters_size, char* strVal) -{ -asn1SccSint i = 0; -byte decodedCharacter; -byte characterToAppendInString; -size_t cur_size_of_last_dec_bytes = 0; -byte last_dec_bytes[128]; -int ret; - -assert(null_characters_size<128); -memset(last_dec_bytes, 0x0, sizeof(last_dec_bytes)); -memset(strVal, 0x0, (size_t)max+1); -while (i<=max) { -if (!pBitStrm.readByte(, &decodedCharacter)) -return FALSE; -ret = put_byte_in_last_dec_bytes(last_dec_bytes, &cur_size_of_last_dec_bytes, null_characters_size, decodedCharacter, &characterToAppendInString); - - -//if (decodedCharacter == (byte)null_character) { -if ((ret == 1) && (memcmp(last_dec_bytes,null_characters,null_characters_size) == 0)) { -strVal[i] = 0x0; -return TRUE; -} else if (ret == 1) { -strVal[i] = characterToAppendInString; -i++; -} -} - -return FALSE; - -} - -*/ - - -def Acn_Dec_String_Ascii_Null_Teminated(pBitStrm: BitStream, max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = -{ - val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) - var i: Int = 0 - while i <= max do - pBitStrm.readByte() match - case None() => return None() - case Some(decodedCharacter) => - if decodedCharacter != null_character then - strVal(i) = decodedCharacter - i += 1 - else - strVal(i) = 0x0 - return Some(strVal) - - None() - -} -def Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm: BitStream, max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = -{ - val sz: Int = if null_character_size < 10 then null_character_size else 10 - val tmp: Array[Byte] = Array.fill(10)(0) - val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_character_size do - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub - j += 1 - - - var i: Int = 0 - while i <= max && !null_character.sameElements(tmp) do - strVal(i) = tmp(0) - i += 1 - j = 0 - while j < null_character_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 - - pBitStrm.readByte() match - case None() => return None() - case Some(ub) => tmp(null_character_size - 1) = ub - - strVal(i) = 0x0 - - if !null_character.sameElements(tmp) then - return None() - - Some(strVal) -} - - -def Acn_Dec_String_Ascii_External_Field_Determinant(pBitStrm: BitStream, max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = -{ - Acn_Dec_String_Ascii_private(pBitStrm, max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) -} - -def Acn_Dec_String_Ascii_Internal_Field_Determinant(pBitStrm: BitStream, max: Long, min: Long): Option[Array[ASCIIChar]] = -{ - BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None() => None() - case Some(nCount) => - Acn_Dec_String_Ascii_private(pBitStrm, max, if nCount <= max then nCount else max) -} - -def Acn_Dec_String_CharIndex_private(pBitStrm: BitStream, max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = -{ - val strVal: Array[ASCIIChar] = Array.fill(max.toInt+1)(0) - var i: Int = 0 - while i < charactersToDecode do - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, allowedCharSet.length - 1) match - case None() => return None() - case Some(charIndex) => - strVal(i) = allowedCharSet(charIndex.toInt) - i += 1 - - Some(strVal) -} - -def Acn_Dec_String_CharIndex_FixSize (pBitStrm: BitStream, max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = -{ - Acn_Dec_String_CharIndex_private(pBitStrm, max, max, allowedCharSet) -} - -def Acn_Dec_String_CharIndex_External_Field_Determinant (pBitStrm: BitStream, max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = -{ - Acn_Dec_String_CharIndex_private(pBitStrm, max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) -} - - -def Acn_Dec_String_CharIndex_Internal_Field_Determinant (pBitStrm: BitStream, max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = -{ - BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None() => None() - case Some(nCount) => - Acn_Dec_String_CharIndex_private(pBitStrm, max, if nCount <= max then nCount else max, allowedCharSet) -} - - -def Acn_Dec_IA5String_CharIndex_External_Field_Determinant(pBitStrm: BitStream, max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = -{ - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - Acn_Dec_String_CharIndex_private(pBitStrm, max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) -} - -def Acn_Dec_IA5String_CharIndex_Internal_Field_Determinant(pBitStrm: BitStream, max: Long, min: Long): Option[Array[ASCIIChar]] = -{ - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - BitStream_DecodeConstraintWholeNumber(pBitStrm, min, max) match - case None() => None() - case Some(nCount) => - Acn_Dec_String_CharIndex_private(pBitStrm, max, if nCount <= max then nCount else max, allowedCharSet) -} - - - - -/* Length Determinant functions*/ -def Acn_Enc_Length(pBitStrm: BitStream, lengthValue: ULong, lengthSizeInBits: Int): Unit = -{ - /* encode length */ - Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm, lengthValue, lengthSizeInBits) -} - -def Acn_Dec_Length(pBitStrm: BitStream, lengthSizeInBits: Int): Option[ULong] = -{ - Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, lengthSizeInBits) -} - -def milbus_encode(v: Long): Long = -{ - if v == 32 then 0 else v -} - -def milbus_decode(v: Long): Long = -{ - if v == 0 then 32 else v -} - - -def Acn_Dec_Int_PositiveInteger_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_8UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSizeInt8 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSizeInt16 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSizeInt32 (pBitStrm: BitStream, encodedSizeInBits: Int): Option[Int] = { - Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_8Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64Int8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_BCD_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UByte] = { - Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_BCD_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UShort] = { - Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_BCD_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInNibbles: Int): Option[UInt] = { - Acn_Dec_Int_BCD_ConstSize(pBitStrm, encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_BCD_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_Int_BCD_VarSize_NullTerminatedUInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_SInt_ASCII_ConstSizeInt8 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Byte] = { - Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_SInt_ASCII_ConstSizeInt16 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Short] = { - Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_SInt_ASCII_ConstSizeInt32 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[Int] = { - Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt8 (pBitStrm: BitStream): Option[Byte] = { - Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt16 (pBitStrm: BitStream): Option[Short] = { - Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_SInt_ASCII_VarSize_LengthEmbeddedInt32 (pBitStrm: BitStream): Option[Int] = { - Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt8 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { - Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt16 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { - Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_SInt_ASCII_VarSize_NullTerminatedInt32 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { - Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_UInt_ASCII_ConstSizeUInt8 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UByte] = { - Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_UInt_ASCII_ConstSizeUInt16 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UShort] = { - Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_UInt_ASCII_ConstSizeUInt32 (pBitStrm: BitStream, encodedSizeInBytes: Int): Option[UInt] = { - Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8 (pBitStrm: BitStream): Option[UByte] = { - Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16 (pBitStrm: BitStream): Option[UShort] = { - Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32 (pBitStrm: BitStream): Option[UInt] = { - Acn_Dec_UInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match - case None() => None() - case Some(v) => Some(v.toInt) -} - - -def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt8 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { - Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) -} - - -def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt16 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { - Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) -} - - -def Acn_Dec_UInt_ASCII_VarSize_NullTerminatedUInt32 (pBitStrm: BitStream, null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { - Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm, null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) -} - diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala deleted file mode 100644 index 4c63e03a3..000000000 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_encoding_uper.scala +++ /dev/null @@ -1,182 +0,0 @@ -package asn1scala - -import stainless.math.BitVectors._ -import stainless.lang.{None => None, Option => Option, Some => Some, _} - -def ObjectIdentifier_subidentifiers_uper_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { - var lastOctet: Boolean = false - val tmp: Array[UByte] = Array.fill(16)(0) - var nSize: Int = 0 - - var siValue = siValueVal - var pSize = pSizeVal - - while !lastOctet do - decreases(siValue) - val curByte: UByte = (siValue % 128).toByte - siValue = siValue / 128 - lastOctet = siValue.toInt == 0 - tmp(nSize) = curByte - nSize += 1 - - var i: Int = 0 - while i < nSize do - decreases(nSize-i) - val curByte: UByte = if i == nSize-1 then tmp(nSize-i-1) else (tmp(nSize-i-1) | 0x80).toByte - encodingBuf(pSize) = curByte - pSize += 1 - i += 1 - return pSize -} -def ObjectIdentifier_uper_encode(pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): Unit = { - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - totalSize = ObjectIdentifier_subidentifiers_uper_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) - - i = 0 - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = ObjectIdentifier_subidentifiers_uper_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0xFF) - else - pBitStrm.appendBit(true) - BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - pBitStrm.appendByte0(tmp(i)) - i += 1 -} -def RelativeOID_uper_encode (pBitStrm: BitStream, pVal: Asn1ObjectIdentifier): Unit = { - //a subifentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded - //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = ObjectIdentifier_subidentifiers_uper_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0xFF) - else - pBitStrm.appendBit(true) - BitStream_EncodeConstraintWholeNumber(pBitStrm, totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - pBitStrm.appendByte0(tmp(i)) - i += 1 -} - -def ObjectIdentifier_subidentifiers_uper_decode(pBitStrm: BitStream, pRemainingOctetsVal: Long): Option[(Long, ULong)] = { - var bLastOctet: Boolean = false - var curOctetValue: ULong = 0 - var siValue: ULong = 0 - var pRemainingOctets: Long = pRemainingOctetsVal - while pRemainingOctets > 0 && !bLastOctet do - decreases(pRemainingOctets) - pBitStrm.readByte() match - case None() => return None() - case Some(curByte) => - pRemainingOctets -= 1 - - bLastOctet = (curByte & 0x80) == 0 - curOctetValue = (curByte & 0x7F).toLong - siValue = siValue << 7 - siValue |= curOctetValue - - return Some((pRemainingOctets, siValue)) -} - - -def ObjectIdentifier_uper_decode_lentg(pBitStrm: BitStream): Option[Long] = { - var totalSize: Long = 0 - - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() - case Some(l) => totalSize = l - - if totalSize > 0x7F then - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match - case None() => return None() - case Some(l) => - totalSize <<= 8 - totalSize |= l - totalSize &= 0x7FFF - - return Some(totalSize) -} -def ObjectIdentifier_uper_decode(pBitStrm: BitStream): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - val pVal = ObjectIdentifier_Init() - - ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None() => return NoneMut() - case Some(l) => totalSize = l - - ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - - pVal.nCount = 2 - pVal.values(0) = si / 40 - pVal.values(1) = si % 40 - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - - ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() - -} -def RelativeOID_uper_decode (pBitStrm: BitStream): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() - - ObjectIdentifier_uper_decode_lentg(pBitStrm) match - case None() => return NoneMut() - case Some(l) => totalSize = l - - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - ObjectIdentifier_subidentifiers_uper_decode(pBitStrm, totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() -} diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala deleted file mode 100644 index fffd802bf..000000000 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_unsigned.scala +++ /dev/null @@ -1,69 +0,0 @@ -package asn1scala - -// all bits of the integer -val MASK_BYTE = 0xFF -val MASK_BYTE_L = 0xFFL -val MASK_SHORT_L = 0xFF_FFL -val MASK_INT_L = 0xFF_FF_FF_FFL - -// MSBs (neg bits of the integer) -val MASK_MSB_BYTE = 0x80L -val MASK_MSB_INT = 0x80_00_00_00L - -// pos bits of the integer -val MASK_POS_BYTE = 0x7FL -val MASK_POS_INT = 0x7F_FF_FF_FFL - -/* -* Meths to upcast unsigned integer data types on the JVM -*/ -extension (ub: UByte) { - def unsignedToLong: Long = ub & MASK_BYTE_L - def unsignedToInt: Int = ub.toInt & MASK_BYTE -} - -extension (us: UShort) { - def unsignedToLong: Long = us & MASK_SHORT_L -} - -extension (ui: UInt) { - def unsignedToLong: Long = ui & MASK_INT_L -} - -extension (i: Int) { - def toUnsignedByte: UByte = { - require(i >= 0 && i <= MASK_BYTE) - - if(i == MASK_MSB_BYTE) - (-MASK_MSB_BYTE).toByte - else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) - ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte - else - i.toByte - } -} - -extension (l: Long) { - def toUnsignedInt: UInt = { - require(l >= 0 && l <= MASK_INT_L) - - if(l == MASK_MSB_INT) - (-MASK_MSB_INT).toInt - else if ((l & MASK_MSB_INT) == MASK_MSB_INT) - ((l & MASK_POS_INT) - MASK_MSB_INT).toInt - else - l.toInt - } -} - -extension (b: Byte) { - def >>>>(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte - } - - def <<<<(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt << i) & MASK_BYTE).toUnsignedByte - } -} diff --git a/asn1scc/GenerateRTL.fs b/asn1scc/GenerateRTL.fs index 2a20a54ce..27de69aaf 100644 --- a/asn1scc/GenerateRTL.fs +++ b/asn1scc/GenerateRTL.fs @@ -108,16 +108,16 @@ let exportRTL (di:DirInfo) (l:ProgrammingLanguage) (args:CommandLineSettings)= match args.encodings with | [] -> () | _ -> - - writeResource di "asn1jvm_encoding.scala" None - writeResource di "asn1jvm_unsigned.scala" None - writeResource di "stainless_utils.scala" None // needed for verification + writeResource di "asn1jvm_Codec.scala" None + writeResource di "asn1jvm_Codec_PER.scala" None + writeResource di "asn1jvm_Helper.scala" None + writeResource di "asn1jvm_Verification.scala" None if hasUper || hasAcn then - writeResource di "asn1jvm_encoding_uper.scala" None + writeResource di "asn1jvm_Codec_UPER.scala" None if hasAcn then - writeResource di "asn1jvm_encoding_acn.scala" None + writeResource di "asn1jvm_Codec_ACN.scala" None // if hasXer then // writeResource di "asn1crt_encoding_xer.c" None diff --git a/asn1scc/asn1jvm_Codec.scala b/asn1scc/asn1jvm_Codec.scala new file mode 100644 index 000000000..81967d663 --- /dev/null +++ b/asn1scc/asn1jvm_Codec.scala @@ -0,0 +1,1004 @@ +package asn1scala + +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +// TODO move to Bitstream if only used there +val masksb: Array[UByte] = Array( + 0x00, // 0 / 0000 0000 / x00 + 0x01, // 1 / 0000 0001 / x01 + 0x03, // 3 / 0000 0011 / x03 + 0x07, // 7 / 0000 0111 / x07 + 0x0F, // 15 / 0000 1111 / x0F + 0x1F, // 31 / 0001 1111 / x1F + 0x3F, // 63 / 0011 1111 / x3F + 0x7F, // 127 / 0111 1111 / x7F + -0x1, // -1 / 1111 1111 / xFF +) + +val masks2: Array[UInt] = Array( + 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 + 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF + 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000 FF00 + 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF 0000 + 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 +) + + +/***********************************************************************************************/ +/** Byte Stream Functions **/ +/***********************************************************************************************/ +def ByteStream_Init(count: Int): ByteStream = { + ByteStream(Array.fill(count)(0), 0, false) +} + +@extern +def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { + pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... + pStrm.currentByte = 0 +}.ensuring(_ => pStrm.buf == buf && pStrm.currentByte == 0 && pStrm.EncodeWhiteSpace == old(pStrm).EncodeWhiteSpace) + +def ByteStream_GetLength(pStrm: ByteStream): Int = { + pStrm.currentByte +} + +/***********************************************************************************************/ +/** Bit Stream Functions **/ +/***********************************************************************************************/ +def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { + arraySameElements(arr1, arr2) + //return + // (nBitsLength1 == nBitsLength2) && + // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && + // (nBitsLength1 % 8 > 0 ? (arr1[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8) == arr2[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8)): TRUE); +} + + +// TODO remove +def BitStream_Init(count: Int): BitStream = { + BitStream(Array.fill(count)(0), 0, 0) +} + +/** + * Parent class for the PER Codec that is used by ACN and UPER + * + * @param count represents the number of bytes in the internal buffer + */ +@mutable +trait Codec { + + def bitStream: BitStream + + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** Integer Functions * */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + /** ******************************************************************************************** */ + + /** ******************************************************************************************** */ + def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { + var cc: UInt = 0 + var curMask: UInt = 0 + var pbits: UInt = 0 + + if v == 0 then + return () + + if v >>> 8 == 0 then + cc = 8 + curMask = 0x80 + else if v >>> 16 == 0 then + cc = 16 + curMask = 0x8000 + else if v >>> 24 == 0 then + cc = 24 + curMask = 0x800000 + else + cc = 32 + curMask = 0x80000000 + + while (v & curMask) == 0 do + decreases(cc) + curMask >>>= 1 + cc -= 1 + + pbits = cc % 8 + if pbits > 0 then + cc -= pbits + bitStream.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) + + while cc > 0 do + decreases(cc) + val t1: UInt = v.toInt & masks2(cc >>> 3) + cc -= 8 + bitStream.appendByte((t1 >>> cc).toByte, negate) + } + + def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { + + var v: UInt = 0 + + var nBits = nBitsVal + while nBits >= 8 do + decreases(nBits) + v = v << 8 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => + // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) + // will be casted to an Int -1 (1111 ... 1111) + v = v | (ub & 0xFF) + + nBits -= 8 + + if nBits != 0 then + v = v << nBits + bitStream.readPartialByte(nBits.toByte) match + case None() => return None() + case Some(ub) => v = v | (ub & 0xFF) + + Some(v) + } + + def encodeNonNegativeInteger(v: ULong): Unit = { + if v >>> 32 == 0 then + encodeNonNegativeInteger32Neg(v.toInt, false) + else + val hi = (v >>> 32).toInt + val lo = v.toInt + encodeNonNegativeInteger32Neg(hi, false) + + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? + bitStream.appendNBitZero(32 - nBits) + encodeNonNegativeInteger32Neg(lo, false) + } + + def decodeNonNegativeInteger(nBits: Int): Option[ULong] = { + if nBits <= 32 then + decodeNonNegativeInteger32Neg(nBits) match + case None() => return None() + case Some(lo) => + return Some(lo & 0xFFFFFFFFL) + + val hi_ret = decodeNonNegativeInteger32Neg(32) + val lo_ret = decodeNonNegativeInteger32Neg(nBits - 32) + + (hi_ret, lo_ret) match + case (Some(hi), Some(lo)) => + var v: ULong = hi & 0xFFFFFFFFL + v = v << nBits - 32L + v |= lo & 0xFFFFFFFFL + return Some(v) + case _ => return None() + //else + // return decodeNonNegativeInteger32Neg(v, nBits) + } + + def encodeNonNegativeIntegerNeg(v: ULong, negate: Boolean): Unit = { + if v >>> 32 == 0 then + encodeNonNegativeInteger32Neg(v.toInt, negate) + else + // TODO: Check Int/Long + val hi = (v >>> 32).toInt + var lo = v.toInt + encodeNonNegativeInteger32Neg(hi, negate) + + /*bug !!!!*/ + if negate then + lo = ~lo + val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) + bitStream.appendNBitZero(32 - nBits) + encodeNonNegativeInteger32Neg(lo, false) + } + + def BitStream_EncodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { + require(min <= max) + require(min <= v && v <= max) + + val range = max - min + if range == 0 then + return + + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) + bitStream.appendNBitZero(nRangeBits - nBits); + encodeNonNegativeInteger((v - min)) + } + + def BitStream_EncodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) + require(min <= v && v <= max) + + val range: ULong = (max - min) + if range == 0 then + return + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) + bitStream.appendNBitZero(nRangeBits - nBits) + encodeNonNegativeInteger(v - min) + } + + def BitStream_DecodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { + + val range: ULong = (max - min) + + // ASSERT_OR_RETURN_FALSE(min <= max); + + if range == 0 then + return Some(min) + + val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) + + decodeNonNegativeInteger(nRangeBits) match + case None() => return None() + case Some(ul) => return Some(ul + min) + } + + def BitStream_DecodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + + BitStream_DecodeConstraintWholeNumber(min.toLong, max.toLong) match + case None() => None() + case Some(l) => Some(l.toByte) + } + + def BitStream_DecodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { + + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(l) => Some(l.toShort) + } + + def BitStream_DecodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { + + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(l) => Some(l.toInt) + } + + def BitStream_DecodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toByte) + } + + def BitStream_DecodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toShort) + } + + def BitStream_DecodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { + + BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + case None() => None() + case Some(l) => Some(l.toInt) + } + + def BitStream_DecodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { + require(max >= 0 && max <= Long.MaxValue) + require(min >= 0 && min <= max) + + val range: ULong = max - min + + if range == 0 then + return Some(min) + + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + + decodeNonNegativeInteger(nRangeBits) match + case None() => None() + case Some(uv) => Some(uv + min) + } + + def BitStream_EncodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { + assert(v >= min) + val nBytes: Int = GetLengthInBytesOfUInt((v - min)) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + /* put required zeros*/ + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) + /*Encode number */ + encodeNonNegativeInteger((v - min)) + } + + def BitStream_EncodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { + assert(v >= min) + val nBytes: Int = GetLengthInBytesOfUInt(v - min) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + /* put required zeros*/ + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) + /*Encode number */ + encodeNonNegativeInteger(v - min) + } + + def BitStream_DecodeSemiConstraintWholeNumber(min: Long): Option[Long] = { + + var nBytes: Long = 0 + var v: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + + v += min + + return Some(v) + } + + def BitStream_DecodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { + + var nBytes: Long = 0 + var v: ULong = 0 + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + v += min + return Some(v) + } + + def BitStream_EncodeUnConstraintWholeNumber(v: Long): Unit = { + val nBytes: Int = GetLengthInBytesOfSInt(v) + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + /*8 bits, first bit is always 0*/ + + if v >= 0 then + bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) + encodeNonNegativeInteger(v) + else + bitStream.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) + encodeNonNegativeIntegerNeg((-v - 1), true) + } + + + def BitStream_DecodeUnConstraintWholeNumber(): Option[Long] = { + + var nBytes: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 255) match + case None() => return None() + case Some(l) => nBytes = l + + val valIsNegative: Boolean = bitStream.peekBit() + + var v: Long = if valIsNegative then Long.MaxValue else 0 + + var i: Long = 0 + while i < nBytes do + decreases(nBytes - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + + i += 1 + + return Some(v) + } + + @extern + def BitStream_EncodeReal(vVal: Double): Unit = { + BitStream_EncodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) + } + + private def BitStream_EncodeRealBitString(vVal: Long): Unit = { + // according to T-REC-X.690 2021 + + var v = vVal + + // 8.5.2 Plus Zero + if v == DoublePosZeroBitString then + BitStream_EncodeConstraintWholeNumber(0, 0, 0xFF) + return; + + // 8.5.3 Minus Zero + if v == DoubleNegZeroBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x43, 0, 0xFF) + return; + + // 8.5.9 SpecialRealValues (2021 standard) + if (v & ExpoBitMask) == ExpoBitMask then + + // 8.5.9 PLUS-INFINITY + if v == DoublePosInfBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x40, 0, 0xFF) + return; + + // 8.5.9 MINUS-INFINITY + else if v == DoubleNegInfBitString then + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x41, 0, 0xFF) + return; + + // 8.5.9 NOT-A-NUMBER + else + BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) + BitStream_EncodeConstraintWholeNumber(0x42, 0, 0xFF) + return; + + // 8.5.6 a) + // fixed encoding style to binary + // 8.5.7.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 + // 8.5.7.3 F value is always zero - bit 0x08 and 0x04 are always 0 + var header = 0x80 + + // 8.5.7.1 + if ((v & SignBitMask) == SignBitMask) { // check sign bit + header |= 0x40 + v &= InverseSignBitMask // clear sign bit + } + + val (exponent, mantissa) = CalculateMantissaAndExponent(v) + + val nManLen: Int = GetLengthInBytesOfUInt(mantissa) + assert(nManLen <= 7) // 52 bit + + val compactExp = RemoveLeadingFFBytesIfNegative(exponent) + val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) + assert(nExpLen >= 1 && nExpLen <= 2) + + // 8.5.7.4 + if nExpLen == 2 then + header |= 0x01 + else if nExpLen == 3 then // this will never happen with this implementation + header |= 0x02 + + /* encode length */ + BitStream_EncodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) + + /* encode header */ + BitStream_EncodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) + + /* encode exponent */ + if exponent >= 0 then + // fill with zeros to have a whole byte + bitStream.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) + encodeNonNegativeInteger(exponent) + else + encodeNonNegativeInteger(compactExp) + + /* encode mantissa */ + bitStream.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) + encodeNonNegativeInteger(mantissa) + } + + @extern + def BitStream_DecodeReal(): Option[Double] = { + BitStream_DecodeRealBitString() match + case None() => + None() + case Some(ll) => + Some(java.lang.Double.longBitsToDouble(ll)) + } + + private def BitStream_DecodeRealBitString(): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(length) => + // 8.5.2 Plus Zero + if length == 0 then + return Some(0) + + // invalid state + if length < 0 || length > DoubleMaxLengthOfSentBytes then + return None() + + bitStream.readByte() match + case None() => None() + case Some(header) => + // 8.5.6 a) + if (header.unsignedToInt & 0x80) != 0x80 then + return None() + + // 8.5.9 PLUS-INFINITY + if header == 0x40 then + Some(DoublePosInfBitString) + + // 8.5.9 MINUS-INFINITY + else if header == 0x41 then + Some(DoubleNegInfBitString) + + // 8.5.9 NOT-A-NUMBER + else if header == 0x42 then + Some(DoubleNotANumber) + + // 8.5.3 Minus Zero + else if header == 0x43 then + Some(DoubleNegZeroBitString) + + // Decode 8.5.7 + else + DecodeRealAsBinaryEncoding(length.toInt - 1, header) + } + + private def DecodeRealAsBinaryEncoding(lengthVal: Int, header: UByte): Option[Long] = { + require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte + require((header.unsignedToInt & 0x80) == 0x80) + require(bitStream.buf.length > lengthVal) + require(bitStream.currentByte < bitStream.buf.length - lengthVal) + + // 8.5.7.2 Base + val expFactor: Int = header.unsignedToInt match + case x if (x & 0x10) > 0 => 3 // 2^3 = 8 + case x if (x & 0x20) > 0 => 4 // 2^4 = 16 + case _ => 1 // 2^1 = 2 + + // 8.5.7.3 Factor F + val factor = 1 << ((header & 0x0C) >>> 2) + + // 8.5.7.4 Length of Exponent + val expLen = (header & 0x03) + 1 + + // sanity check + if expLen > lengthVal then + return None() + + // decode exponent + val expIsNegative = bitStream.peekBit() + var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 + + var i: Int = 0 + (while i < expLen do + decreases(expLen - i) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) + + i += 1 + ).invariant(i >= 0 && i <= expLen) + + // decode mantissa + val length = lengthVal - expLen + var N: ULong = 0 + var j: Int = 0 + (while j < length do + decreases(length - j) + + bitStream.readByte() match + case None() => return None() + case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) + + j += 1 + ).invariant(j >= 0 && j <= length) + + var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) + + // 8.5.7.1 Set Sign bit + if (header & 0x40) > 0 then + v |= SignBitMask + + Some(v) + } + + def BitStream_checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { + var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal + val tmp_currentByte: Int = bitStream.currentByte + val tmp_currentBit: Int = bitStream.currentBit + var tmp_byte: UByte = 0 + + if bitStream.currentByte.toLong * 8 + bitStream.currentBit + bit_terminated_pattern_size_in_bits.toInt > bitStream.buf.length.toLong * 8 then + return 0 + + var i: Int = 0 + while bit_terminated_pattern_size_in_bits >= 8 do + decreases(bit_terminated_pattern_size_in_bits) + + bitStream.readByte() match + case None() => return 0 + case Some(ub) => tmp_byte = ub + + bit_terminated_pattern_size_in_bits = 8 + if bit_terminated_pattern(i) != tmp_byte then + bitStream.currentByte = tmp_currentByte + bitStream.currentBit = tmp_currentBit + return 1 + i += 1 + + if bit_terminated_pattern_size_in_bits > 0 then + bitStream.readPartialByte(bit_terminated_pattern_size_in_bits) match + case None() => return 0 + case Some(ub) => tmp_byte = ub + + tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte + + if bit_terminated_pattern(i) != tmp_byte then + bitStream.currentByte = tmp_currentByte + bitStream.currentBit = tmp_currentBit + return 1 + + return 2 + } + + def BitStream_ReadBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { + var checkBitPatternPresentResult: Int = 0 + + var bitsRead: Int = 0 + + val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) + + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do + decreases(nMaxReadBits - bitsRead) + bitStream.readBit() match + case None() => return NoneMut() + case Some(bitVal) => + tmpStrm.appendBit(bitVal) + bitsRead += 1 + + if bitsRead < nMaxReadBits then + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then + checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + if checkBitPatternPresentResult != 2 then + return NoneMut() + + return SomeMut((tmpStrm.buf, bitsRead)) + } + + def BitStream_EncodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { + val cb = bitStream.currentBit + var ret: Boolean = false + + if cb == 0 then + ret = bitStream.currentByte + nCount <= bitStream.buf.length + if ret then + copyToArray(arr, bitStream.buf, bitStream.currentByte, nCount) + bitStream.currentByte += nCount + + else + ret = bitStream.appendByteArray(arr, nCount) + + ret + } + + def BitStream_DecodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { + val cb: Int = bitStream.currentBit + val arr: Array[UByte] = Array.fill(nCount + 1)(0) + + if cb == 0 then + if bitStream.currentByte + nCount > bitStream.buf.length then + return NoneMut() + + arrayCopyOffset(bitStream.buf, arr, bitStream.currentByte, bitStream.currentByte + nCount, 0) + bitStream.currentByte += nCount + + else + bitStream.readByteArray(nCount) match + case NoneMut() => return NoneMut() + case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) + + SomeMut(arr) + } + + def BitStream_EncodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { + var nRemainingItemsVar1: Int = nCount + var nCurBlockSize1: Int = 0 + var nCurOffset1: Int = 0 + var ret: Boolean = nCount >= 0 + + while nRemainingItemsVar1 >= 0x4000 && ret do + decreases(nRemainingItemsVar1) + if nRemainingItemsVar1 >= 0x10000 then + nCurBlockSize1 = 0x10000 + BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + else if nRemainingItemsVar1 >= 0xC000 then + nCurBlockSize1 = 0xC000 + BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + else if nRemainingItemsVar1 >= 0x8000 then + nCurBlockSize1 = 0x8000 + BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + else + nCurBlockSize1 = 0x4000 + BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + + var i1: Int = nCurOffset1 + while i1 < nCurBlockSize1 + nCurOffset1 && ret do + decreases(nCurBlockSize1 + nCurOffset1 - i1) + ret = bitStream.appendByte0(arr(i1)) + i1 += 1 + + nCurOffset1 += nCurBlockSize1 + nRemainingItemsVar1 -= nCurBlockSize1 + + if ret then + if nRemainingItemsVar1 <= 0x7F then + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) + + + var i1: Int = nCurOffset1 + while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do + decreases(nCurOffset1 + nRemainingItemsVar1 - i1) + ret = bitStream.appendByte0(arr(i1)) + i1 += 1 + + return ret + } + + def BitStream_DecodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) + + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + var nCount: Int = 0 + + var nLengthTmp1: Long = 0 + var nRemainingItemsVar1: Long = 0 + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + + // get header data + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + // 11xx_xxxx header, there is a next fragment + while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + + // get current block size + if nRemainingItemsVar1 == 0xC4 then + nCurBlockSize1 = 0x10000 + else if nRemainingItemsVar1 == 0xC3 then + nCurBlockSize1 = 0xC000 + else if nRemainingItemsVar1 == 0xC2 then + nCurBlockSize1 = 0x8000 + else if nRemainingItemsVar1 == 0xC1 then + nCurBlockSize1 = 0x4000 + else + return NoneMut() + + // fill current payload fragment into dest + var i1: Int = nCurOffset1.toInt + while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do + decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) + bitStream.readByte() match + case None() => return NoneMut() + case Some(ub) => arr(i1) = ub + i1 += 1 + + // sum combined length + nLengthTmp1 += nCurBlockSize1 + // set offset for next run + nCurOffset1 += nCurBlockSize1 + + // get next header + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower + if (nRemainingItemsVar1 & 0x80) > 0 then + + nRemainingItemsVar1 <<= 8 // put upper at correct position + // get size (lower byte) + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => + nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size + nRemainingItemsVar1 &= 0x7FFF // clear the control bit + + if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then + var i1: Int = nCurOffset1.toInt + + // fill last payload fragment into dest + while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do + decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) + bitStream.readByte() match + case None() => return NoneMut() + case Some(ub) => arr(i1) = ub + i1 += 1 + + // add remainingSize to already written size - this var holds the absolut number in all fragments + nLengthTmp1 += nRemainingItemsVar1 + + // resize output array and copy data + if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then + val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) + arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) + return SomeMut(newArr) + else + return NoneMut() + + NoneMut() + } + + def BitStream_EncodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax + + if ret then + if asn1SizeMax < 65536 then + if asn1SizeMin != asn1SizeMax then + BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + ret = BitStream_EncodeOctetString_no_length(arr, nCount) + + else + ret = BitStream_EncodeOctetString_fragmentation(arr, nCount) + + return ret + } + + def BitStream_DecodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + + if asn1SizeMax < 65536 then + var nCount: Int = 0 + if asn1SizeMin != asn1SizeMax then + BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + case None() => return NoneMut() + case Some(l) => nCount = l.toInt + else + nCount = asn1SizeMin.toInt + + if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then + return BitStream_DecodeOctetString_no_length(nCount) + else + return NoneMut() + + else + return BitStream_DecodeOctetString_fragmentation(asn1SizeMax) + + } + + def BitStream_EncodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + if asn1SizeMax < 65536 then + if asn1SizeMin != asn1SizeMax then + BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + + bitStream.appendBits(arr, nCount) + + else + var nRemainingItemsVar1: Long = nCount.toLong + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + while nRemainingItemsVar1 >= 0x4000 do + decreases(nRemainingItemsVar1) + + if nRemainingItemsVar1 >= 0x10000 then + nCurBlockSize1 = 0x10000 + BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + + else if nRemainingItemsVar1 >= 0xC000 then + nCurBlockSize1 = 0xC000 + BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + else if nRemainingItemsVar1 >= 0x8000 then + nCurBlockSize1 = 0x8000 + BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + else + nCurBlockSize1 = 0x4000 + BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + + val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) + bitStream.appendBits(t, nCurBlockSize1.toInt) + nCurOffset1 += nCurBlockSize1 + nRemainingItemsVar1 -= nCurBlockSize1 + + + if nRemainingItemsVar1 <= 0x7F then + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) + + val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) + bitStream.appendBits(t, nRemainingItemsVar1.toInt) + + true + } + + def BitStream_DecodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + require(asn1SizeMax <= Int.MaxValue) + + if (asn1SizeMax < 65536) { + var nCount: Long = 0 + if asn1SizeMin != asn1SizeMax then + BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + case None() => return NoneMut() + case Some(l) => nCount = l + else + nCount = asn1SizeMin + + return bitStream.readBits(nCount.toInt) + + } else { + var nRemainingItemsVar1: Long = 0 + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + var nLengthTmp1: Long = 0 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + if nRemainingItemsVar1 == 0xC4 then + nCurBlockSize1 = 0x10000 + else if nRemainingItemsVar1 == 0xC3 then + nCurBlockSize1 = 0xC000 + else if nRemainingItemsVar1 == 0xC2 then + nCurBlockSize1 = 0x8000 + else if nRemainingItemsVar1 == 0xC1 then + nCurBlockSize1 = 0x4000 + else + return NoneMut() + + /*COVERAGE_IGNORE*/ + if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then + return NoneMut() + /*COVERAGE_IGNORE*/ + + bitStream.readBits(nCurBlockSize1.toInt) match + case NoneMut() => return NoneMut() + case SomeMut(t) => + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) + nLengthTmp1 += nCurBlockSize1 + nCurOffset1 += nCurBlockSize1 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => nRemainingItemsVar1 = l + + if (nRemainingItemsVar1 & 0x80) > 0 then + nRemainingItemsVar1 <<= 8 + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return NoneMut() + case Some(l) => + nRemainingItemsVar1 |= l + nRemainingItemsVar1 &= 0x7FFF + + if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then + + bitStream.readBits(nRemainingItemsVar1.toInt) match + case NoneMut() => return NoneMut() + case SomeMut(t) => + arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) + nLengthTmp1 += nRemainingItemsVar1 + if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then + return SomeMut(arr) + } + return NoneMut() + } +} diff --git a/asn1scc/asn1jvm_Codec_ACN.scala b/asn1scc/asn1jvm_Codec_ACN.scala new file mode 100644 index 000000000..fe76f858f --- /dev/null +++ b/asn1scc/asn1jvm_Codec_ACN.scala @@ -0,0 +1,1580 @@ +package asn1scala + +import stainless.lang.StaticChecks.assert +import stainless.lang.{None, Option, Some} + +val FAILED_READ_ERR_CODE = 5400 + +// TODO remove / replace by invariant +def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { + assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) +} + +/** + * Get an instance of a ACN coded bitstream + * @param count of elements in underlaying buffer + * @return ACN coded bitstream + */ +def initACNCodec(count: Int): ACN = { + ACN(BitStream(Array.fill(count)(0))) +} + +case class ACN(bitStream: BitStream) extends Codec { + + def alignToByte(): Unit = { + if bitStream.currentBit != 0 then + bitStream.currentBit = 0 + bitStream.currentByte += 1 + CHECK_BIT_STREAM(bitStream) + } + + def alignToShort(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + CHECK_BIT_STREAM(bitStream) + } + + def alignToInt(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + CHECK_BIT_STREAM(bitStream) + } + + /*ACN Integer functions*/ + def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { + if encodedSizeInBits == 0 then + return + + /* Get number of bits*/ + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) + /* put required zeros*/ + // TODO what if nBits > encodedSizeInBits ?? + bitStream.appendNBitZero(encodedSizeInBits - nBits) + /*Encode number */ + encodeNonNegativeInteger(intVal) + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { + bitStream.appendByte0(intVal.toByte) + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { + val tmp: ULong = intVal + var mask: ULong = 0xFF + mask <<= (size - 1) * 8 + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + mask >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_SHORT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_INT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal: ULong, size: Int): Unit = { + var tmp: ULong = intVal + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = tmp.toByte + bitStream.appendByte0(ByteToEncode) + tmp >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 2) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 4) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + + def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { + decodeNonNegativeInteger(encodedSizeInBits) match + case None() => None() + case Some(ul) => Some(ul) + } + + + def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(ub) => Some(ub & 0xFF) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + ret <<= 8 + ret |= (ub & 0xFF) + i += 1 + + Some(ret) + } + + // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly + def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + var tmp: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + tmp = ub & 0xFF + tmp <<= i * 8 + ret |= tmp + i += 1 + + Some(ret) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(2) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(4) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { + val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) + bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) + ret + } + + + def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { + val MAX_BYTE_MASK = 0xFF00000000000000L + assert(nBytes <= 8) + + var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 - nBytes * 8) + + var i: Int = 0 + while i < nBytes do + val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + vv <<= 8 + i += 1 + } + + + def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte + + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(intVal, nBytes) + + CHECK_BIT_STREAM(bitStream) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { + var v: ULong = 0 + + bitStream.readByte() match + case None() => return None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + v = (v << 8) | (ub & 0xFF) + i += 1 + + Some(v) + } + + + def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { + if intVal >= 0 then + bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) + encodeNonNegativeInteger(intVal) + + else + bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) + encodeNonNegativeIntegerNeg(-intVal - 1, true) + + CHECK_BIT_STREAM(bitStream) + } + + + def enc_Int_TwosComplement_ConstSize_8(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_8(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_16(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_32(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_big_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_64(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_16(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_32(int2uint(intVal)) + } + + def enc_Int_TwosComplement_ConstSize_little_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) + } + + def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { + val valIsNegative: Boolean = bitStream.peekBit() + val nBytes: Int = encodedSizeInBits / 8 + val rstBits: Int = encodedSizeInBits % 8 + + var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 + + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << 8) | (ub & 0xFF) + i += 1 + + if rstBits > 0 then + bitStream.readPartialByte(rstBits.toByte) match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << rstBits) | (ub & 0xFF) + + Some(pIntVal) + } + + + def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 1)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + + def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { + val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte + + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(int2uint(intVal), nBytes) + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { + var v: ULong = 0 + var isNegative: Boolean = false + + bitStream.readByte() match + case None() => None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + if i == 0 && (ub & 0x80) > 0 then + v = Long.MaxValue + isNegative = true + + v = (v << 8) | (ub & 0xFF) + i += 1 + + if isNegative then + Some(-(~v) - 1) + else + Some(v) + } + + + //return values is in nibbles + def get_Int_Size_BCD(intVal: ULong): Int = { + var intVar = intVal + var ret: Int = 0 + while intVar > 0 do + intVar /= 10 + ret += 1 + + ret + } + + + def enc_Int_BCD_ConstSize(intVal: ULong, encodedSizeInNibbles: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) + + assert(100 >= encodedSizeInNibbles) + + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 + + assert(encodedSizeInNibbles >= totalNibbles) + + var i: Int = encodedSizeInNibbles - 1 + while i >= 0 do + bitStream.appendPartialByte(tmp(i).toByte, 4, false) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { + var ret: ULong = 0 + + var encodedSizeInNibblesVar = encodedSizeInNibbles + while encodedSizeInNibblesVar > 0 do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + ret *= 10 + ret += digit + encodedSizeInNibblesVar -= 1 + + Some(ret) + } + + + def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nNibbles: Int = get_Int_Size_BCD(intVal) + /* encode length */ + bitStream.appendByte0(nNibbles.toByte) + + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) + } + + + //encoding puts an 'F' at the end + def enc_Int_BCD_VarSize_NullTerminated(intVal: ULong): Unit = { + + val nNibbles: Int = get_Int_Size_BCD(intVal) + + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) + + bitStream.appendPartialByte(0xF, 4, false) + + CHECK_BIT_STREAM(bitStream) + } + + def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { + var ret: ULong = 0 + + while true do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + if (digit > 9) + return Some(ret) + + ret *= 10 + ret += digit + + Some(ret) + } + + + def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) + + assert(100 >= encodedSizeInBytes) + + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 + + assert(encodedSizeInBytes >= totalNibbles) + + var i = encodedSizeInBytes - 1 + while i >= 0 do + bitStream.appendByte0((tmp(i) + '0').toByte) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def enc_SInt_ASCII_ConstSize(intVal: Long, encodedSizeInBytes: Int): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) + } + + def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { + var encodedSizeInBytesVar = encodedSizeInBytes + var ret: ULong = 0 + + while encodedSizeInBytesVar > 0 do + bitStream.readByte() match + case None() => return None() + case Some(digit) => + assert(digit >= '0' && digit <= '9') + + ret *= 10 + ret += (digit.toInt - '0').toByte + + encodedSizeInBytesVar -= 1 + + Some(ret) + } + + def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(digit) => + var sign: Int = 1 + if digit == '+' then + sign = 1 + else if digit == '-' then + sign = -1 + else + assert(false) + + dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match + case None() => None() + case Some(ul) => Some(sign * ul) + } + + + def getIntegerDigits(intVal: ULong): (Array[Byte], Byte) = { + var intVar = intVal + val digitsArray100: Array[Byte] = Array.fill(100)(0) + val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) + var totalDigits: Byte = 0 + + + if intVar > 0 then + while intVar > 0 && totalDigits < 100 do + reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte + totalDigits = (totalDigits + 1).toByte + intVar /= 10 + + var i: Int = totalDigits - 1 + while i >= 0 do + digitsArray100(totalDigits - 1 - i) = reversedDigitsArray(i) + i -= 1 + + else + digitsArray100(0) = '0' + totalDigits = 1 + + (digitsArray100, totalDigits) + } + + + def enc_SInt_ASCII_VarSize_LengthEmbedded(intVal: Long): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + val (digitsArray100, nChars) = getIntegerDigits(absIntVal) + + /* encode length, plus 1 for sign */ + bitStream.appendByte0((nChars + 1).toByte) + + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) + + /* encode length */ + bitStream.appendByte0(nChars) + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) + } + + def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) + } + + + def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) + + var i: Int = 0 // TODO: size_t? + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 + + i = 0 + while i < null_characters_size do + bitStream.appendByte0(null_characters(i)) + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val absValue: ULong = if intVal >= 0 then intVal else -intVal + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) + } + + def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { + var digit: Byte = 0 + var ret: ULong = 0 + val tmp: Array[Byte] = Array.fill(10)(0) + + val sz: Int = if null_characters_size < 10 then null_characters_size else 10 + + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_characters_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 + + var i: Long = 0 + while !null_characters.sameElements(tmp) do + digit = tmp(0) + i += 1 + + j = 0 + while j < null_characters_size - 1 do + tmp(j) = tmp(j + 1) + j += 1 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_characters_size - 1) = ub + + digit = (digit - '0').toByte + + ret *= 10 + ret += digit + + Some(ret) + } + + + def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { + var isNegative: Boolean = false + + bitStream.readByte() match + case None() => None() + case Some(digit) => + assert(digit == '-' || digit == '+') + if digit == '-' then + isNegative = true + + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(ul) => Some(if isNegative then -ul else ul) + } + + + /* Boolean Decode */ + // TODO move to codec? + def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var pBoolValue: Boolean = true + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return None() + case Some(curByte) => + if curByte != patternToRead(i) then + pBoolValue = false + i += 1 + + if nRemainingBitsToRead > 0 then + bitStream.readPartialByte(nRemainingBitsToRead.toByte) match + case None() => return None() + case Some(curByte) => + if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then + pBoolValue = false + + Some(pBoolValue) + } + + // TODO move to codec? + def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return Left(FAILED_READ_ERR_CODE) + case Some(_) => i += 1 + + if nRemainingBitsToRead > 0 then + if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then + return Left(FAILED_READ_ERR_CODE) + + Right(0) + } + + + /*Real encoding functions*/ + def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array + + var i: Int = 0 + while i < 4 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_32_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1).toDouble) + } + + def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + + def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 0 + while i < 8 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_64_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 0 + while i < 8 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array + + var i: Int = 3 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_32_little_endian(): Option[Double] = { + dec_Real_IEEE754_32_little_endian_fp32() match + case None() => None() + case Some(f) => Some(f.toDouble) + } + + def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 3 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 7 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_64_little_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 7 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + /* String functions*/ + def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { + var i: Long = 0 + while i < max do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + } + + def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { + var i: Long = 0 + while (i < max) && (strVal(i.toInt) != '\u0000') do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + + i + } + + def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + bitStream.appendByte(null_character.toByte, false) + } + + def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + var i: Int = 0 + while i < null_character_size do + bitStream.appendByte(null_character(i), false) + i += 1 + } + + + def enc_String_Ascii_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + } + + def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_Ascii_private(max, strVal) + } + + def enc_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + var i: Int = 0 + while i < max do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + } + + def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { + var i: Int = 0 + while (i < max) && (strVal(i) != '\u0000') do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + + i + } + + + def enc_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def enc_IA5String_CharIndex_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + strVal(i) = decodedCharacter + i += 1 + Some(strVal) + } + + + def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, max) + } + + def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i <= max do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + if decodedCharacter != null_character then + strVal(i) = decodedCharacter + i += 1 + else + strVal(i) = 0x0 + return Some(strVal) + + None() + + } + + def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { + val sz: Int = if null_character_size < 10 then null_character_size else 10 + val tmp: Array[Byte] = Array.fill(10)(0) + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_character_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 + + + var i: Int = 0 + while i <= max && !null_character.sameElements(tmp) do + strVal(i) = tmp(0) + i += 1 + j = 0 + while j < null_character_size - 1 do + tmp(j) = tmp(j + 1) + j += 1 + + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_character_size - 1) = ub + + strVal(i) = 0x0 + + if !null_character.sameElements(tmp) then + return None() + + Some(strVal) + } + + + def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) + } + + def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_Ascii_private(max, if nCount <= max then nCount else max) + } + + def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match + case None() => return None() + case Some(charIndex) => + strVal(i) = allowedCharSet(charIndex.toInt) + i += 1 + + Some(strVal) + } + + def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, max, allowedCharSet) + } + + def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + + def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + /* Length Determinant functions*/ + def enc_Length(lengthValue: ULong, lengthSizeInBits: Int): Unit = { + /* encode length */ + enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) + } + + def dec_Length(lengthSizeInBits: Int): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) + } + + def milbus_encode(v: Long): Long = { + if v == 32 then 0 else v + } + + def milbus_decode(v: Long): Long = { + if v == 0 then 32 else v + } + + def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } +} diff --git a/asn1scc/asn1jvm_Codec_PER.scala b/asn1scc/asn1jvm_Codec_PER.scala new file mode 100644 index 000000000..8a497030c --- /dev/null +++ b/asn1scc/asn1jvm_Codec_PER.scala @@ -0,0 +1,13 @@ +package asn1scala + + +/** + * Get an instance of a PER coded bitstream + * @param count of elements in underlaying buffer + * @return PER coded bitstream + */ +def initPERCodec(count: Int): PER = { + PER(BitStream(Array.fill(count)(0))) +} + +case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scc/asn1jvm_Codec_UPER.scala b/asn1scc/asn1jvm_Codec_UPER.scala new file mode 100644 index 000000000..6e31d64f4 --- /dev/null +++ b/asn1scc/asn1jvm_Codec_UPER.scala @@ -0,0 +1,199 @@ +package asn1scala + +import stainless.math.BitVectors._ +import stainless.lang.{None => None, Option => Option, Some => Some, _} + +/** + * Get an instance of a UPER coded bitstream + * @param count of elements in underlaying buffer + * @return UPER coded bitstream + */ +def initUPERCodec(count: Int): UPER = { + UPER(BitStream(Array.fill(count)(0))) +} + +case class UPER(bitStream: BitStream) extends Codec { + + def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { + var lastOctet: Boolean = false + val tmp: Array[UByte] = Array.fill(16)(0) + var nSize: Int = 0 + + var siValue = siValueVal + var pSize = pSizeVal + + while !lastOctet do + decreases(siValue) + val curByte: UByte = (siValue % 128).toByte + siValue = siValue / 128 + lastOctet = siValue.toInt == 0 + tmp(nSize) = curByte + nSize += 1 + + var i: Int = 0 + while i < nSize do + decreases(nSize - i) + val curByte: UByte = if i == nSize - 1 then tmp(nSize - i - 1) else (tmp(nSize - i - 1) | 0x80).toByte + encodingBuf(pSize) = curByte + pSize += 1 + i += 1 + return pSize + } + + def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) + + i = 0 + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def relativeOID_encode(pVal: Asn1ObjectIdentifier): Unit = { + //a subIdentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded + //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { + var bLastOctet: Boolean = false + var curOctetValue: ULong = 0 + var siValue: ULong = 0 + var pRemainingOctets: Long = pRemainingOctetsVal + while pRemainingOctets > 0 && !bLastOctet do + decreases(pRemainingOctets) + bitStream.readByte() match + case None() => return None() + case Some(curByte) => + pRemainingOctets -= 1 + + bLastOctet = (curByte & 0x80) == 0 + curOctetValue = (curByte & 0x7F).toLong + siValue = siValue << 7 + siValue |= curOctetValue + + return Some((pRemainingOctets, siValue)) + } + + + def objectIdentifier_decode_length(): Option[Long] = { + var totalSize: Long = 0 + + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => totalSize = l + + if totalSize > 0x7F then + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => + totalSize <<= 8 + totalSize |= l + totalSize &= 0x7FFF + + return Some(totalSize) + } + + def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + + val pVal = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + + pVal.nCount = 2 + pVal.values(0) = si / 40 + pVal.values(1) = si % 40 + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + + } + + def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + } +} diff --git a/asn1scc/asn1jvm_Helper.scala b/asn1scc/asn1jvm_Helper.scala new file mode 100644 index 000000000..c2e1e400a --- /dev/null +++ b/asn1scc/asn1jvm_Helper.scala @@ -0,0 +1,196 @@ +package asn1scala + +import stainless.* +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} +import stainless.collection.* +import stainless.annotation.* +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +// all bits of the integer +val MASK_BYTE = 0xFF +val MASK_BYTE_L = 0xFFL +val MASK_SHORT_L = 0xFF_FFL +val MASK_INT_L = 0xFF_FF_FF_FFL + +// MSBs (neg bits of the integer) +val MASK_MSB_BYTE = 0x80L +val MASK_MSB_INT = 0x80_00_00_00L + +// pos bits of the integer +val MASK_POS_BYTE = 0x7FL +val MASK_POS_INT = 0x7F_FF_FF_FFL + +/* +* Meths to upcast unsigned integer data types on the JVM +*/ +extension (ub: UByte) { + def unsignedToLong: Long = ub & MASK_BYTE_L + def unsignedToInt: Int = ub.toInt & MASK_BYTE +} + +extension (us: UShort) { + def unsignedToLong: Long = us & MASK_SHORT_L +} + +extension (ui: UInt) { + def unsignedToLong: Long = ui & MASK_INT_L +} + +extension (i: Int) { + def toUnsignedByte: UByte = { + require(i >= 0 && i <= MASK_BYTE) + + if(i == MASK_MSB_BYTE) + (-MASK_MSB_BYTE).toByte + else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) + ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte + else + i.toByte + } +} + +extension (l: Long) { + def toUnsignedInt: UInt = { + require(l >= 0 && l <= MASK_INT_L) + + if(l == MASK_MSB_INT) + (-MASK_MSB_INT).toInt + else if ((l & MASK_MSB_INT) == MASK_MSB_INT) + ((l & MASK_POS_INT) - MASK_MSB_INT).toInt + else + l.toInt + } +} + +extension (b: Byte) { + def >>>>(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte + } + + def <<<<(i: Int): Byte = { + require(i >= 0 && i <= 8) + ((b.toInt << i) & MASK_BYTE).toUnsignedByte + } +} + + +def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { + if v >>> 8 == 0 then + (v, 0) + else if v >>> 16 == 0 then + (v >>> 8, 8) + else if v >>> 24 == 0 then + (v >>> 16, 16) + else + (v >>> 24, 24) +}.ensuring((v, n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24) + +def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { + require(vVal >= 0 && vVal <= 0xFF) + require(n >= 0 && n <= 8) + require(1<<(8-n) > vVal) + decreases(8-n) + + if(vVal == 0) then + n + else + GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) +} + +def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { + val (v, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) + n + GetNumberOfBitsInLastByteRec(v, 0) +} + +def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { + if v >>> 32 == 0 then + GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) + else + val h = (v >>> 32).toUnsignedInt + 32 + GetNumberOfBitsForNonNegativeInteger32(h) +}.ensuring(n => n >= 0 && n <= 64) + +def GetLengthInBytesOfUInt (v: ULong): Int = { + GetLengthInBytesOfSInt(v) // just call signed, is signed anyway +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) + +def GetLengthInBytesOfSInt (v: Long): Int = { + max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) + +/** +Binary encoding will be used +REAL = M*B^E +where +M = S*N*2^F + +ENCODING is done within three parts +part 1 is 1 byte header +part 2 is 1 or more byte for exponent +part 3 is 3 or more byte for mantissa (N) + +First byte +S :0-->+, S:1-->-1 +Base will be always be 2 (implied by 6th and 5th bit which are zero) +ab: F (0..3) +cd:00 --> 1 byte for exponent as 2's complement +cd:01 --> 2 byte for exponent as 2's complement +cd:10 --> 3 byte for exponent as 2's complement +cd:11 --> 1 byte for encoding the length of the exponent, then the exponent + +8 7 6 5 4 3 2 1 ++-+-+-+-+-+-+-+-+ +|1|S|0|0|a|b|c|d| ++-+-+-+-+-+-+-+-+ + **/ + +def CalculateMantissaAndExponent(doubleAsLong64: Long): (UInt, ULong) = { + require({ + val rawExp = (doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits + rawExp >= 0 &&& rawExp <= ((1 << 11) - 2) // 2046, 2047 is the infinity case - never end up here with infinity + }) + + val exponent: UInt = ((doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt + var mantissa: ULong = doubleAsLong64 & MantissaBitMask + mantissa = mantissa | MantissaExtraBit + + (exponent, mantissa) + +}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) + &&& m >= 0 &&& m <= MantissaBitMask) + +def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { + ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) +} + +/** +Helper function for REAL encoding + +Negative Ints always need 4 bytes of space, the ASN.1 standard compacts those numbers down +to 8, 16 or 24 bits depending on the leading bytes full of 1s. + +Example: +-4 in Int: 0b1111_..._1111_1100 +--> compacted to 0b1111_1100 + +The ASN.1 header holds the detail on how to interpret this number + **/ +def RemoveLeadingFFBytesIfNegative(v: Int): Int = { + if v >= 0 then + v + else if v >= Byte.MinValue then + v & 0xFF + else if v >= Short.MinValue then + v & 0xFF_FF + else if v >= -8_388_608 then + v & 0xFF_FF_FF + else + v +} + +sealed trait OptionMut[@mutable A] +case class NoneMut[@mutable A]() extends OptionMut[A] +case class SomeMut[@mutable A](v: A) extends OptionMut[A] diff --git a/asn1scc/asn1jvm_Verification.scala b/asn1scc/asn1jvm_Verification.scala new file mode 100644 index 000000000..c51aea393 --- /dev/null +++ b/asn1scc/asn1jvm_Verification.scala @@ -0,0 +1,193 @@ +package asn1scala + +import stainless.* +import stainless.lang.* +import stainless.collection.* +import stainless.annotation.{wrapping => _, *} +import stainless.proof.* +import stainless.math.* +import StaticChecks.* + +val masksc: Array[Byte] = Array( + 0x00, // / 0000 0000 / + -0x80, // / 1000 0000 / + -0x40, // / 1100 0000 / + -0x20, // / 1110 0000 / + -0x10, // / 1111 0000 / + -0x08, // / 1111 1000 / + -0x04, // / 1111 1100 / + -0x02, // / 1111 1110 / +) + +def arrayRangesEqOffset[T](a1: Array[T], a2: Array[T], fromA1: Int, toA1: Int, fromA2: Int): Boolean = { + require(0 <= fromA1 && fromA1 <= toA1) + require(toA1 <= a1.length) + require(0 <= fromA2 && fromA2 <= a2.length - (toA1 - fromA1)) + decreases(toA1 - fromA1) + if (fromA1 == toA1) true + else a1(fromA1) == a2(fromA2) && arrayRangesEqOffset(a1, a2, fromA1 + 1, toA1, fromA2 + 1) +} + +def arrayCopyOffset[T](src: Array[T], dst: Array[T], fromSrc: Int, toSrc: Int, fromDst: Int): Unit = { + require(0 <= fromSrc && fromSrc <= toSrc) + require(toSrc <= src.length) + require(0 <= fromDst && fromDst <= dst.length - (toSrc - fromSrc)) + decreases(toSrc - fromSrc) + + if (fromSrc < toSrc) { + dst(fromDst) = src(fromSrc) + arrayCopyOffset(src, dst, fromSrc + 1, toSrc, fromDst + 1) + } +} + +def arrayCopyOffsetLen[T](src: Array[T], dst: Array[T], fromSrc: Int, fromDst: Int, len: Int): Unit = { + require(0 <= len && len <= src.length && len <= dst.length) + require(0 <= fromSrc && fromSrc <= src.length - len) + require(0 <= fromDst && fromDst <= dst.length - len) + arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) +} + +def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { + require(0 <= len && len <= src.length) + require(0 <= startInDst && startInDst <= src.length - len) + require(src.length <= dst.length) + arrayCopyOffset(src, dst, 0, len, startInDst) +} + +def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = + a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) + +// TODO: Reimplement in terms of arrayRangesEqOffset +def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + decreases(to - from) + if (from == to) true + else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) +} +@opaque @inlineOnce +def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { + require(0 <= at && at < a.length) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(0 <= i && i <= at) + require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) + decreases(i) + if (i == 0) () + else rec(i - 1) + }.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) + } + + rec(at) +}.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) +} + +def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { + require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) + val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt + val arrPrefixEnd = (toBit / 8).toInt + val fromBitIx = (fromBit / 8).toInt + val toBitIx = (toBit / 8).toInt + (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) +} + +def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { + require(0 <= from && from <= to && to <= 7) + ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) +} + +def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { + require(a1.length <= a2.length) + require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) + require(fromBit < a1.length.toLong * 8) + (fromBit < toBit) ==> { + val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) + val restFrom = (fromBit % 8).toInt + val restTo = (toBit % 8).toInt + ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { + if (fromBitIx == toBitIx) { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) + } else { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && + ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) + } + } + } +} + +@opaque @inlineOnce +def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + require(from <= at && at < to) + require(arrayPrefix(a1, a2, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= at) + require(arrayPrefix(a1, a2, i, to)) + decreases(to - i) + if (i == at) () + else rec(i + 1) + }.ensuring { _ => + a1(at) == a2(at) + } + + rec(from) +}.ensuring(_ => a1(at) == a2(at)) + +@opaque @inlineOnce +def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to < a1.length) + require(arrayPrefix(a1, a2, from, to)) + require(a1(to) == a2(to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= to) + require(arrayPrefix(a1, a2, i, to + 1)) + decreases(i) + if (i == from) () + else { + arrayPrefixImpliesEq(a1, a2, from, i - 1, to) + rec(i - 1) + } + }.ensuring { _ => + arrayPrefix(a1, a2, from, to + 1) + } + + rec(to) +}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) + +@opaque @inlineOnce +def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { + require(0 <= from && from <= mid && mid <= to) + require(a1.length <= a2.length && a2.length <= a3.length) + require(mid <= a1.length && to <= a2.length) + require(arrayPrefix(a1, a2, from, mid)) + require(arrayPrefix(a2, a3, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= mid) + require(arrayPrefix(a1, a2, i, mid)) + require(arrayPrefix(a2, a3, i, to)) + require(arrayPrefix(a1, a3, from, i)) + decreases(to - i) + if (i == mid) () + else { + arrayPrefixAppend(a1, a3, from, i) + rec(i + 1) + } + }.ensuring { _ => + arrayPrefix(a1, a3, from, mid) + } + rec(from) +}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index c8fb804a7..dcba42c18 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -8,6 +8,12 @@ + + + + + + @@ -82,12 +88,6 @@ - - asn1jvm_encoding_uper.scala - - - asn1jvm_encoding.scala - asn1jvm.scala @@ -97,15 +97,6 @@ stainless-library_2.13-0.9.7.jar - - asn1jvm_encoding_acn.scala - - - stainless_utils.scala - - - asn1jvm_unsigned.scala - asn1jvm_Bitstream.scala From 1e23e0a91b31674ffff5fb10bcb6f30bbbfa95b4 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 30 Oct 2023 16:34:49 +0100 Subject: [PATCH 058/174] correct indent --- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 2922 ++++++++--------- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 346 +- .../asn1scala/asn1jvm_Verification.scala | 276 +- 3 files changed, 1772 insertions(+), 1772 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index b95b75fe1..048105da9 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -7,7 +7,7 @@ val FAILED_READ_ERR_CODE = 5400 // TODO remove / replace by invariant def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { - assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) + assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) } /** @@ -16,1565 +16,1565 @@ def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { * @return ACN coded bitstream */ def initACNCodec(count: Int): ACN = { - ACN(BitStream(Array.fill(count)(0))) + ACN(BitStream(Array.fill(count)(0))) } case class ACN(bitStream: BitStream) extends Codec { - def alignToByte(): Unit = { - if bitStream.currentBit != 0 then - bitStream.currentBit = 0 - bitStream.currentByte += 1 - CHECK_BIT_STREAM(bitStream) - } - - def alignToShort(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT - CHECK_BIT_STREAM(bitStream) - } - - def alignToInt(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT - CHECK_BIT_STREAM(bitStream) - } - - /*ACN Integer functions*/ - def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { - if encodedSizeInBits == 0 then - return - - /* Get number of bits*/ - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) - /* put required zeros*/ - // TODO what if nBits > encodedSizeInBits ?? - bitStream.appendNBitZero(encodedSizeInBits - nBits) - /*Encode number */ - encodeNonNegativeInteger(intVal) - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { - bitStream.appendByte0(intVal.toByte) - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { - val tmp: ULong = intVal - var mask: ULong = 0xFF - mask <<= (size - 1) * 8 - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) - mask >>>= 8 - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_SHORT) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_32(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_INT) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_64(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_LONG) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal: ULong, size: Int): Unit = { - var tmp: ULong = intVal - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = tmp.toByte - bitStream.appendByte0(ByteToEncode) - tmp >>>= 8 - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 2) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_32(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 4) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_64(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) - } - - - def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { - decodeNonNegativeInteger(encodedSizeInBits) match - case None() => None() - case Some(ul) => Some(ul) - } - - - def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(ub) => Some(ub & 0xFF) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { - var ret: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - ret <<= 8 - ret |= (ub & 0xFF) - i += 1 - - Some(ret) - } - - // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly - def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { - var ret: ULong = 0 - var tmp: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - tmp = ub & 0xFF - tmp <<= i * 8 - ret |= tmp - i += 1 - - Some(ret) - } + def alignToByte(): Unit = { + if bitStream.currentBit != 0 then + bitStream.currentBit = 0 + bitStream.currentByte += 1 + CHECK_BIT_STREAM(bitStream) + } + + def alignToShort(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + CHECK_BIT_STREAM(bitStream) + } + + def alignToInt(): Unit = { + alignToByte() + bitStream.currentByte = ((bitStream.currentByte + + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + CHECK_BIT_STREAM(bitStream) + } + + /*ACN Integer functions*/ + def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { + if encodedSizeInBits == 0 then + return + + /* Get number of bits*/ + val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) + /* put required zeros*/ + // TODO what if nBits > encodedSizeInBits ?? + bitStream.appendNBitZero(encodedSizeInBits - nBits) + /*Encode number */ + encodeNonNegativeInteger(intVal) + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { + bitStream.appendByte0(intVal.toByte) + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { + val tmp: ULong = intVal + var mask: ULong = 0xFF + mask <<= (size - 1) * 8 + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + mask >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_SHORT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_INT) + } + + def enc_Int_PositiveInteger_ConstSize_big_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal: ULong, size: Int): Unit = { + var tmp: ULong = intVal + + var i: Int = 0 + while i < size do + val ByteToEncode: Byte = tmp.toByte + bitStream.appendByte0(ByteToEncode) + tmp >>>= 8 + i += 1 + + CHECK_BIT_STREAM(bitStream) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 2) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_32(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 4) + } + + def enc_Int_PositiveInteger_ConstSize_little_endian_64(intVal: ULong): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) + } + + + def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { + decodeNonNegativeInteger(encodedSizeInBits) match + case None() => None() + case Some(ul) => Some(ul) + } + + + def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(ub) => Some(ub & 0xFF) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + ret <<= 8 + ret |= (ub & 0xFF) + i += 1 + + Some(ret) + } + + // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly + def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { + var ret: ULong = 0 + var tmp: ULong = 0 + + var i: Int = 0 + while i < SizeInBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + tmp = ub & 0xFF + tmp <<= i * 8 + ret |= tmp + i += 1 - def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_little_endian_N(2) - } + Some(ret) + } - def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_little_endian_N(4) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { - val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) - bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - ret - } + def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(2) + } + def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize_little_endian_N(4) + } - def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { - val MAX_BYTE_MASK = 0xFF00000000000000L - assert(nBytes <= 8) + def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { + val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) + bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) + ret + } - var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 - nBytes * 8) - - var i: Int = 0 - while i < nBytes do - val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) - vv <<= 8 - i += 1 - } + def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { + val MAX_BYTE_MASK = 0xFF00000000000000L + assert(nBytes <= 8) - def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte - - /* encode length */ - bitStream.appendByte0(nBytes) - /* Encode integer data*/ - encode_UnsignedInteger(intVal, nBytes) - - CHECK_BIT_STREAM(bitStream) - } + var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 - nBytes * 8) - def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { - var v: ULong = 0 - - bitStream.readByte() match - case None() => return None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - v = (v << 8) | (ub & 0xFF) - i += 1 - - Some(v) - } - - - def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { - if intVal >= 0 then - bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) - encodeNonNegativeInteger(intVal) - - else - bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) - encodeNonNegativeIntegerNeg(-intVal - 1, true) - - CHECK_BIT_STREAM(bitStream) - } - - - def enc_Int_TwosComplement_ConstSize_8(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_8(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_16(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_16(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_32(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_32(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_64(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_64(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_16(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_16(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_32(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_32(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_64(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) - } - - def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { - val valIsNegative: Boolean = bitStream.peekBit() - val nBytes: Int = encodedSizeInBits / 8 - val rstBits: Int = encodedSizeInBits % 8 - - var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 - - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << 8) | (ub & 0xFF) - i += 1 - - if rstBits > 0 then - bitStream.readPartialByte(rstBits.toByte) match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << rstBits) | (ub & 0xFF) - - Some(pIntVal) - } - - - def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 1)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) - } - - - def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { - val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte - - /* encode length */ - bitStream.appendByte0(nBytes) - /* Encode integer data*/ - encode_UnsignedInteger(int2uint(intVal), nBytes) - - CHECK_BIT_STREAM(bitStream) - } - - - def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { - var v: ULong = 0 - var isNegative: Boolean = false - - bitStream.readByte() match - case None() => None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - if i == 0 && (ub & 0x80) > 0 then - v = Long.MaxValue - isNegative = true - - v = (v << 8) | (ub & 0xFF) - i += 1 - - if isNegative then - Some(-(~v) - 1) - else - Some(v) - } - - - //return values is in nibbles - def get_Int_Size_BCD(intVal: ULong): Int = { - var intVar = intVal - var ret: Int = 0 - while intVar > 0 do - intVar /= 10 - ret += 1 + var i: Int = 0 + while i < nBytes do + val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte + bitStream.appendByte0(ByteToEncode) + vv <<= 8 + i += 1 + } - ret - } + def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte - def enc_Int_BCD_ConstSize(intVal: ULong, encodedSizeInNibbles: Int): Unit = { - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(intVal, nBytes) - assert(100 >= encodedSizeInNibbles) + CHECK_BIT_STREAM(bitStream) + } - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 + def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { + var v: ULong = 0 - assert(encodedSizeInNibbles >= totalNibbles) + bitStream.readByte() match + case None() => return None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + v = (v << 8) | (ub & 0xFF) + i += 1 - var i: Int = encodedSizeInNibbles - 1 - while i >= 0 do - bitStream.appendPartialByte(tmp(i).toByte, 4, false) - i -= 1 + Some(v) + } - CHECK_BIT_STREAM(bitStream) - } + def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { + if intVal >= 0 then + bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) + encodeNonNegativeInteger(intVal) - def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { - var ret: ULong = 0 + else + bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) + encodeNonNegativeIntegerNeg(-intVal - 1, true) - var encodedSizeInNibblesVar = encodedSizeInNibbles - while encodedSizeInNibblesVar > 0 do - bitStream.readPartialByte(4) match - case None() => return None() - case Some(digit) => - ret *= 10 - ret += digit - encodedSizeInNibblesVar -= 1 + CHECK_BIT_STREAM(bitStream) + } - Some(ret) - } + def enc_Int_TwosComplement_ConstSize_8(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_8(int2uint(intVal)) + } - def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val nNibbles: Int = get_Int_Size_BCD(intVal) - /* encode length */ - bitStream.appendByte0(nNibbles.toByte) + def enc_Int_TwosComplement_ConstSize_big_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_16(int2uint(intVal)) + } - /* Encode Number */ - enc_Int_BCD_ConstSize(intVal, nNibbles) + def enc_Int_TwosComplement_ConstSize_big_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_32(int2uint(intVal)) + } - CHECK_BIT_STREAM(bitStream) - } + def enc_Int_TwosComplement_ConstSize_big_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_big_endian_64(int2uint(intVal)) + } + def enc_Int_TwosComplement_ConstSize_little_endian_16(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_16(int2uint(intVal)) + } - def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) - } + def enc_Int_TwosComplement_ConstSize_little_endian_32(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_32(int2uint(intVal)) + } + def enc_Int_TwosComplement_ConstSize_little_endian_64(intVal: Long): Unit = { + enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) + } - //encoding puts an 'F' at the end - def enc_Int_BCD_VarSize_NullTerminated(intVal: ULong): Unit = { + def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { + val valIsNegative: Boolean = bitStream.peekBit() + val nBytes: Int = encodedSizeInBits / 8 + val rstBits: Int = encodedSizeInBits % 8 - val nNibbles: Int = get_Int_Size_BCD(intVal) + var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 - /* Encode Number */ - enc_Int_BCD_ConstSize(intVal, nNibbles) + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << 8) | (ub & 0xFF) + i += 1 - bitStream.appendPartialByte(0xF, 4, false) + if rstBits > 0 then + bitStream.readPartialByte(rstBits.toByte) match + case None() => return None() + case Some(ub) => + pIntVal = (pIntVal << rstBits) | (ub & 0xFF) + + Some(pIntVal) + } + + + def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 1)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 2)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(ul) => Some(uint2int(ul, 4)) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + } + + + def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { + val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte + + /* encode length */ + bitStream.appendByte0(nBytes) + /* Encode integer data*/ + encode_UnsignedInteger(int2uint(intVal), nBytes) + + CHECK_BIT_STREAM(bitStream) + } + + + def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { + var v: ULong = 0 + var isNegative: Boolean = false + + bitStream.readByte() match + case None() => None() + case Some(nBytes) => + var i: Int = 0 + while i < nBytes do + bitStream.readByte() match + case None() => return None() + case Some(ub) => + if i == 0 && (ub & 0x80) > 0 then + v = Long.MaxValue + isNegative = true + + v = (v << 8) | (ub & 0xFF) + i += 1 + + if isNegative then + Some(-(~v) - 1) + else + Some(v) + } + + + //return values is in nibbles + def get_Int_Size_BCD(intVal: ULong): Int = { + var intVar = intVal + var ret: Int = 0 + while intVar > 0 do + intVar /= 10 + ret += 1 + + ret + } + + + def enc_Int_BCD_ConstSize(intVal: ULong, encodedSizeInNibbles: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) + + assert(100 >= encodedSizeInNibbles) + + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 + + assert(encodedSizeInNibbles >= totalNibbles) + + var i: Int = encodedSizeInNibbles - 1 + while i >= 0 do + bitStream.appendPartialByte(tmp(i).toByte, 4, false) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } - CHECK_BIT_STREAM(bitStream) - } - def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { - var ret: ULong = 0 + def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { + var ret: ULong = 0 + + var encodedSizeInNibblesVar = encodedSizeInNibbles + while encodedSizeInNibblesVar > 0 do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + ret *= 10 + ret += digit + encodedSizeInNibblesVar -= 1 - while true do - bitStream.readPartialByte(4) match - case None() => return None() - case Some(digit) => - if (digit > 9) - return Some(ret) + Some(ret) + } - ret *= 10 - ret += digit - Some(ret) - } + def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val nNibbles: Int = get_Int_Size_BCD(intVal) + /* encode length */ + bitStream.appendByte0(nNibbles.toByte) + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) - def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) + CHECK_BIT_STREAM(bitStream) + } - assert(100 >= encodedSizeInBytes) - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 + def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) + } - assert(encodedSizeInBytes >= totalNibbles) - var i = encodedSizeInBytes - 1 - while i >= 0 do - bitStream.appendByte0((tmp(i) + '0').toByte) - i -= 1 + //encoding puts an 'F' at the end + def enc_Int_BCD_VarSize_NullTerminated(intVal: ULong): Unit = { + + val nNibbles: Int = get_Int_Size_BCD(intVal) - CHECK_BIT_STREAM(bitStream) - } + /* Encode Number */ + enc_Int_BCD_ConstSize(intVal, nNibbles) + bitStream.appendPartialByte(0xF, 4, false) - def enc_SInt_ASCII_ConstSize(intVal: Long, encodedSizeInBytes: Int): Unit = { - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + CHECK_BIT_STREAM(bitStream) + } + + def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { + var ret: ULong = 0 + + while true do + bitStream.readPartialByte(4) match + case None() => return None() + case Some(digit) => + if (digit > 9) + return Some(ret) - /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + ret *= 10 + ret += digit - enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) - } + Some(ret) + } - def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { - var encodedSizeInBytesVar = encodedSizeInBytes - var ret: ULong = 0 - while encodedSizeInBytesVar > 0 do - bitStream.readByte() match - case None() => return None() - case Some(digit) => - assert(digit >= '0' && digit <= '9') + def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { + var intVar = intVal + var totalNibbles: Int = 0 + val tmp: Array[UByte] = Array.fill(100)(0) - ret *= 10 - ret += (digit.toInt - '0').toByte + assert(100 >= encodedSizeInBytes) - encodedSizeInBytesVar -= 1 + while intVar > 0 do + tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] + totalNibbles += 1 + intVar /= 10 - Some(ret) - } + assert(encodedSizeInBytes >= totalNibbles) - def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { - bitStream.readByte() match - case None() => None() + var i = encodedSizeInBytes - 1 + while i >= 0 do + bitStream.appendByte0((tmp(i) + '0').toByte) + i -= 1 + + CHECK_BIT_STREAM(bitStream) + } + + + def enc_SInt_ASCII_ConstSize(intVal: Long, encodedSizeInBytes: Int): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') + + enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) + } + + def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { + var encodedSizeInBytesVar = encodedSizeInBytes + var ret: ULong = 0 + + while encodedSizeInBytesVar > 0 do + bitStream.readByte() match + case None() => return None() case Some(digit) => - var sign: Int = 1 - if digit == '+' then - sign = 1 - else if digit == '-' then - sign = -1 - else - assert(false) + assert(digit >= '0' && digit <= '9') - dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match - case None() => None() - case Some(ul) => Some(sign * ul) - } + ret *= 10 + ret += (digit.toInt - '0').toByte + encodedSizeInBytesVar -= 1 - def getIntegerDigits(intVal: ULong): (Array[Byte], Byte) = { - var intVar = intVal - val digitsArray100: Array[Byte] = Array.fill(100)(0) - val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) - var totalDigits: Byte = 0 + Some(ret) + } + def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(digit) => + var sign: Int = 1 + if digit == '+' then + sign = 1 + else if digit == '-' then + sign = -1 + else + assert(false) + + dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match + case None() => None() + case Some(ul) => Some(sign * ul) + } + + + def getIntegerDigits(intVal: ULong): (Array[Byte], Byte) = { + var intVar = intVal + val digitsArray100: Array[Byte] = Array.fill(100)(0) + val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) + var totalDigits: Byte = 0 + + + if intVar > 0 then + while intVar > 0 && totalDigits < 100 do + reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte + totalDigits = (totalDigits + 1).toByte + intVar /= 10 + + var i: Int = totalDigits - 1 + while i >= 0 do + digitsArray100(totalDigits - 1 - i) = reversedDigitsArray(i) + i -= 1 - if intVar > 0 then - while intVar > 0 && totalDigits < 100 do - reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte - totalDigits = (totalDigits + 1).toByte - intVar /= 10 + else + digitsArray100(0) = '0' + totalDigits = 1 - var i: Int = totalDigits - 1 - while i >= 0 do - digitsArray100(totalDigits - 1 - i) = reversedDigitsArray(i) - i -= 1 + (digitsArray100, totalDigits) + } - else - digitsArray100(0) = '0' - totalDigits = 1 - (digitsArray100, totalDigits) - } + def enc_SInt_ASCII_VarSize_LengthEmbedded(intVal: Long): Unit = { + val absIntVal: ULong = if intVal >= 0 then intVal else -intVal + val (digitsArray100, nChars) = getIntegerDigits(absIntVal) + /* encode length, plus 1 for sign */ + bitStream.appendByte0((nChars + 1).toByte) - def enc_SInt_ASCII_VarSize_LengthEmbedded(intVal: Long): Unit = { - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal - val (digitsArray100, nChars) = getIntegerDigits(absIntVal) + /* encode sign */ + bitStream.appendByte0(if intVal >= 0 then '+' else '-') - /* encode length, plus 1 for sign */ - bitStream.appendByte0((nChars + 1).toByte) + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 - /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + CHECK_BIT_STREAM(bitStream) + } - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 + def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) - CHECK_BIT_STREAM(bitStream) - } + /* encode length */ + bitStream.appendByte0(nChars) + /* encode digits */ + var i: Int = 0 + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 - def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val (digitsArray100, nChars) = getIntegerDigits(intVal) + CHECK_BIT_STREAM(bitStream) + } - /* encode length */ - bitStream.appendByte0(nChars) - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 - CHECK_BIT_STREAM(bitStream) - } + def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) + } + def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { + bitStream.readByte() match + case None() => None() + case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) + } - def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) - } - def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { - bitStream.readByte() match - case None() => None() - case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) - } + def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val (digitsArray100, nChars) = getIntegerDigits(intVal) + var i: Int = 0 // TODO: size_t? + while i < 100 && digitsArray100(i) != 0x0 do + bitStream.appendByte0(digitsArray100(i)) + i += 1 - def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { - val (digitsArray100, nChars) = getIntegerDigits(intVal) + i = 0 + while i < null_characters_size do + bitStream.appendByte0(null_characters(i)) + i += 1 - var i: Int = 0 // TODO: size_t? - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 + CHECK_BIT_STREAM(bitStream) + } - i = 0 - while i < null_characters_size do - bitStream.appendByte0(null_characters(i)) - i += 1 + def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { + val absValue: ULong = if intVal >= 0 then intVal else -intVal + bitStream.appendByte0(if intVal >= 0 then '+' else '-') - CHECK_BIT_STREAM(bitStream) - } + enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) + } - def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { - val absValue: ULong = if intVal >= 0 then intVal else -intVal - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { + var digit: Byte = 0 + var ret: ULong = 0 + val tmp: Array[Byte] = Array.fill(10)(0) - enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) - } + val sz: Int = if null_characters_size < 10 then null_characters_size else 10 - def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { - var digit: Byte = 0 - var ret: ULong = 0 - val tmp: Array[Byte] = Array.fill(10)(0) + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_characters_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 - val sz: Int = if null_characters_size < 10 then null_characters_size else 10 + var i: Long = 0 + while !null_characters.sameElements(tmp) do + digit = tmp(0) + i += 1 - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_characters_size do - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub + j = 0 + while j < null_characters_size - 1 do + tmp(j) = tmp(j + 1) j += 1 - var i: Long = 0 - while !null_characters.sameElements(tmp) do - digit = tmp(0) - i += 1 + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_characters_size - 1) = ub - j = 0 - while j < null_characters_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 + digit = (digit - '0').toByte - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(null_characters_size - 1) = ub + ret *= 10 + ret += digit - digit = (digit - '0').toByte + Some(ret) + } - ret *= 10 - ret += digit - Some(ret) - } + def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { + var isNegative: Boolean = false + bitStream.readByte() match + case None() => None() + case Some(digit) => + assert(digit == '-' || digit == '+') + if digit == '-' then + isNegative = true - def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { - var isNegative: Boolean = false + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(ul) => Some(if isNegative then -ul else ul) + } - bitStream.readByte() match - case None() => None() - case Some(digit) => - assert(digit == '-' || digit == '+') - if digit == '-' then - isNegative = true - - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(ul) => Some(if isNegative then -ul else ul) - } - - - /* Boolean Decode */ - // TODO move to codec? - def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var pBoolValue: Boolean = true - var i: Int = 0 - while i < nBytesToRead do - bitStream.readByte() match - case None() => return None() - case Some(curByte) => - if curByte != patternToRead(i) then - pBoolValue = false - i += 1 - - if nRemainingBitsToRead > 0 then - bitStream.readPartialByte(nRemainingBitsToRead.toByte) match - case None() => return None() - case Some(curByte) => - if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then - pBoolValue = false - - Some(pBoolValue) - } - - // TODO move to codec? - def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var i: Int = 0 - while i < nBytesToRead do - bitStream.readByte() match - case None() => return Left(FAILED_READ_ERR_CODE) - case Some(_) => i += 1 - - if nRemainingBitsToRead > 0 then - if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then - return Left(FAILED_READ_ERR_CODE) - - Right(0) - } - - - /*Real encoding functions*/ - def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array - - var i: Int = 0 - while i < 4 do - bitStream.appendByte0(b(i)) - i += 1 - } - - def dec_Real_IEEE754_32_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1).toDouble) - } - - def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) - } - - - def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 0 - while i < 8 do - bitStream.appendByte0(b(i)) - i += 1 - } - - def dec_Real_IEEE754_64_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 0 - while i < 8 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) - } - - - def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array - - var i: Int = 3 - while i >= 0 do - bitStream.appendByte0(b(i)) - i -= 1 - } - - def dec_Real_IEEE754_32_little_endian(): Option[Double] = { - dec_Real_IEEE754_32_little_endian_fp32() match - case None() => None() - case Some(f) => Some(f.toDouble) - } - - def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 3 - while i >= 0 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) - } - - def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 7 - while i >= 0 do - bitStream.appendByte0(b(i)) - i -= 1 - } - - def dec_Real_IEEE754_64_little_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 7 - while i >= 0 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) - } - - - /* String functions*/ - def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { - var i: Long = 0 - while i < max do - bitStream.appendByte(strVal(i.toInt), false) - i += 1 - } - - def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { - var i: Long = 0 - while (i < max) && (strVal(i.toInt) != '\u0000') do - bitStream.appendByte(strVal(i.toInt), false) - i += 1 - - i - } - - def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - bitStream.appendByte(null_character.toByte, false) - } - - def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - var i: Int = 0 - while i < null_character_size do - bitStream.appendByte(null_character(i), false) - i += 1 - } - - - def enc_String_Ascii_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - } - - def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_Ascii_private(max, strVal) - } - - def enc_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { - var i: Int = 0 - while i < max do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) - i += 1 - } - - def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { - var i: Int = 0 - while (i < max) && (strVal(i) != '\u0000') do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) - i += 1 - - i - } - - - def enc_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - - def enc_IA5String_CharIndex_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - def enc_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - - def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i < charactersToDecode do - bitStream.readByte() match - case None() => return None() - case Some(decodedCharacter) => - strVal(i) = decodedCharacter - i += 1 - Some(strVal) - } - - - def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { - dec_String_Ascii_private(max, max) - } - - def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i <= max do - bitStream.readByte() match - case None() => return None() - case Some(decodedCharacter) => - if decodedCharacter != null_character then - strVal(i) = decodedCharacter - i += 1 - else - strVal(i) = 0x0 - return Some(strVal) - - None() - - } - - def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { - val sz: Int = if null_character_size < 10 then null_character_size else 10 - val tmp: Array[Byte] = Array.fill(10)(0) - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_character_size do - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub + + /* Boolean Decode */ + // TODO move to codec? + def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var pBoolValue: Boolean = true + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return None() + case Some(curByte) => + if curByte != patternToRead(i) then + pBoolValue = false + i += 1 + + if nRemainingBitsToRead > 0 then + bitStream.readPartialByte(nRemainingBitsToRead.toByte) match + case None() => return None() + case Some(curByte) => + if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then + pBoolValue = false + + Some(pBoolValue) + } + + // TODO move to codec? + def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { + val nBytesToRead: Int = nBitsToRead / 8 + val nRemainingBitsToRead: Int = nBitsToRead % 8 + + var i: Int = 0 + while i < nBytesToRead do + bitStream.readByte() match + case None() => return Left(FAILED_READ_ERR_CODE) + case Some(_) => i += 1 + + if nRemainingBitsToRead > 0 then + if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then + return Left(FAILED_READ_ERR_CODE) + + Right(0) + } + + + /*Real encoding functions*/ + def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array + + var i: Int = 0 + while i < 4 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_32_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1).toDouble) + } + + def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 0 + while i < 4 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + + def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 0 + while i < 8 do + bitStream.appendByte0(b(i)) + i += 1 + } + + def dec_Real_IEEE754_64_big_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 0 + while i < 8 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i += 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array + + var i: Int = 3 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_32_little_endian(): Option[Double] = { + dec_Real_IEEE754_32_little_endian_fp32() match + case None() => None() + case Some(f) => Some(f.toDouble) + } + + def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { + val b: Array[Byte] = Array.fill(4)(0) + var i: Int = 3 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toInt + Some(java.lang.Float.intBitsToFloat(dat1)) + } + + def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + + var i: Int = 7 + while i >= 0 do + bitStream.appendByte0(b(i)) + i -= 1 + } + + def dec_Real_IEEE754_64_little_endian(): Option[Double] = { + val b: Array[Byte] = Array.fill(8)(0) + var i: Int = 7 + while i >= 0 do + bitStream.readByte() match + case None() => return None() + case Some(ub) => b(i) = ub + i -= 1 + + val dat1 = BigInt(b).toLong + Some(java.lang.Double.longBitsToDouble(dat1)) + } + + + /* String functions*/ + def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { + var i: Long = 0 + while i < max do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + } + + def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { + var i: Long = 0 + while (i < max) && (strVal(i.toInt) != '\u0000') do + bitStream.appendByte(strVal(i.toInt), false) + i += 1 + + i + } + + def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + bitStream.appendByte(null_character.toByte, false) + } + + def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + var i: Int = 0 + while i < null_character_size do + bitStream.appendByte(null_character(i), false) + i += 1 + } + + + def enc_String_Ascii_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + enc_String_Ascii_private(max, strVal) + } + + def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_Ascii_private(max, strVal) + } + + def enc_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + var i: Int = 0 + while i < max do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + } + + def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { + var i: Int = 0 + while (i < max) && (strVal(i) != '\u0000') do + val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) + BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + i += 1 + + i + } + + + def enc_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def enc_IA5String_CharIndex_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + def enc_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + val strLen: Int = strVal.length + BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + enc_String_CharIndex_private(max, allowedCharSet, strVal) + } + + + def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + strVal(i) = decodedCharacter + i += 1 + Some(strVal) + } + + + def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, max) + } + + def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i <= max do + bitStream.readByte() match + case None() => return None() + case Some(decodedCharacter) => + if decodedCharacter != null_character then + strVal(i) = decodedCharacter + i += 1 + else + strVal(i) = 0x0 + return Some(strVal) + + None() + + } + + def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { + val sz: Int = if null_character_size < 10 then null_character_size else 10 + val tmp: Array[Byte] = Array.fill(10)(0) + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + //read null_character_size characters into the tmp buffer + var j: Int = 0 + while j < null_character_size do + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(j) = ub + j += 1 + + + var i: Int = 0 + while i <= max && !null_character.sameElements(tmp) do + strVal(i) = tmp(0) + i += 1 + j = 0 + while j < null_character_size - 1 do + tmp(j) = tmp(j + 1) j += 1 + bitStream.readByte() match + case None() => return None() + case Some(ub) => tmp(null_character_size - 1) = ub + + strVal(i) = 0x0 + + if !null_character.sameElements(tmp) then + return None() + + Some(strVal) + } - var i: Int = 0 - while i <= max && !null_character.sameElements(tmp) do - strVal(i) = tmp(0) - i += 1 - j = 0 - while j < null_character_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 - - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(null_character_size - 1) = ub - - strVal(i) = 0x0 - - if !null_character.sameElements(tmp) then - return None() - - Some(strVal) - } - - - def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) - } - - def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_Ascii_private(max, if nCount <= max then nCount else max) - } - - def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i < charactersToDecode do - BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match - case None() => return None() - case Some(charIndex) => - strVal(i) = allowedCharSet(charIndex.toInt) - i += 1 - - Some(strVal) - } - - def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { - dec_String_CharIndex_private(max, max, allowedCharSet) - } - - def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) - } - - - def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) - } - - - def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) - } - - def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) - } - - - /* Length Determinant functions*/ - def enc_Length(lengthValue: ULong, lengthSizeInBits: Int): Unit = { - /* encode length */ - enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) - } - - def dec_Length(lengthSizeInBits: Int): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) - } - - def milbus_encode(v: Long): Long = { - if v == 32 then 0 else v - } - - def milbus_decode(v: Long): Long = { - if v == 0 then 32 else v - } - - def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } + + def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) + } + + def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_Ascii_private(max, if nCount <= max then nCount else max) + } + + def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { + val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var i: Int = 0 + while i < charactersToDecode do + BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match + case None() => return None() + case Some(charIndex) => + strVal(i) = allowedCharSet(charIndex.toInt) + i += 1 + + Some(strVal) + } + + def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, max, allowedCharSet) + } + + def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + + def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) + } + + def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + val allowedCharSet: Array[ASCIIChar] = Array( + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, + 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, + 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, + 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, + 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F + ) + BitStream_DecodeConstraintWholeNumber(min, max) match + case None() => None() + case Some(nCount) => + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + } + + + /* Length Determinant functions*/ + def enc_Length(lengthValue: ULong, lengthSizeInBits: Int): Unit = { + /* encode length */ + enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) + } + + def dec_Length(lengthSizeInBits: Int): Option[ULong] = { + dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) + } + + def milbus_encode(v: Long): Long = { + if v == 32 then 0 else v + } + + def milbus_decode(v: Long): Long = { + if v == 0 then 32 else v + } + + def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { + dec_Int_PositiveInteger_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_PositiveInteger_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { + dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_8() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_big_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_16() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_32() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { + dec_Int_TwosComplement_ConstSize_little_endian_64() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_Int_TwosComplement_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { + dec_Int_BCD_ConstSize(encodedSizeInNibbles) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { + dec_Int_BCD_VarSize_NullTerminated() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { + dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { + dec_SInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { + dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { + dec_UInt_ASCII_VarSize_LengthEmbedded() match + case None() => None() + case Some(v) => Some(v.toInt) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toByte) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toShort) + } + + def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match + case None() => None() + case Some(v) => Some(v.toInt) + } } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 1683265dd..7da6ea1a3 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -9,191 +9,191 @@ import stainless.lang.{None => None, Option => Option, Some => Some, _} * @return UPER coded bitstream */ def initUPERCodec(count: Int): UPER = { - UPER(BitStream(Array.fill(count)(0))) + UPER(BitStream(Array.fill(count)(0))) } case class UPER(bitStream: BitStream) extends Codec { - def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { - var lastOctet: Boolean = false - val tmp: Array[UByte] = Array.fill(16)(0) - var nSize: Int = 0 - - var siValue = siValueVal - var pSize = pSizeVal - - while !lastOctet do - decreases(siValue) - val curByte: UByte = (siValue % 128).toByte - siValue = siValue / 128 - lastOctet = siValue.toInt == 0 - tmp(nSize) = curByte - nSize += 1 - - var i: Int = 0 - while i < nSize do - decreases(nSize - i) - val curByte: UByte = if i == nSize - 1 then tmp(nSize - i - 1) else (tmp(nSize - i - 1) | 0x80).toByte - encodingBuf(pSize) = curByte - pSize += 1 - i += 1 - return pSize - } - - def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) - - i = 0 - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) - i += 1 - } - - def relativeOID_encode(pVal: Asn1ObjectIdentifier): Unit = { - //a subIdentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded - //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) - i += 1 - } - - def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { - var bLastOctet: Boolean = false - var curOctetValue: ULong = 0 - var siValue: ULong = 0 - var pRemainingOctets: Long = pRemainingOctetsVal - while pRemainingOctets > 0 && !bLastOctet do - decreases(pRemainingOctets) - bitStream.readByte() match - case None() => return None() - case Some(curByte) => - pRemainingOctets -= 1 - - bLastOctet = (curByte & 0x80) == 0 - curOctetValue = (curByte & 0x7F).toLong - siValue = siValue << 7 - siValue |= curOctetValue - - return Some((pRemainingOctets, siValue)) - } - - - def objectIdentifier_decode_length(): Option[Long] = { - var totalSize: Long = 0 - - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { + var lastOctet: Boolean = false + val tmp: Array[UByte] = Array.fill(16)(0) + var nSize: Int = 0 + + var siValue = siValueVal + var pSize = pSizeVal + + while !lastOctet do + decreases(siValue) + val curByte: UByte = (siValue % 128).toByte + siValue = siValue / 128 + lastOctet = siValue.toInt == 0 + tmp(nSize) = curByte + nSize += 1 + + var i: Int = 0 + while i < nSize do + decreases(nSize - i) + val curByte: UByte = if i == nSize - 1 then tmp(nSize - i - 1) else (tmp(nSize - i - 1) | 0x80).toByte + encodingBuf(pSize) = curByte + pSize += 1 + i += 1 + return pSize + } + + def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) + + i = 0 + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def relativeOID_encode(pVal: Asn1ObjectIdentifier): Unit = { + //a subIdentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded + //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) + val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) + var totalSize: Int = 0 + + var i: Int = 0 + + while i < pVal.nCount do + decreases(pVal.nCount - i) + totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) + i += 1 + + + if totalSize <= 0x7F then + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + else + bitStream.appendBit(true) + BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + + i = 0 + while i < totalSize do + decreases(totalSize - i) + bitStream.appendByte0(tmp(i)) + i += 1 + } + + def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { + var bLastOctet: Boolean = false + var curOctetValue: ULong = 0 + var siValue: ULong = 0 + var pRemainingOctets: Long = pRemainingOctetsVal + while pRemainingOctets > 0 && !bLastOctet do + decreases(pRemainingOctets) + bitStream.readByte() match case None() => return None() - case Some(l) => totalSize = l + case Some(curByte) => + pRemainingOctets -= 1 - if totalSize > 0x7F then - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return None() - case Some(l) => - totalSize <<= 8 - totalSize |= l - totalSize &= 0x7FFF + bLastOctet = (curByte & 0x80) == 0 + curOctetValue = (curByte & 0x7F).toLong + siValue = siValue << 7 + siValue |= curOctetValue - return Some(totalSize) - } + return Some((pRemainingOctets, siValue)) + } - def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - val pVal = ObjectIdentifier_Init() + def objectIdentifier_decode_length(): Option[Long] = { + var totalSize: Long = 0 - objectIdentifier_decode_length() match - case None() => return NoneMut() - case Some(l) => totalSize = l + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => totalSize = l + + if totalSize > 0x7F then + BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + case None() => return None() + case Some(l) => + totalSize <<= 8 + totalSize |= l + totalSize &= 0x7FFF + + return Some(totalSize) + } + + def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + + val pVal = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + objectIdentifier_subIdentifiers_decode(totalSize) match + case None() => return NoneMut() + case Some((l, ul)) => + totalSize = l + si = ul - objectIdentifier_subIdentifiers_decode(totalSize) match + pVal.nCount = 2 + pVal.values(0) = si / 40 + pVal.values(1) = si % 40 + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + + objectIdentifier_subIdentifiers_decode(totalSize) match case None() => return NoneMut() case Some((l, ul)) => - totalSize = l - si = ul - - pVal.nCount = 2 - pVal.values(0) = si / 40 - pVal.values(1) = si % 40 - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() - - } - - def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() - - objectIdentifier_decode_length() match + totalSize = l + si = ul + + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + + } + + def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { + var si: ULong = 0 + var totalSize: Long = 0 + val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() + + objectIdentifier_decode_length() match + case None() => return NoneMut() + case Some(l) => totalSize = l + + while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) + objectIdentifier_subIdentifiers_decode(totalSize) match case None() => return NoneMut() - case Some(l) => totalSize = l - - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() - } + case Some((l, ul)) => + totalSize = l + si = ul + pVal.values(pVal.nCount) = si + pVal.nCount += 1 + + //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH + if totalSize == 0 then + SomeMut(pVal) + else + NoneMut() + } } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala index 6d232572d..d9a1c3ba4 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala @@ -9,185 +9,185 @@ import stainless.math.* import StaticChecks.* val masksc: Array[Byte] = Array( - 0x00, // / 0000 0000 / - -0x80, // / 1000 0000 / - -0x40, // / 1100 0000 / - -0x20, // / 1110 0000 / - -0x10, // / 1111 0000 / - -0x08, // / 1111 1000 / - -0x04, // / 1111 1100 / - -0x02, // / 1111 1110 / + 0x00, // / 0000 0000 / + -0x80, // / 1000 0000 / + -0x40, // / 1100 0000 / + -0x20, // / 1110 0000 / + -0x10, // / 1111 0000 / + -0x08, // / 1111 1000 / + -0x04, // / 1111 1100 / + -0x02, // / 1111 1110 / ) def arrayRangesEqOffset[T](a1: Array[T], a2: Array[T], fromA1: Int, toA1: Int, fromA2: Int): Boolean = { - require(0 <= fromA1 && fromA1 <= toA1) - require(toA1 <= a1.length) - require(0 <= fromA2 && fromA2 <= a2.length - (toA1 - fromA1)) - decreases(toA1 - fromA1) - if (fromA1 == toA1) true - else a1(fromA1) == a2(fromA2) && arrayRangesEqOffset(a1, a2, fromA1 + 1, toA1, fromA2 + 1) + require(0 <= fromA1 && fromA1 <= toA1) + require(toA1 <= a1.length) + require(0 <= fromA2 && fromA2 <= a2.length - (toA1 - fromA1)) + decreases(toA1 - fromA1) + if (fromA1 == toA1) true + else a1(fromA1) == a2(fromA2) && arrayRangesEqOffset(a1, a2, fromA1 + 1, toA1, fromA2 + 1) } def arrayCopyOffset[T](src: Array[T], dst: Array[T], fromSrc: Int, toSrc: Int, fromDst: Int): Unit = { - require(0 <= fromSrc && fromSrc <= toSrc) - require(toSrc <= src.length) - require(0 <= fromDst && fromDst <= dst.length - (toSrc - fromSrc)) - decreases(toSrc - fromSrc) - - if (fromSrc < toSrc) { - dst(fromDst) = src(fromSrc) - arrayCopyOffset(src, dst, fromSrc + 1, toSrc, fromDst + 1) - } + require(0 <= fromSrc && fromSrc <= toSrc) + require(toSrc <= src.length) + require(0 <= fromDst && fromDst <= dst.length - (toSrc - fromSrc)) + decreases(toSrc - fromSrc) + + if (fromSrc < toSrc) { + dst(fromDst) = src(fromSrc) + arrayCopyOffset(src, dst, fromSrc + 1, toSrc, fromDst + 1) + } } def arrayCopyOffsetLen[T](src: Array[T], dst: Array[T], fromSrc: Int, fromDst: Int, len: Int): Unit = { - require(0 <= len && len <= src.length && len <= dst.length) - require(0 <= fromSrc && fromSrc <= src.length - len) - require(0 <= fromDst && fromDst <= dst.length - len) - arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) + require(0 <= len && len <= src.length && len <= dst.length) + require(0 <= fromSrc && fromSrc <= src.length - len) + require(0 <= fromDst && fromDst <= dst.length - len) + arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) } def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { - require(0 <= len && len <= src.length) - require(0 <= startInDst && startInDst <= src.length - len) - require(src.length <= dst.length) - arrayCopyOffset(src, dst, 0, len, startInDst) + require(0 <= len && len <= src.length) + require(0 <= startInDst && startInDst <= src.length - len) + require(src.length <= dst.length) + arrayCopyOffset(src, dst, 0, len, startInDst) } def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = - a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) + a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) // TODO: Reimplement in terms of arrayRangesEqOffset def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - decreases(to - from) - if (from == to) true - else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + decreases(to - from) + if (from == to) true + else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) } @opaque @inlineOnce def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { - require(0 <= at && at < a.length) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(0 <= i && i <= at) - require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) - decreases(i) - if (i == 0) () - else rec(i - 1) - }.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) - } - - rec(at) + require(0 <= at && at < a.length) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(0 <= i && i <= at) + require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) + decreases(i) + if (i == 0) () + else rec(i - 1) + }.ensuring { _ => + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) + } + + rec(at) }.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) + arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) } def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { - require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) - val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt - val arrPrefixEnd = (toBit / 8).toInt - val fromBitIx = (fromBit / 8).toInt - val toBitIx = (toBit / 8).toInt - (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) + require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) + val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt + val arrPrefixEnd = (toBit / 8).toInt + val fromBitIx = (fromBit / 8).toInt + val toBitIx = (toBit / 8).toInt + (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) } def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { - require(0 <= from && from <= to && to <= 7) - ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) + require(0 <= from && from <= to && to <= 7) + ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) } def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { - require(a1.length <= a2.length) - require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) - require(fromBit < a1.length.toLong * 8) - (fromBit < toBit) ==> { - val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) - val restFrom = (fromBit % 8).toInt - val restTo = (toBit % 8).toInt - ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { - if (fromBitIx == toBitIx) { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) - } else { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && - ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) - } - } - } + require(a1.length <= a2.length) + require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) + require(fromBit < a1.length.toLong * 8) + (fromBit < toBit) ==> { + val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) + val restFrom = (fromBit % 8).toInt + val restTo = (toBit % 8).toInt + ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { + if (fromBitIx == toBitIx) { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) + } else { + bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && + ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) + } + } + } } @opaque @inlineOnce def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - require(from <= at && at < to) - require(arrayPrefix(a1, a2, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= at) - require(arrayPrefix(a1, a2, i, to)) - decreases(to - i) - if (i == at) () - else rec(i + 1) - }.ensuring { _ => - a1(at) == a2(at) - } - - rec(from) + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to <= a1.length) + require(from <= at && at < to) + require(arrayPrefix(a1, a2, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= at) + require(arrayPrefix(a1, a2, i, to)) + decreases(to - i) + if (i == at) () + else rec(i + 1) + }.ensuring { _ => + a1(at) == a2(at) + } + + rec(from) }.ensuring(_ => a1(at) == a2(at)) @opaque @inlineOnce def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to < a1.length) - require(arrayPrefix(a1, a2, from, to)) - require(a1(to) == a2(to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= to) - require(arrayPrefix(a1, a2, i, to + 1)) - decreases(i) - if (i == from) () - else { - arrayPrefixImpliesEq(a1, a2, from, i - 1, to) - rec(i - 1) - } - }.ensuring { _ => - arrayPrefix(a1, a2, from, to + 1) - } - - rec(to) + require(0 <= from && from <= to) + require(a1.length <= a2.length) + require(to < a1.length) + require(arrayPrefix(a1, a2, from, to)) + require(a1(to) == a2(to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= to) + require(arrayPrefix(a1, a2, i, to + 1)) + decreases(i) + if (i == from) () + else { + arrayPrefixImpliesEq(a1, a2, from, i - 1, to) + rec(i - 1) + } + }.ensuring { _ => + arrayPrefix(a1, a2, from, to + 1) + } + + rec(to) }.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) @opaque @inlineOnce def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { - require(0 <= from && from <= mid && mid <= to) - require(a1.length <= a2.length && a2.length <= a3.length) - require(mid <= a1.length && to <= a2.length) - require(arrayPrefix(a1, a2, from, mid)) - require(arrayPrefix(a2, a3, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= mid) - require(arrayPrefix(a1, a2, i, mid)) - require(arrayPrefix(a2, a3, i, to)) - require(arrayPrefix(a1, a3, from, i)) - decreases(to - i) - if (i == mid) () - else { - arrayPrefixAppend(a1, a3, from, i) - rec(i + 1) - } - }.ensuring { _ => - arrayPrefix(a1, a3, from, mid) - } - rec(from) + require(0 <= from && from <= mid && mid <= to) + require(a1.length <= a2.length && a2.length <= a3.length) + require(mid <= a1.length && to <= a2.length) + require(arrayPrefix(a1, a2, from, mid)) + require(arrayPrefix(a2, a3, from, to)) + + @opaque @inlineOnce + def rec(i: Int): Unit = { + require(from <= i && i <= mid) + require(arrayPrefix(a1, a2, i, mid)) + require(arrayPrefix(a2, a3, i, to)) + require(arrayPrefix(a1, a3, from, i)) + decreases(to - i) + if (i == mid) () + else { + arrayPrefixAppend(a1, a3, from, i) + rec(i + 1) + } + }.ensuring { _ => + arrayPrefix(a1, a3, from, mid) + } + rec(from) }.ensuring(_ => arrayPrefix(a1, a3, from, mid)) From 713f582d62880451b71026fdfd1c6d24d84795dd Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 30 Oct 2023 17:17:33 +0100 Subject: [PATCH 059/174] rename ACN functions --- BackendAst/DAstACN.fs | 12 +++- StgScala/acn_scala.stg | 152 ++++++++++++++++++++--------------------- 2 files changed, 85 insertions(+), 79 deletions(-) diff --git a/BackendAst/DAstACN.fs b/BackendAst/DAstACN.fs index 33b990e67..98558ab70 100644 --- a/BackendAst/DAstACN.fs +++ b/BackendAst/DAstACN.fs @@ -149,9 +149,15 @@ let handleAlignemntForAsn1Types (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (code | Some al -> let alStr, nAligmVal = match al with - | AcnGenericTypes.NextByte -> "NextByte", 8I - | AcnGenericTypes.NextWord -> "NextWord", 16I - | AcnGenericTypes.NextDWord -> "NextDWord", 32I + | AcnGenericTypes.NextByte -> match ST.lang with + | Scala -> "Byte", 8I + | _ -> "NextByte", 8I + | AcnGenericTypes.NextWord -> match ST.lang with + | Scala -> "Short", 16I + | _ -> "NextWord", 16I + | AcnGenericTypes.NextDWord -> match ST.lang with + | Scala -> "Int", 32I + | _ -> "NextDWord", 32I let newFuncBody st errCode prms p = let content, ns1a = funcBody st errCode prms p let newContent = diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 34d8004de..bb26d6887 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -85,255 +85,255 @@ while ret.isRight && \< .asInstanceOf[Int] do >> alignToNext_encode(sMainBody, sAligmentValue, nAligmentValue) ::= << -Acn_AlignTo(pBitStrm, true) +codec.alignTo() >> alignToNext_decode(sMainBody, sAligmentValue, nAligmentValue) ::= << -Acn_AlignTo(pBitStrm, false) +codec.alignTo(pBitStrm) >> -PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize(pBitStrm, _encode(

)

, )" +PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize(_encode(

)

, )" PositiveInteger_ConstSize_decode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize(pBitStrm, ) match +codec.dec_Int_PositiveInteger_ConstSize) match case None() => return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_8(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_8(_encode(

)

)" PositiveInteger_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_8(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_8 return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_16(_encode(

)

)" PositiveInteger_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_big_endian_16 return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_32(_encode(

)

)" PositiveInteger_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_big_endian_32 return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_64(_encode(

)

)" PositiveInteger_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_big_endian_64() match case None() => return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_16(_encode(

)

)" PositiveInteger_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_little_endian_16() match case None() => return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_32(_encode(

)

)" PositiveInteger_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_little_endian_32() match case None() => return Left() case Some(x) =>

= x >> -PositiveInteger_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm, _encode(

)

)" +PositiveInteger_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_64(_encode(

)

)" PositiveInteger_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64(pBitStrm) match +codec.dec_Int_PositiveInteger_ConstSize_little_endian_64() match case None() => return Left() case Some(x) =>

= x >> -PositiveInteger_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= "Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" +PositiveInteger_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= "codec.enc_Int_PositiveInteger_VarSize_LengthEmbedded(_encode(

)

)" PositiveInteger_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= << -Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded(pBitStrm) match +codec.dec_Int_PositiveInteger_VarSize_LengthEmbedded() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize(pBitStrm, _encode(

)

, )" +TwosComplement_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize(_encode(

)

, )" TwosComplement_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize(pBitStrm, ) match +codec.dec_Int_TwosComplement_ConstSize() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_8(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_8(_encode(

)

)" TwosComplement_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_8(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_8() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_16(_encode(

)

)" TwosComplement_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_big_endian_16() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_32(_encode(

)

)" TwosComplement_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_big_endian_32() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_64(_encode(

)

)" TwosComplement_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_big_endian_64() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_16(_encode(

)

)" TwosComplement_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_little_endian_16() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_32(_encode(

)

)" TwosComplement_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32(pBitStrm) match +codec.dec_Int_TwosComplement_ConstSize_little_endian_32() match case None() => return Left() case Some(x) =>

= x >> -TwosComplement_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm, _encode(

)

)" +TwosComplement_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_64(_encode(

)

)" TwosComplement_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64(pBitStrm) +codec.dec_Int_TwosComplement_ConstSize_little_endian_64() case None() => return Left() case Some(x) =>

= x >> -TwosComplement_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" +TwosComplement_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_TwosComplement_VarSize_LengthEmbedded(_encode(

)

)" TwosComplement_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded(pBitStrm) +codec.dec_Int_TwosComplement_VarSize_LengthEmbedded() case None() => return Left() case Some(x) =>

= x >> -BCD_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= "Acn_Enc_Int_BCD_ConstSize(pBitStrm, _encode(

)

, )" +BCD_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= "codec.enc_Int_BCD_ConstSize(_encode(

)

, )" BCD_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= << -Acn_Dec_Int_BCD_ConstSize(pBitStrm, ) match +codec.dec_Int_BCD_ConstSize() match case None() => return Left() case Some(x) =>

= x >> -BCD_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_Int_BCD_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" +BCD_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_BCD_VarSize_LengthEmbedded(_encode(

)

)" BCD_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -Acn_Dec_Int_BCD_VarSize_LengthEmbedded(pBitStrm) +codec.dec_Int_BCD_VarSize_LengthEmbedded() case None() => return Left() case Some(x) =>

= x >> -BCD_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "Acn_Enc_Int_BCD_VarSize_NullTerminated(pBitStrm, _encode(

)

)" +BCD_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_BCD_VarSize_NullTerminated(_encode(

)

)" BCD_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -Acn_Dec_Int_BCD_VarSize_NullTerminated(pBitStrm) match +codec.dec_Int_BCD_VarSize_NullTerminated() match case None() => return Left() case Some(x) =>

= x >> -ASCII_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= "Acn_Enc_SInt_ASCII_ConstSize(pBitStrm, _encode(

)

, ) " +ASCII_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= "codec.enc_SInt_ASCII_ConstSize(_encode(

)

, ) " ASCII_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -Acn_Dec_SInt_ASCII_ConstSize(pBitStrm, ) match +codec.dec_SInt_ASCII_ConstSize() match case None() => return Left() case Some(x) =>

= x >> -ASCII_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "Acn_Enc_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm, _encode(

)

)" +ASCII_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_SInt_ASCII_VarSize_LengthEmbedded(_encode(

)

)" ASCII_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -Acn_Dec_SInt_ASCII_VarSize_LengthEmbedded(pBitStrm) match +codec.dec_SInt_ASCII_VarSize_LengthEmbedded() match case None() => return Left() case Some(x) =>

= x >> ASCII_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -Acn_Enc_SInt_ASCII_VarSize_NullTerminated(pBitStrm, _encode(

)

, (byte[]){}, ) +codec.enc_SInt_ASCII_VarSize_NullTerminated(_encode(

)

, (byte[]){}, ) >> ASCII_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -Acn_Dec_SInt_ASCII_VarSize_NullTerminated(pBitStrm, (byte[]){}, ) match +codec.dec_SInt_ASCII_VarSize_NullTerminated((byte[]){}, ) match case None() => return Left() case Some(x) =>

= x >> ASCII_UINT_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -Acn_Enc_UInt_ASCII_ConstSize(pBitStrm, _encode(

)

, ) +codec.enc_UInt_ASCII_ConstSize(_encode(

)

, ) >> ASCII_UINT_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -Acn_Dec_UInt_ASCII_ConstSize(pBitStrm, ) match +codec.dec_UInt_ASCII_ConstSize() match case None() => return Left() case Some(x) =>

= x >> ASCII_UINT_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -Acn_Enc_UInt_ASCII_VarSize_NullTerminated(pBitStrm, _encode(

)

, (byte[]){}, ) +codec.enc_UInt_ASCII_VarSize_NullTerminated(_encode(

)

, (byte[]){}, ) >> ASCII_UINT_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -Acn_Dec_UInt_ASCII_VarSize_NullTerminated(pBitStrm,

, (byte[]){}, ) match +codec.dec_UInt_ASCII_VarSize_NullTerminated(

, (byte[]){}, ) match case None() => return Left() case Some(x) =>

= x >> -Real_32_big_endian_encode(p, sSuffix, sErrCode) ::= "Acn_Enc_Real_IEEE754_32_big_endian(pBitStrm,

.toFloat)" +Real_32_big_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_big_endian(

.toFloat)" Real_32_big_endian_decode(p, sSuffix, sErrCode) ::= << -Acn_Dec_Real_IEEE754_32_big_endian(pBitStrm) match +codec.dec_Real_IEEE754_32_big_endian() match case None() => return Left() case Some(x) =>

= x >> -Real_64_big_endian_encode(p, sErrCode) ::= "Acn_Enc_Real_IEEE754_64_big_endian(pBitStrm,

)" +Real_64_big_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_big_endian(

)" Real_64_big_endian_decode(p, sErrCode) ::= << -Acn_Dec_Real_IEEE754_64_big_endian(pBitStrm) match +codec.dec_Real_IEEE754_64_big_endian(match case None() => return Left() case Some(x) =>

= x >> -Real_32_little_endian_encode(p, sSuffix, sErrCode) ::= "Acn_Enc_Real_IEEE754_32_little_endian(pBitStrm,

)" +Real_32_little_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_little_endian(

)" Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= << -Acn_Dec_Real_IEEE754_32_little_endian(pBitStrm) match +codec.dec_Real_IEEE754_32_little_endian() match case None() => return Left() case Some(x) =>

= x >> -Real_64_little_endian_encode(p, sErrCode) ::= "Acn_Enc_Real_IEEE754_64_little_endian(pBitStrm,

)" +Real_64_little_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_little_endian(

)" Real_64_little_endian_decode(p, sErrCode) ::= << -Acn_Dec_Real_IEEE754_64_little_endian(pBitStrm) match +codec.dec_Real_IEEE754_64_little_endian(match case None() => return Left() case Some(x) => @@ -445,9 +445,9 @@ if ret.isRight then >> /* Strings */ -Acn_String_Ascii_FixSize_encode(p, sErrCode, nAsn1Max) ::= "Acn_Enc_String_Ascii_FixSize(pBitStrm, ,

)" +Acn_String_Ascii_FixSize_encode(p, sErrCode, nAsn1Max) ::= "codec.enc_String_Ascii_FixSize(,

)" Acn_String_Ascii_FixSize_decode(p, sErrCode, nAsn1Max) ::= << -Acn_Dec_String_Ascii_FixSize(pBitStrm, ) match +codec.dec_String_Ascii_FixSize() match case None() => return Left() case Some(x) => @@ -455,28 +455,28 @@ Acn_Dec_String_Ascii_FixSize(pBitStrm, ) match >> Acn_String_Ascii_Null_Teminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm, , (byte[]){}, ,

) +codec.enc_String_Ascii_Null_Teminated_mult(, (byte[]){}, ,

) >> Acn_String_Ascii_Null_Teminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm, , (byte[]){}, ) match +codec.dec_String_Ascii_Null_Teminated_mult(, (byte[]){}, ) match case None() => return Left() case Some(x) =>

= x >> -Acn_String_Ascii_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld) ::= "Acn_Enc_String_Ascii_External_Field_Determinant(pBitStrm, ,

)" +Acn_String_Ascii_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld) ::= "codec.enc_String_Ascii_External_Field_Determinant(,

)" Acn_String_Ascii_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld) ::= << -Acn_Dec_String_Ascii_External_Field_Determinant(pBitStrm, , ) match +codec.dec_String_Ascii_External_Field_Determinant(, ) match case None() => return Left() case Some(x) =>

= x >> Acn_String_Ascii_Internal_Field_Determinant_encode(p, sErrCode, nAsn1Max, nAsn1Min, nInternalLengthDeterminantSizeInBits) ::= << -Acn_Enc_String_Ascii_Internal_Field_Determinant(pBitStrm, , ,

) +codec.enc_String_Ascii_Internal_Field_Determinant(, ,

) >> Acn_String_Ascii_Internal_Field_Determinant_decode(p, sErrCode, nAsn1Max, nAsn1Min, nInternalLengthDeterminantSizeInBits) ::= << -Acn_Dec_String_Ascii_Internal_Field_Determinant(pBitStrm, , ) match +codec.dec_String_Ascii_Internal_Field_Determinant(, ) match case None() => return Left() case Some(x) =>

= x >> @@ -487,35 +487,35 @@ static byte allowedCharSet[] = {}; wrap, anch Acn_String_CharIndex_FixSize_encode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Enc_String_CharIndex_FixSize(pBitStrm, , allowedCharSet, ,

) +codec.enc_String_CharIndex_FixSize(, allowedCharSet, ,

) >> Acn_String_CharIndex_FixSize_decode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Dec_String_CharIndex_FixSize(pBitStrm, , allowedCharSet, ) match +codec.dec_String_CharIndex_FixSize(, allowedCharSet, ) match case None() => return Left() case Some(x) =>

= x >> Acn_String_CharIndex_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Enc_String_CharIndex_External_Field_Determinant(pBitStrm, , allowedCharSet, ,

) +codec.enc_String_CharIndex_External_Field_Determinant(, allowedCharSet, ,

) >> Acn_String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Dec_String_CharIndex_External_Field_Determinant(pBitStrm, , allowedCharSet, , ) match +codec.dec_String_CharIndex_External_Field_Determinant(, allowedCharSet, , ) match case None() => return Left() case Some(x) =>

= x >> Acn_IA5String_CharIndex_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Enc_IA5String_CharIndex_External_Field_Determinant(pBitStrm, ,

) +codec.enc_IA5String_CharIndex_External_Field_Determinant(,

) >> Acn_IA5String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -Acn_Dec_IA5String_CharIndex_External_Field_Determinant(pBitStrm, , ) match +codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) match case None() => return Left() case Some(x) =>

= x >> From b94ee5b4ac871b7fd7cc037f702e0aa8c92dc937 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 30 Oct 2023 18:45:43 +0100 Subject: [PATCH 060/174] WIP: uper codec --- StgScala/test_cases_scala.stg | 4 +- StgScala/uper_scala.stg | 101 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 78 +- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 10 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 8 +- asn1scc/asn1jvm_Codec.scala | 1004 ----------- asn1scc/asn1jvm_Codec_ACN.scala | 1580 ----------------- asn1scc/asn1jvm_Codec_PER.scala | 13 - asn1scc/asn1jvm_Codec_UPER.scala | 199 --- asn1scc/asn1jvm_Helper.scala | 196 -- asn1scc/asn1jvm_Verification.scala | 193 -- asn1scc/asn1scc.fsproj | 39 +- 12 files changed, 121 insertions(+), 3304 deletions(-) delete mode 100644 asn1scc/asn1jvm_Codec.scala delete mode 100644 asn1scc/asn1jvm_Codec_ACN.scala delete mode 100644 asn1scc/asn1jvm_Codec_PER.scala delete mode 100644 asn1scc/asn1jvm_Codec_UPER.scala delete mode 100644 asn1scc/asn1jvm_Helper.scala delete mode 100644 asn1scc/asn1jvm_Verification.scala diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 6f106cbf7..6b9a99e51 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -69,9 +69,9 @@ bitStrm.attachBuffer(bitStrm.buf) // TODO: reset curBit, curByte instead? Codec_Decode_XER(sModName, sFuncName, sTasName, sEnc, sAmber) ::= << // test_cases_scala.stg:71 -ByteStream_AttachBuffer(bitStrm, encBuff, _REQUIRED_BYTES_FOR_ENCODING) +bitStrm.attachBuffer(encBuff, _REQUIRED_BYTES_FOR_ENCODING) // Decode value -(bitStrm) match +bitStrm.() match case Left(_) => return Left(2) case Right(pVal) => decodedPDU = pVal >> diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index ef79ab672..efe6489a0 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -3,14 +3,14 @@ rtlModuleName() ::= "" call_base_type_func_encode(p, sFuncName) ::= << -(

, pBitStrm, false) match +(

, codec, false) match // uper:6 case Right(retVal) => ret = Right(retVal) case Left(err) => return Left(err) >> call_base_type_func_decode(p, sFuncName) ::= << -(pBitStrm) match +codec.() match // uper:13 case Right(decData) =>

= decData case Left(err) => @@ -32,7 +32,7 @@ EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrc >> EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << -def (@annotation.unused : , @annotation.unused pBitStrm: BitStream, bCheckConstraints: Boolean): Either[ErrorCode, Int] = //uper:35 +def (@annotation.unused : , @annotation.unused codec: UPER, bCheckConstraints: Boolean): Either[ErrorCode, Int] = //uper:35 { var ret: Either[ErrorCode, Int] = Right(0) @@ -56,7 +56,7 @@ EmitTypeAssignment_def_decode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrc >> EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << -def (@annotation.unused pBitStrm: BitStream): Either[ErrorCode, ] = // uper:58 +def (@annotation.unused codec: UPER): Either[ErrorCode, ] = // uper:58 { var pVal: = () @@ -65,7 +65,7 @@ def (@annotation.unused pBitStrm: BitSt - (pVal) match + (pVal) match // uper:68 case Left(l) => Left(l) case Right(_) => Right(pVal) @@ -90,7 +90,7 @@ static byte allowedCharSet[] = {}; wrap, anch InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< int charIndex = GetCharIndex(

[], allowedCharSet, ); -BitStream_EncodeConstraintWholeNumber(pBitStrm, charIndex, 0, ) +codec.encodeConstraintWholeNumber(charIndex, 0, ) >> InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< @@ -102,11 +102,11 @@ if !worked then >> InternalItem_string_no_alpha_encode(p, sErrCode, i) ::=<< -BitStream_EncodeConstraintWholeNumber(pBitStrm,

(), 0, 127) +codec.encodeConstraintWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -BitStream_DecodeConstraintWholeNumberByte(pBitStrm, 0, 127) match +BitStream_DecodeConstraintWholeNumberByte(pBitStrm, 0, 127) match // uper:109 case Some(c) =>

() = c case None() => @@ -117,9 +117,12 @@ BitStream_DecodeConstraintWholeNumberByte(pBitStrm, 0, 127) match /*case: A:: = INTEGER (-5..20) */ -IntFullyConstraint_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= "BitStream_EncodeConstraintWholeNumber(pBitStrm,

, , )" +IntFullyConstraint_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << +codec.encodeConstraintWholeNumber(

, , ) +>> + IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:122 case Some(n) =>

= n case None() => @@ -128,11 +131,11 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match /*case: Positive fully constraint A:: = INTEGER (5..20) */ IntFullyConstraintPos_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -BitStream_EncodeConstraintPosWholeNumber(pBitStrm,

, , ) +codec.encodeConstraintPosWholeNumber(

, , ) >> IntFullyConstraintPos_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -BitStream_DecodeConstraintPosWholeNumber(pBitStrm, , ) match +codec.decodeConstraintPosWholeNumber(, ) match // uper:135 case Some(decPosNr) =>

= decPosNr case None() => @@ -142,7 +145,7 @@ BitStream_DecodeConstraintPosWholeNumber(pBitStrm, , ) mat /*case: A :: = INTEGER */ IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -BitStream_DecodeUnConstraintWholeNumber(pBitStrm) match +BitStream_DecodeUnConstraintWholeNumber(pBitStrm) match // uper:145 case Some(x) =>

= x case None() => @@ -222,18 +225,18 @@ pBitStrm.appendBit(

) >> Boolean_decode(p, sErrCode) ::= << -pBitStrm.readBit() match +pBitStrm.readBit() match // uper:225 case Some(bit) =>

= bit case None() => return Left() >> -Real_encode(p, sSuffix, sErrCode) ::= "BitStream_EncodeReal(pBitStrm,

)" +Real_encode(p, sSuffix, sErrCode) ::= "codec.encodeReal(

)" Real_decode(p, sSuffix, sErrCode) ::= << -BitStream_DecodeReal(pBitStrm) match +codec.decodeReal() match // uper:234 case Some(d) => -

= d.asInstanceOf[Double] // TODO this cast may loose precision in case that the target val

is a double +

= d.asInstanceOf[Double] case None() => return Left() >> @@ -258,7 +261,7 @@ if !_uper_decode(pBitStrm,

) then Enumerated_item_encode(p, sName, nIndex, nLastItemIndex) ::= << case => - BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, ) + codec.encodeConstraintWholeNumber(, 0, ) >> Enumerated_item_decode(p, sName, nIndex, nLastItemIndex) ::= << @@ -267,16 +270,16 @@ case => >> Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -

match +

match // uper:270 case _ => ret = Left() >> Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match // uper:277 case Some(x) => - x match + x match case _ => return Left() @@ -288,7 +291,7 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match choice_child_encode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr, bIsSequence, bIsEnum) ::= << case () => - BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, ) + codec.encodeConstraintWholeNumber(, 0, ) >> choice_child_decode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr, bIsSequence, bIsEnum) ::= << @@ -307,14 +310,14 @@ case => >> choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -

match +

match // uper:310 }; separator="\n"> case _ => ret = Left() >> choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match // uper:317 case Some(choice) => choice match }; separator="\n"> @@ -329,7 +332,7 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match /* SEQUENCE START */ sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "pBitStrm.appendBit(

exist.);" sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << -pBitStrm.readBit() match +pBitStrm.readBit() match // uper:332 case Some(bit) =>

exist. = bit case None() => @@ -408,14 +411,14 @@ str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength =

.indexOf(0x00) /*ret = nStringLength >= && nStringLength \<= ;*/ -BitStream_EncodeConstraintWholeNumber(pBitStrm, nStringLength, , ) +codec.encodeConstraintWholeNumber(nStringLength, , ) >> str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength = 0 -BitStream_DecodeConstraintWholeNumberInt(pBitStrm, , ) match +BitStream_DecodeConstraintWholeNumberInt(pBitStrm, , ) match // uper:418 case Some(n) => nStringLength = n

(nStringLength) = 0 // TODO do we need a 0 terminator? @@ -436,12 +439,12 @@ seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSiz >> seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ) +codec.encodeConstraintWholeNumber(

nCount, , ) >> seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:444 case Some(n) =>

nCount = n.asInstanceOf[Int] case None() => @@ -457,7 +460,7 @@ if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr, .a >> octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << -BitStream_DecodeOctetString_no_length(pBitStrm, ) match +BitStream_DecodeOctetString_no_length(pBitStrm, ) match // uper:460 case SomeMut(x) => x.copyToArray(

arr) case NoneMut() => @@ -465,14 +468,14 @@ BitStream_DecodeOctetString_no_length(pBitStrm, ) match >> octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << -BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ) +codec.encodeConstraintWholeNumber(

nCount, , ) if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount.asInstanceOf[Int]) then ret = Left() >> octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << // decode length -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:475 case Some(n) => assert(n >= 0)

nCount = n @@ -480,7 +483,7 @@ BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match return Left() // decode payload -BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int]) match +BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int]) match // uper:483 case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -493,7 +496,7 @@ assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast pBitStrm.appendBits(

arr, .asInstanceOf[Int]) >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << -pBitStrm.readBits(.asInstanceOf[Int]) match +pBitStrm.readBits(.asInstanceOf[Int]) match // uper:496 case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -501,12 +504,12 @@ pBitStrm.readBits(.asInstanceOf[Int]) match >> bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ) +codec.encodeConstraintWholeNumber(

nCount, , ) >> bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:509 case Some(n) =>

nCount = n case None() => @@ -522,7 +525,7 @@ FixedSize_Fragmentation_sqf_64K_encode(p, sAcc,sCurOffset, sCurBlockSize, sBlock var = 0 while( \< ) { - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF) + codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) pBitStrm.appendBits(&

arr[/8], (int)) @@ -542,7 +545,7 @@ while( \< ) FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize, sBlockId, sCurOffset, sCurBlockSize, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::=<< //encode Block = ; -BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) +codec.encodeConstraintWholeNumber(, 0, 0xFF) pBitStrm.appendBits(&

arr[/8], (int)); @@ -559,11 +562,11 @@ for(=(int); \< (int)( + ); < FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingItemsWithinByte, nRemainingItemsVar, sCurOffset, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::= << //encode remaining items -BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) +codec.encodeConstraintWholeNumber(, 0, 0xFF) pBitStrm.appendBit(true) -BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0x7FFF) +codec.encodeConstraintWholeNumber(, 0, 0x7FFF) @@ -591,16 +594,16 @@ while ( >= 0x4000 && \< (a { if >= 0x10000 then = 0x10000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF) + codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) else if >= 0xC000 then = 0xC000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC3, 0, 0xFF) + codec.encodeConstraintWholeNumber(0xC3, 0, 0xFF) else if >= 0x8000 then = 0x8000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC2, 0, 0xFF) + codec.encodeConstraintWholeNumber(0xC2, 0, 0xFF) else = 0x4000 - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF) + codec.encodeConstraintWholeNumber(0xC1, 0, 0xFF) pBitStrm.appendBits(&

arr[/8], (int)); @@ -618,10 +621,10 @@ while ( >= 0x4000 && \< (a } if \<= 0x7F then - BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) + codec.encodeConstraintWholeNumber(, 0, 0xFF) else pBitStrm.appendBit(true) - BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0x7FFF) + codec.encodeConstraintWholeNumber(, 0, 0x7FFF) pBitStrm.appendBits(&

arr[/8], (int)); @@ -730,7 +733,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0 -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match +BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:733 case None() => return Left() case Some(x) => @@ -767,7 +770,7 @@ while(( & 0xC0) == 0xC0) { += += - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:770 case None() => return Left() case Some(x) => @@ -777,7 +780,7 @@ while(( & 0xC0) == 0xC0) { if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match + BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:780 case None() => return Left() case Some(x) => diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index c17ba0ec8..dcde69ff6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -200,7 +200,7 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } - def BitStream_EncodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { + def encodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) require(min <= v && v <= max) @@ -214,7 +214,7 @@ trait Codec { encodeNonNegativeInteger((v - min)) } - def BitStream_EncodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { + def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { require(max >= 0 && max <= Long.MaxValue) require(min >= 0 && min <= max) require(min <= v && v <= max) @@ -286,7 +286,7 @@ trait Codec { case Some(l) => Some(l.toInt) } - def BitStream_DecodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { + def decodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { require(max >= 0 && max <= Long.MaxValue) require(min >= 0 && min <= max) @@ -307,7 +307,7 @@ trait Codec { val nBytes: Int = GetLengthInBytesOfUInt((v - min)) /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + encodeConstraintWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) @@ -320,7 +320,7 @@ trait Codec { val nBytes: Int = GetLengthInBytesOfUInt(v - min) /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + encodeConstraintWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) @@ -377,7 +377,7 @@ trait Codec { val nBytes: Int = GetLengthInBytesOfSInt(v) /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) + encodeConstraintWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ if v >= 0 then @@ -415,24 +415,24 @@ trait Codec { } @extern - def BitStream_EncodeReal(vVal: Double): Unit = { - BitStream_EncodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) + def encodeReal(vVal: Double): Unit = { + encodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) } - private def BitStream_EncodeRealBitString(vVal: Long): Unit = { + private def encodeRealBitString(vVal: Long): Unit = { // according to T-REC-X.690 2021 var v = vVal // 8.5.2 Plus Zero if v == DoublePosZeroBitString then - BitStream_EncodeConstraintWholeNumber(0, 0, 0xFF) + encodeConstraintWholeNumber(0, 0, 0xFF) return; // 8.5.3 Minus Zero if v == DoubleNegZeroBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x43, 0, 0xFF) + encodeConstraintWholeNumber(1, 0, 0xFF) + encodeConstraintWholeNumber(0x43, 0, 0xFF) return; // 8.5.9 SpecialRealValues (2021 standard) @@ -440,20 +440,20 @@ trait Codec { // 8.5.9 PLUS-INFINITY if v == DoublePosInfBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x40, 0, 0xFF) + encodeConstraintWholeNumber(1, 0, 0xFF) + encodeConstraintWholeNumber(0x40, 0, 0xFF) return; // 8.5.9 MINUS-INFINITY else if v == DoubleNegInfBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x41, 0, 0xFF) + encodeConstraintWholeNumber(1, 0, 0xFF) + encodeConstraintWholeNumber(0x41, 0, 0xFF) return; // 8.5.9 NOT-A-NUMBER else - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x42, 0, 0xFF) + encodeConstraintWholeNumber(1, 0, 0xFF) + encodeConstraintWholeNumber(0x42, 0, 0xFF) return; // 8.5.6 a) @@ -484,10 +484,10 @@ trait Codec { header |= 0x02 /* encode length */ - BitStream_EncodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) + encodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) /* encode header */ - BitStream_EncodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) + encodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) /* encode exponent */ if exponent >= 0 then @@ -503,15 +503,15 @@ trait Codec { } @extern - def BitStream_DecodeReal(): Option[Double] = { - BitStream_DecodeRealBitString() match + def decodeReal(): Option[Double] = { + decodeRealBitString() match case None() => None() case Some(ll) => Some(java.lang.Double.longBitsToDouble(ll)) } - private def BitStream_DecodeRealBitString(): Option[Long] = { + private def decodeRealBitString(): Option[Long] = { bitStream.readByte() match case None() => None() case Some(length) => @@ -548,10 +548,10 @@ trait Codec { // Decode 8.5.7 else - DecodeRealAsBinaryEncoding(length.toInt - 1, header) + decodeRealFromBitStream(length.toInt - 1, header) } - private def DecodeRealAsBinaryEncoding(lengthVal: Int, header: UByte): Option[Long] = { + private def decodeRealFromBitStream(lengthVal: Int, header: UByte): Option[Long] = { require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) require(bitStream.buf.length > lengthVal) @@ -723,16 +723,16 @@ trait Codec { decreases(nRemainingItemsVar1) if nRemainingItemsVar1 >= 0x10000 then nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + encodeConstraintWholeNumber(0xC4, 0, 0xFF) else if nRemainingItemsVar1 >= 0xC000 then nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + encodeConstraintWholeNumber(0xC3, 0, 0xFF) else if nRemainingItemsVar1 >= 0x8000 then nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + encodeConstraintWholeNumber(0xC2, 0, 0xFF) else nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + encodeConstraintWholeNumber(0xC1, 0, 0xFF) var i1: Int = nCurOffset1 while i1 < nCurBlockSize1 + nCurOffset1 && ret do @@ -745,10 +745,10 @@ trait Codec { if ret then if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) + encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) else bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) + encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) var i1: Int = nCurOffset1 @@ -853,7 +853,7 @@ trait Codec { if ret then if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) ret = BitStream_EncodeOctetString_no_length(arr, nCount) else @@ -886,7 +886,7 @@ trait Codec { def BitStream_EncodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) bitStream.appendBits(arr, nCount) @@ -899,17 +899,17 @@ trait Codec { if nRemainingItemsVar1 >= 0x10000 then nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) + encodeConstraintWholeNumber(0xC4, 0, 0xFF) else if nRemainingItemsVar1 >= 0xC000 then nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) + encodeConstraintWholeNumber(0xC3, 0, 0xFF) else if nRemainingItemsVar1 >= 0x8000 then nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) + encodeConstraintWholeNumber(0xC2, 0, 0xFF) else nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) + encodeConstraintWholeNumber(0xC1, 0, 0xFF) val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) bitStream.appendBits(t, nCurBlockSize1.toInt) @@ -918,10 +918,10 @@ trait Codec { if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) + encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) else bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) + encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) bitStream.appendBits(t, nRemainingItemsVar1.toInt) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 048105da9..0150111ea 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -891,7 +891,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_Ascii_private(max, strVal) } @@ -899,7 +899,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < max do val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + encodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) i += 1 } @@ -907,7 +907,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while (i < max) && (strVal(i) != '\u0000') do val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + encodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) i += 1 i @@ -920,7 +920,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_CharIndex_private(max, allowedCharSet, strVal) } @@ -962,7 +962,7 @@ case class ACN(bitStream: BitStream) extends Codec { 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_CharIndex_private(max, allowedCharSet, strVal) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 7da6ea1a3..c8e43986a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -54,10 +54,10 @@ case class UPER(bitStream: BitStream) extends Codec { i += 1 if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) else bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do @@ -81,10 +81,10 @@ case class UPER(bitStream: BitStream) extends Codec { if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) else bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do diff --git a/asn1scc/asn1jvm_Codec.scala b/asn1scc/asn1jvm_Codec.scala deleted file mode 100644 index 81967d663..000000000 --- a/asn1scc/asn1jvm_Codec.scala +++ /dev/null @@ -1,1004 +0,0 @@ -package asn1scala - -import stainless.* -import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} -import stainless.collection.* -import stainless.annotation.* -import stainless.proof.* -import stainless.math.* -import StaticChecks.* - -// TODO move to Bitstream if only used there -val masksb: Array[UByte] = Array( - 0x00, // 0 / 0000 0000 / x00 - 0x01, // 1 / 0000 0001 / x01 - 0x03, // 3 / 0000 0011 / x03 - 0x07, // 7 / 0000 0111 / x07 - 0x0F, // 15 / 0000 1111 / x0F - 0x1F, // 31 / 0001 1111 / x1F - 0x3F, // 63 / 0011 1111 / x3F - 0x7F, // 127 / 0111 1111 / x7F - -0x1, // -1 / 1111 1111 / xFF -) - -val masks2: Array[UInt] = Array( - 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 - 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF - 0x0000FF00, // 65280 / 0000 0000 0000 0000 1111 1111 0000 0000 / 0x0000 FF00 - 0x00FF0000, // 16711680 / 0000 0000 1111 1111 0000 0000 0000 0000 / 0x00FF 0000 - 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 -) - - -/***********************************************************************************************/ -/** Byte Stream Functions **/ -/***********************************************************************************************/ -def ByteStream_Init(count: Int): ByteStream = { - ByteStream(Array.fill(count)(0), 0, false) -} - -@extern -def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { - pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... - pStrm.currentByte = 0 -}.ensuring(_ => pStrm.buf == buf && pStrm.currentByte == 0 && pStrm.EncodeWhiteSpace == old(pStrm).EncodeWhiteSpace) - -def ByteStream_GetLength(pStrm: ByteStream): Int = { - pStrm.currentByte -} - -/***********************************************************************************************/ -/** Bit Stream Functions **/ -/***********************************************************************************************/ -def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { - arraySameElements(arr1, arr2) - //return - // (nBitsLength1 == nBitsLength2) && - // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && - // (nBitsLength1 % 8 > 0 ? (arr1[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8) == arr2[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8)): TRUE); -} - - -// TODO remove -def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), 0, 0) -} - -/** - * Parent class for the PER Codec that is used by ACN and UPER - * - * @param count represents the number of bytes in the internal buffer - */ -@mutable -trait Codec { - - def bitStream: BitStream - - /** ******************************************************************************************** */ - /** ******************************************************************************************** */ - /** ******************************************************************************************** */ - /** ******************************************************************************************** */ - /** Integer Functions * */ - /** ******************************************************************************************** */ - /** ******************************************************************************************** */ - /** ******************************************************************************************** */ - - /** ******************************************************************************************** */ - def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { - var cc: UInt = 0 - var curMask: UInt = 0 - var pbits: UInt = 0 - - if v == 0 then - return () - - if v >>> 8 == 0 then - cc = 8 - curMask = 0x80 - else if v >>> 16 == 0 then - cc = 16 - curMask = 0x8000 - else if v >>> 24 == 0 then - cc = 24 - curMask = 0x800000 - else - cc = 32 - curMask = 0x80000000 - - while (v & curMask) == 0 do - decreases(cc) - curMask >>>= 1 - cc -= 1 - - pbits = cc % 8 - if pbits > 0 then - cc -= pbits - bitStream.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) - - while cc > 0 do - decreases(cc) - val t1: UInt = v.toInt & masks2(cc >>> 3) - cc -= 8 - bitStream.appendByte((t1 >>> cc).toByte, negate) - } - - def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { - - var v: UInt = 0 - - var nBits = nBitsVal - while nBits >= 8 do - decreases(nBits) - v = v << 8 - - bitStream.readByte() match - case None() => return None() - case Some(ub) => - // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) - // will be casted to an Int -1 (1111 ... 1111) - v = v | (ub & 0xFF) - - nBits -= 8 - - if nBits != 0 then - v = v << nBits - bitStream.readPartialByte(nBits.toByte) match - case None() => return None() - case Some(ub) => v = v | (ub & 0xFF) - - Some(v) - } - - def encodeNonNegativeInteger(v: ULong): Unit = { - if v >>> 32 == 0 then - encodeNonNegativeInteger32Neg(v.toInt, false) - else - val hi = (v >>> 32).toInt - val lo = v.toInt - encodeNonNegativeInteger32Neg(hi, false) - - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? - bitStream.appendNBitZero(32 - nBits) - encodeNonNegativeInteger32Neg(lo, false) - } - - def decodeNonNegativeInteger(nBits: Int): Option[ULong] = { - if nBits <= 32 then - decodeNonNegativeInteger32Neg(nBits) match - case None() => return None() - case Some(lo) => - return Some(lo & 0xFFFFFFFFL) - - val hi_ret = decodeNonNegativeInteger32Neg(32) - val lo_ret = decodeNonNegativeInteger32Neg(nBits - 32) - - (hi_ret, lo_ret) match - case (Some(hi), Some(lo)) => - var v: ULong = hi & 0xFFFFFFFFL - v = v << nBits - 32L - v |= lo & 0xFFFFFFFFL - return Some(v) - case _ => return None() - //else - // return decodeNonNegativeInteger32Neg(v, nBits) - } - - def encodeNonNegativeIntegerNeg(v: ULong, negate: Boolean): Unit = { - if v >>> 32 == 0 then - encodeNonNegativeInteger32Neg(v.toInt, negate) - else - // TODO: Check Int/Long - val hi = (v >>> 32).toInt - var lo = v.toInt - encodeNonNegativeInteger32Neg(hi, negate) - - /*bug !!!!*/ - if negate then - lo = ~lo - val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) - bitStream.appendNBitZero(32 - nBits) - encodeNonNegativeInteger32Neg(lo, false) - } - - def BitStream_EncodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { - require(min <= max) - require(min <= v && v <= max) - - val range = max - min - if range == 0 then - return - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) - bitStream.appendNBitZero(nRangeBits - nBits); - encodeNonNegativeInteger((v - min)) - } - - def BitStream_EncodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { - require(max >= 0 && max <= Long.MaxValue) - require(min >= 0 && min <= max) - require(min <= v && v <= max) - - val range: ULong = (max - min) - if range == 0 then - return - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - bitStream.appendNBitZero(nRangeBits - nBits) - encodeNonNegativeInteger(v - min) - } - - def BitStream_DecodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { - - val range: ULong = (max - min) - - // ASSERT_OR_RETURN_FALSE(min <= max); - - if range == 0 then - return Some(min) - - val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) - - decodeNonNegativeInteger(nRangeBits) match - case None() => return None() - case Some(ul) => return Some(ul + min) - } - - def BitStream_DecodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { - - BitStream_DecodeConstraintWholeNumber(min.toLong, max.toLong) match - case None() => None() - case Some(l) => Some(l.toByte) - } - - def BitStream_DecodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { - - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(l) => Some(l.toShort) - } - - def BitStream_DecodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { - - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(l) => Some(l.toInt) - } - - def BitStream_DecodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { - - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toByte) - } - - def BitStream_DecodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { - - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toShort) - } - - def BitStream_DecodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { - - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toInt) - } - - def BitStream_DecodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { - require(max >= 0 && max <= Long.MaxValue) - require(min >= 0 && min <= max) - - val range: ULong = max - min - - if range == 0 then - return Some(min) - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - - decodeNonNegativeInteger(nRangeBits) match - case None() => None() - case Some(uv) => Some(uv + min) - } - - def BitStream_EncodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { - assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt((v - min)) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - /* put required zeros*/ - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) - /*Encode number */ - encodeNonNegativeInteger((v - min)) - } - - def BitStream_EncodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { - assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt(v - min) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - /* put required zeros*/ - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) - /*Encode number */ - encodeNonNegativeInteger(v - min) - } - - def BitStream_DecodeSemiConstraintWholeNumber(min: Long): Option[Long] = { - - var nBytes: Long = 0 - var v: Long = 0 - - BitStream_DecodeConstraintWholeNumber(0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - bitStream.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - - v += min - - return Some(v) - } - - def BitStream_DecodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { - - var nBytes: Long = 0 - var v: ULong = 0 - BitStream_DecodeConstraintWholeNumber(0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - bitStream.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - v += min - return Some(v) - } - - def BitStream_EncodeUnConstraintWholeNumber(v: Long): Unit = { - val nBytes: Int = GetLengthInBytesOfSInt(v) - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ - - if v >= 0 then - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) - encodeNonNegativeInteger(v) - else - bitStream.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) - encodeNonNegativeIntegerNeg((-v - 1), true) - } - - - def BitStream_DecodeUnConstraintWholeNumber(): Option[Long] = { - - var nBytes: Long = 0 - - BitStream_DecodeConstraintWholeNumber(0, 255) match - case None() => return None() - case Some(l) => nBytes = l - - val valIsNegative: Boolean = bitStream.peekBit() - - var v: Long = if valIsNegative then Long.MaxValue else 0 - - var i: Long = 0 - while i < nBytes do - decreases(nBytes - i) - - bitStream.readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong - - i += 1 - - return Some(v) - } - - @extern - def BitStream_EncodeReal(vVal: Double): Unit = { - BitStream_EncodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) - } - - private def BitStream_EncodeRealBitString(vVal: Long): Unit = { - // according to T-REC-X.690 2021 - - var v = vVal - - // 8.5.2 Plus Zero - if v == DoublePosZeroBitString then - BitStream_EncodeConstraintWholeNumber(0, 0, 0xFF) - return; - - // 8.5.3 Minus Zero - if v == DoubleNegZeroBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x43, 0, 0xFF) - return; - - // 8.5.9 SpecialRealValues (2021 standard) - if (v & ExpoBitMask) == ExpoBitMask then - - // 8.5.9 PLUS-INFINITY - if v == DoublePosInfBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x40, 0, 0xFF) - return; - - // 8.5.9 MINUS-INFINITY - else if v == DoubleNegInfBitString then - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x41, 0, 0xFF) - return; - - // 8.5.9 NOT-A-NUMBER - else - BitStream_EncodeConstraintWholeNumber(1, 0, 0xFF) - BitStream_EncodeConstraintWholeNumber(0x42, 0, 0xFF) - return; - - // 8.5.6 a) - // fixed encoding style to binary - // 8.5.7.2 exp has always base 2 - bit 0x20 and 0x10 are always 0 - // 8.5.7.3 F value is always zero - bit 0x08 and 0x04 are always 0 - var header = 0x80 - - // 8.5.7.1 - if ((v & SignBitMask) == SignBitMask) { // check sign bit - header |= 0x40 - v &= InverseSignBitMask // clear sign bit - } - - val (exponent, mantissa) = CalculateMantissaAndExponent(v) - - val nManLen: Int = GetLengthInBytesOfUInt(mantissa) - assert(nManLen <= 7) // 52 bit - - val compactExp = RemoveLeadingFFBytesIfNegative(exponent) - val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) - assert(nExpLen >= 1 && nExpLen <= 2) - - // 8.5.7.4 - if nExpLen == 2 then - header |= 0x01 - else if nExpLen == 3 then // this will never happen with this implementation - header |= 0x02 - - /* encode length */ - BitStream_EncodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) - - /* encode header */ - BitStream_EncodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) - - /* encode exponent */ - if exponent >= 0 then - // fill with zeros to have a whole byte - bitStream.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) - encodeNonNegativeInteger(exponent) - else - encodeNonNegativeInteger(compactExp) - - /* encode mantissa */ - bitStream.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) - encodeNonNegativeInteger(mantissa) - } - - @extern - def BitStream_DecodeReal(): Option[Double] = { - BitStream_DecodeRealBitString() match - case None() => - None() - case Some(ll) => - Some(java.lang.Double.longBitsToDouble(ll)) - } - - private def BitStream_DecodeRealBitString(): Option[Long] = { - bitStream.readByte() match - case None() => None() - case Some(length) => - // 8.5.2 Plus Zero - if length == 0 then - return Some(0) - - // invalid state - if length < 0 || length > DoubleMaxLengthOfSentBytes then - return None() - - bitStream.readByte() match - case None() => None() - case Some(header) => - // 8.5.6 a) - if (header.unsignedToInt & 0x80) != 0x80 then - return None() - - // 8.5.9 PLUS-INFINITY - if header == 0x40 then - Some(DoublePosInfBitString) - - // 8.5.9 MINUS-INFINITY - else if header == 0x41 then - Some(DoubleNegInfBitString) - - // 8.5.9 NOT-A-NUMBER - else if header == 0x42 then - Some(DoubleNotANumber) - - // 8.5.3 Minus Zero - else if header == 0x43 then - Some(DoubleNegZeroBitString) - - // Decode 8.5.7 - else - DecodeRealAsBinaryEncoding(length.toInt - 1, header) - } - - private def DecodeRealAsBinaryEncoding(lengthVal: Int, header: UByte): Option[Long] = { - require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte - require((header.unsignedToInt & 0x80) == 0x80) - require(bitStream.buf.length > lengthVal) - require(bitStream.currentByte < bitStream.buf.length - lengthVal) - - // 8.5.7.2 Base - val expFactor: Int = header.unsignedToInt match - case x if (x & 0x10) > 0 => 3 // 2^3 = 8 - case x if (x & 0x20) > 0 => 4 // 2^4 = 16 - case _ => 1 // 2^1 = 2 - - // 8.5.7.3 Factor F - val factor = 1 << ((header & 0x0C) >>> 2) - - // 8.5.7.4 Length of Exponent - val expLen = (header & 0x03) + 1 - - // sanity check - if expLen > lengthVal then - return None() - - // decode exponent - val expIsNegative = bitStream.peekBit() - var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 - - var i: Int = 0 - (while i < expLen do - decreases(expLen - i) - - bitStream.readByte() match - case None() => return None() - case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) - - i += 1 - ).invariant(i >= 0 && i <= expLen) - - // decode mantissa - val length = lengthVal - expLen - var N: ULong = 0 - var j: Int = 0 - (while j < length do - decreases(length - j) - - bitStream.readByte() match - case None() => return None() - case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) - - j += 1 - ).invariant(j >= 0 && j <= length) - - var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) - - // 8.5.7.1 Set Sign bit - if (header & 0x40) > 0 then - v |= SignBitMask - - Some(v) - } - - def BitStream_checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { - var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal - val tmp_currentByte: Int = bitStream.currentByte - val tmp_currentBit: Int = bitStream.currentBit - var tmp_byte: UByte = 0 - - if bitStream.currentByte.toLong * 8 + bitStream.currentBit + bit_terminated_pattern_size_in_bits.toInt > bitStream.buf.length.toLong * 8 then - return 0 - - var i: Int = 0 - while bit_terminated_pattern_size_in_bits >= 8 do - decreases(bit_terminated_pattern_size_in_bits) - - bitStream.readByte() match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - bit_terminated_pattern_size_in_bits = 8 - if bit_terminated_pattern(i) != tmp_byte then - bitStream.currentByte = tmp_currentByte - bitStream.currentBit = tmp_currentBit - return 1 - i += 1 - - if bit_terminated_pattern_size_in_bits > 0 then - bitStream.readPartialByte(bit_terminated_pattern_size_in_bits) match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte - - if bit_terminated_pattern(i) != tmp_byte then - bitStream.currentByte = tmp_currentByte - bitStream.currentBit = tmp_currentBit - return 1 - - return 2 - } - - def BitStream_ReadBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { - var checkBitPatternPresentResult: Int = 0 - - var bitsRead: Int = 0 - - val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) - - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do - decreases(nMaxReadBits - bitsRead) - bitStream.readBit() match - case None() => return NoneMut() - case Some(bitVal) => - tmpStrm.appendBit(bitVal) - bitsRead += 1 - - if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if checkBitPatternPresentResult != 2 then - return NoneMut() - - return SomeMut((tmpStrm.buf, bitsRead)) - } - - def BitStream_EncodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { - val cb = bitStream.currentBit - var ret: Boolean = false - - if cb == 0 then - ret = bitStream.currentByte + nCount <= bitStream.buf.length - if ret then - copyToArray(arr, bitStream.buf, bitStream.currentByte, nCount) - bitStream.currentByte += nCount - - else - ret = bitStream.appendByteArray(arr, nCount) - - ret - } - - def BitStream_DecodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { - val cb: Int = bitStream.currentBit - val arr: Array[UByte] = Array.fill(nCount + 1)(0) - - if cb == 0 then - if bitStream.currentByte + nCount > bitStream.buf.length then - return NoneMut() - - arrayCopyOffset(bitStream.buf, arr, bitStream.currentByte, bitStream.currentByte + nCount, 0) - bitStream.currentByte += nCount - - else - bitStream.readByteArray(nCount) match - case NoneMut() => return NoneMut() - case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) - - SomeMut(arr) - } - - def BitStream_EncodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { - var nRemainingItemsVar1: Int = nCount - var nCurBlockSize1: Int = 0 - var nCurOffset1: Int = 0 - var ret: Boolean = nCount >= 0 - - while nRemainingItemsVar1 >= 0x4000 && ret do - decreases(nRemainingItemsVar1) - if nRemainingItemsVar1 >= 0x10000 then - nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) - else if nRemainingItemsVar1 >= 0xC000 then - nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) - else if nRemainingItemsVar1 >= 0x8000 then - nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) - else - nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) - - var i1: Int = nCurOffset1 - while i1 < nCurBlockSize1 + nCurOffset1 && ret do - decreases(nCurBlockSize1 + nCurOffset1 - i1) - ret = bitStream.appendByte0(arr(i1)) - i1 += 1 - - nCurOffset1 += nCurBlockSize1 - nRemainingItemsVar1 -= nCurBlockSize1 - - if ret then - if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) - - - var i1: Int = nCurOffset1 - while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do - decreases(nCurOffset1 + nRemainingItemsVar1 - i1) - ret = bitStream.appendByte0(arr(i1)) - i1 += 1 - - return ret - } - - def BitStream_DecodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { - require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) - - val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) - var nCount: Int = 0 - - var nLengthTmp1: Long = 0 - var nRemainingItemsVar1: Long = 0 - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - - // get header data - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - // 11xx_xxxx header, there is a next fragment - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease - - // get current block size - if nRemainingItemsVar1 == 0xC4 then - nCurBlockSize1 = 0x10000 - else if nRemainingItemsVar1 == 0xC3 then - nCurBlockSize1 = 0xC000 - else if nRemainingItemsVar1 == 0xC2 then - nCurBlockSize1 = 0x8000 - else if nRemainingItemsVar1 == 0xC1 then - nCurBlockSize1 = 0x4000 - else - return NoneMut() - - // fill current payload fragment into dest - var i1: Int = nCurOffset1.toInt - while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do - decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) - bitStream.readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub - i1 += 1 - - // sum combined length - nLengthTmp1 += nCurBlockSize1 - // set offset for next run - nCurOffset1 += nCurBlockSize1 - - // get next header - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower - if (nRemainingItemsVar1 & 0x80) > 0 then - - nRemainingItemsVar1 <<= 8 // put upper at correct position - // get size (lower byte) - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size - nRemainingItemsVar1 &= 0x7FFF // clear the control bit - - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - var i1: Int = nCurOffset1.toInt - - // fill last payload fragment into dest - while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do - decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) - bitStream.readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub - i1 += 1 - - // add remainingSize to already written size - this var holds the absolut number in all fragments - nLengthTmp1 += nRemainingItemsVar1 - - // resize output array and copy data - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) - arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) - return SomeMut(newArr) - else - return NoneMut() - - NoneMut() - } - - def BitStream_EncodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { - var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax - - if ret then - if asn1SizeMax < 65536 then - if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - ret = BitStream_EncodeOctetString_no_length(arr, nCount) - - else - ret = BitStream_EncodeOctetString_fragmentation(arr, nCount) - - return ret - } - - def BitStream_DecodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - - if asn1SizeMax < 65536 then - var nCount: Int = 0 - if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l.toInt - else - nCount = asn1SizeMin.toInt - - if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then - return BitStream_DecodeOctetString_no_length(nCount) - else - return NoneMut() - - else - return BitStream_DecodeOctetString_fragmentation(asn1SizeMax) - - } - - def BitStream_EncodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { - if asn1SizeMax < 65536 then - if asn1SizeMin != asn1SizeMax then - BitStream_EncodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - - bitStream.appendBits(arr, nCount) - - else - var nRemainingItemsVar1: Long = nCount.toLong - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - while nRemainingItemsVar1 >= 0x4000 do - decreases(nRemainingItemsVar1) - - if nRemainingItemsVar1 >= 0x10000 then - nCurBlockSize1 = 0x10000 - BitStream_EncodeConstraintWholeNumber(0xC4, 0, 0xFF) - - else if nRemainingItemsVar1 >= 0xC000 then - nCurBlockSize1 = 0xC000 - BitStream_EncodeConstraintWholeNumber(0xC3, 0, 0xFF) - else if nRemainingItemsVar1 >= 0x8000 then - nCurBlockSize1 = 0x8000 - BitStream_EncodeConstraintWholeNumber(0xC2, 0, 0xFF) - else - nCurBlockSize1 = 0x4000 - BitStream_EncodeConstraintWholeNumber(0xC1, 0, 0xFF) - - val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) - bitStream.appendBits(t, nCurBlockSize1.toInt) - nCurOffset1 += nCurBlockSize1 - nRemainingItemsVar1 -= nCurBlockSize1 - - - if nRemainingItemsVar1 <= 0x7F then - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) - - val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) - bitStream.appendBits(t, nRemainingItemsVar1.toInt) - - true - } - - def BitStream_DecodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - require(asn1SizeMax <= Int.MaxValue) - - if (asn1SizeMax < 65536) { - var nCount: Long = 0 - if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l - else - nCount = asn1SizeMin - - return bitStream.readBits(nCount.toInt) - - } else { - var nRemainingItemsVar1: Long = 0 - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - var nLengthTmp1: Long = 0 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease - if nRemainingItemsVar1 == 0xC4 then - nCurBlockSize1 = 0x10000 - else if nRemainingItemsVar1 == 0xC3 then - nCurBlockSize1 = 0xC000 - else if nRemainingItemsVar1 == 0xC2 then - nCurBlockSize1 = 0x8000 - else if nRemainingItemsVar1 == 0xC1 then - nCurBlockSize1 = 0x4000 - else - return NoneMut() - - /*COVERAGE_IGNORE*/ - if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then - return NoneMut() - /*COVERAGE_IGNORE*/ - - bitStream.readBits(nCurBlockSize1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) - nLengthTmp1 += nCurBlockSize1 - nCurOffset1 += nCurBlockSize1 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - if (nRemainingItemsVar1 & 0x80) > 0 then - nRemainingItemsVar1 <<= 8 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l - nRemainingItemsVar1 &= 0x7FFF - - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - - bitStream.readBits(nRemainingItemsVar1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) - nLengthTmp1 += nRemainingItemsVar1 - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return SomeMut(arr) - } - return NoneMut() - } -} diff --git a/asn1scc/asn1jvm_Codec_ACN.scala b/asn1scc/asn1jvm_Codec_ACN.scala deleted file mode 100644 index fe76f858f..000000000 --- a/asn1scc/asn1jvm_Codec_ACN.scala +++ /dev/null @@ -1,1580 +0,0 @@ -package asn1scala - -import stainless.lang.StaticChecks.assert -import stainless.lang.{None, Option, Some} - -val FAILED_READ_ERR_CODE = 5400 - -// TODO remove / replace by invariant -def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { - assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) -} - -/** - * Get an instance of a ACN coded bitstream - * @param count of elements in underlaying buffer - * @return ACN coded bitstream - */ -def initACNCodec(count: Int): ACN = { - ACN(BitStream(Array.fill(count)(0))) -} - -case class ACN(bitStream: BitStream) extends Codec { - - def alignToByte(): Unit = { - if bitStream.currentBit != 0 then - bitStream.currentBit = 0 - bitStream.currentByte += 1 - CHECK_BIT_STREAM(bitStream) - } - - def alignToShort(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT - CHECK_BIT_STREAM(bitStream) - } - - def alignToInt(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT - CHECK_BIT_STREAM(bitStream) - } - - /*ACN Integer functions*/ - def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { - if encodedSizeInBits == 0 then - return - - /* Get number of bits*/ - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) - /* put required zeros*/ - // TODO what if nBits > encodedSizeInBits ?? - bitStream.appendNBitZero(encodedSizeInBits - nBits) - /*Encode number */ - encodeNonNegativeInteger(intVal) - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { - bitStream.appendByte0(intVal.toByte) - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { - val tmp: ULong = intVal - var mask: ULong = 0xFF - mask <<= (size - 1) * 8 - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) - mask >>>= 8 - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_SHORT) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_32(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_INT) - } - - def enc_Int_PositiveInteger_ConstSize_big_endian_64(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal, NO_OF_BYTES_IN_JVM_LONG) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal: ULong, size: Int): Unit = { - var tmp: ULong = intVal - - var i: Int = 0 - while i < size do - val ByteToEncode: Byte = tmp.toByte - bitStream.appendByte0(ByteToEncode) - tmp >>>= 8 - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 2) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_32(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, 4) - } - - def enc_Int_PositiveInteger_ConstSize_little_endian_64(intVal: ULong): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) - } - - - def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { - decodeNonNegativeInteger(encodedSizeInBits) match - case None() => None() - case Some(ul) => Some(ul) - } - - - def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(ub) => Some(ub & 0xFF) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { - var ret: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - ret <<= 8 - ret |= (ub & 0xFF) - i += 1 - - Some(ret) - } - - // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly - def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { - var ret: ULong = 0 - var tmp: ULong = 0 - - var i: Int = 0 - while i < SizeInBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - tmp = ub & 0xFF - tmp <<= i * 8 - ret |= tmp - i += 1 - - Some(ret) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_little_endian_N(2) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize_little_endian_N(4) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { - val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) - bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - ret - } - - - def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { - val MAX_BYTE_MASK = 0xFF00000000000000L - assert(nBytes <= 8) - - var vv: ULong = v << (NO_OF_BYTES_IN_JVM_LONG * 8 - nBytes * 8) - - var i: Int = 0 - while i < nBytes do - val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) - vv <<= 8 - i += 1 - } - - - def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte - - /* encode length */ - bitStream.appendByte0(nBytes) - /* Encode integer data*/ - encode_UnsignedInteger(intVal, nBytes) - - CHECK_BIT_STREAM(bitStream) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { - var v: ULong = 0 - - bitStream.readByte() match - case None() => return None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - v = (v << 8) | (ub & 0xFF) - i += 1 - - Some(v) - } - - - def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { - if intVal >= 0 then - bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) - encodeNonNegativeInteger(intVal) - - else - bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) - encodeNonNegativeIntegerNeg(-intVal - 1, true) - - CHECK_BIT_STREAM(bitStream) - } - - - def enc_Int_TwosComplement_ConstSize_8(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_8(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_16(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_16(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_32(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_32(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_big_endian_64(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_big_endian_64(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_16(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_16(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_32(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_32(int2uint(intVal)) - } - - def enc_Int_TwosComplement_ConstSize_little_endian_64(intVal: Long): Unit = { - enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) - } - - def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { - val valIsNegative: Boolean = bitStream.peekBit() - val nBytes: Int = encodedSizeInBits / 8 - val rstBits: Int = encodedSizeInBits % 8 - - var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 - - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << 8) | (ub & 0xFF) - i += 1 - - if rstBits > 0 then - bitStream.readPartialByte(rstBits.toByte) match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << rstBits) | (ub & 0xFF) - - Some(pIntVal) - } - - - def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 1)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) - } - - - def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { - val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte - - /* encode length */ - bitStream.appendByte0(nBytes) - /* Encode integer data*/ - encode_UnsignedInteger(int2uint(intVal), nBytes) - - CHECK_BIT_STREAM(bitStream) - } - - - def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { - var v: ULong = 0 - var isNegative: Boolean = false - - bitStream.readByte() match - case None() => None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - bitStream.readByte() match - case None() => return None() - case Some(ub) => - if i == 0 && (ub & 0x80) > 0 then - v = Long.MaxValue - isNegative = true - - v = (v << 8) | (ub & 0xFF) - i += 1 - - if isNegative then - Some(-(~v) - 1) - else - Some(v) - } - - - //return values is in nibbles - def get_Int_Size_BCD(intVal: ULong): Int = { - var intVar = intVal - var ret: Int = 0 - while intVar > 0 do - intVar /= 10 - ret += 1 - - ret - } - - - def enc_Int_BCD_ConstSize(intVal: ULong, encodedSizeInNibbles: Int): Unit = { - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) - - assert(100 >= encodedSizeInNibbles) - - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 - - assert(encodedSizeInNibbles >= totalNibbles) - - var i: Int = encodedSizeInNibbles - 1 - while i >= 0 do - bitStream.appendPartialByte(tmp(i).toByte, 4, false) - i -= 1 - - CHECK_BIT_STREAM(bitStream) - } - - - def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { - var ret: ULong = 0 - - var encodedSizeInNibblesVar = encodedSizeInNibbles - while encodedSizeInNibblesVar > 0 do - bitStream.readPartialByte(4) match - case None() => return None() - case Some(digit) => - ret *= 10 - ret += digit - encodedSizeInNibblesVar -= 1 - - Some(ret) - } - - - def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val nNibbles: Int = get_Int_Size_BCD(intVal) - /* encode length */ - bitStream.appendByte0(nNibbles.toByte) - - /* Encode Number */ - enc_Int_BCD_ConstSize(intVal, nNibbles) - - CHECK_BIT_STREAM(bitStream) - } - - - def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) - } - - - //encoding puts an 'F' at the end - def enc_Int_BCD_VarSize_NullTerminated(intVal: ULong): Unit = { - - val nNibbles: Int = get_Int_Size_BCD(intVal) - - /* Encode Number */ - enc_Int_BCD_ConstSize(intVal, nNibbles) - - bitStream.appendPartialByte(0xF, 4, false) - - CHECK_BIT_STREAM(bitStream) - } - - def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { - var ret: ULong = 0 - - while true do - bitStream.readPartialByte(4) match - case None() => return None() - case Some(digit) => - if (digit > 9) - return Some(ret) - - ret *= 10 - ret += digit - - Some(ret) - } - - - def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { - var intVar = intVal - var totalNibbles: Int = 0 - val tmp: Array[UByte] = Array.fill(100)(0) - - assert(100 >= encodedSizeInBytes) - - while intVar > 0 do - tmp(totalNibbles) = (intVar % 10).asInstanceOf[UByte] - totalNibbles += 1 - intVar /= 10 - - assert(encodedSizeInBytes >= totalNibbles) - - var i = encodedSizeInBytes - 1 - while i >= 0 do - bitStream.appendByte0((tmp(i) + '0').toByte) - i -= 1 - - CHECK_BIT_STREAM(bitStream) - } - - - def enc_SInt_ASCII_ConstSize(intVal: Long, encodedSizeInBytes: Int): Unit = { - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal - - /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') - - enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) - } - - def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { - var encodedSizeInBytesVar = encodedSizeInBytes - var ret: ULong = 0 - - while encodedSizeInBytesVar > 0 do - bitStream.readByte() match - case None() => return None() - case Some(digit) => - assert(digit >= '0' && digit <= '9') - - ret *= 10 - ret += (digit.toInt - '0').toByte - - encodedSizeInBytesVar -= 1 - - Some(ret) - } - - def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { - bitStream.readByte() match - case None() => None() - case Some(digit) => - var sign: Int = 1 - if digit == '+' then - sign = 1 - else if digit == '-' then - sign = -1 - else - assert(false) - - dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match - case None() => None() - case Some(ul) => Some(sign * ul) - } - - - def getIntegerDigits(intVal: ULong): (Array[Byte], Byte) = { - var intVar = intVal - val digitsArray100: Array[Byte] = Array.fill(100)(0) - val reversedDigitsArray: Array[Byte] = Array.fill(100)(0) - var totalDigits: Byte = 0 - - - if intVar > 0 then - while intVar > 0 && totalDigits < 100 do - reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte - totalDigits = (totalDigits + 1).toByte - intVar /= 10 - - var i: Int = totalDigits - 1 - while i >= 0 do - digitsArray100(totalDigits - 1 - i) = reversedDigitsArray(i) - i -= 1 - - else - digitsArray100(0) = '0' - totalDigits = 1 - - (digitsArray100, totalDigits) - } - - - def enc_SInt_ASCII_VarSize_LengthEmbedded(intVal: Long): Unit = { - val absIntVal: ULong = if intVal >= 0 then intVal else -intVal - val (digitsArray100, nChars) = getIntegerDigits(absIntVal) - - /* encode length, plus 1 for sign */ - bitStream.appendByte0((nChars + 1).toByte) - - /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') - - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val (digitsArray100, nChars) = getIntegerDigits(intVal) - - /* encode length */ - bitStream.appendByte0(nChars) - /* encode digits */ - var i: Int = 0 - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - - def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match - case None() => None() - case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) - } - - def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { - bitStream.readByte() match - case None() => None() - case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) - } - - - def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { - val (digitsArray100, nChars) = getIntegerDigits(intVal) - - var i: Int = 0 // TODO: size_t? - while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) - i += 1 - - i = 0 - while i < null_characters_size do - bitStream.appendByte0(null_characters(i)) - i += 1 - - CHECK_BIT_STREAM(bitStream) - } - - def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { - val absValue: ULong = if intVal >= 0 then intVal else -intVal - bitStream.appendByte0(if intVal >= 0 then '+' else '-') - - enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) - } - - def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { - var digit: Byte = 0 - var ret: ULong = 0 - val tmp: Array[Byte] = Array.fill(10)(0) - - val sz: Int = if null_characters_size < 10 then null_characters_size else 10 - - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_characters_size do - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub - j += 1 - - var i: Long = 0 - while !null_characters.sameElements(tmp) do - digit = tmp(0) - i += 1 - - j = 0 - while j < null_characters_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 - - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(null_characters_size - 1) = ub - - digit = (digit - '0').toByte - - ret *= 10 - ret += digit - - Some(ret) - } - - - def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { - var isNegative: Boolean = false - - bitStream.readByte() match - case None() => None() - case Some(digit) => - assert(digit == '-' || digit == '+') - if digit == '-' then - isNegative = true - - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(ul) => Some(if isNegative then -ul else ul) - } - - - /* Boolean Decode */ - // TODO move to codec? - def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var pBoolValue: Boolean = true - var i: Int = 0 - while i < nBytesToRead do - bitStream.readByte() match - case None() => return None() - case Some(curByte) => - if curByte != patternToRead(i) then - pBoolValue = false - i += 1 - - if nRemainingBitsToRead > 0 then - bitStream.readPartialByte(nRemainingBitsToRead.toByte) match - case None() => return None() - case Some(curByte) => - if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then - pBoolValue = false - - Some(pBoolValue) - } - - // TODO move to codec? - def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { - val nBytesToRead: Int = nBitsToRead / 8 - val nRemainingBitsToRead: Int = nBitsToRead % 8 - - var i: Int = 0 - while i < nBytesToRead do - bitStream.readByte() match - case None() => return Left(FAILED_READ_ERR_CODE) - case Some(_) => i += 1 - - if nRemainingBitsToRead > 0 then - if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then - return Left(FAILED_READ_ERR_CODE) - - Right(0) - } - - - /*Real encoding functions*/ - def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array - - var i: Int = 0 - while i < 4 do - bitStream.appendByte0(b(i)) - i += 1 - } - - def dec_Real_IEEE754_32_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1).toDouble) - } - - def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) - } - - - def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 0 - while i < 8 do - bitStream.appendByte0(b(i)) - i += 1 - } - - def dec_Real_IEEE754_64_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 0 - while i < 8 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) - } - - - def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array - - var i: Int = 3 - while i >= 0 do - bitStream.appendByte0(b(i)) - i -= 1 - } - - def dec_Real_IEEE754_32_little_endian(): Option[Double] = { - dec_Real_IEEE754_32_little_endian_fp32() match - case None() => None() - case Some(f) => Some(f.toDouble) - } - - def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 3 - while i >= 0 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) - } - - def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 7 - while i >= 0 do - bitStream.appendByte0(b(i)) - i -= 1 - } - - def dec_Real_IEEE754_64_little_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 7 - while i >= 0 do - bitStream.readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 - - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) - } - - - /* String functions*/ - def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { - var i: Long = 0 - while i < max do - bitStream.appendByte(strVal(i.toInt), false) - i += 1 - } - - def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { - var i: Long = 0 - while (i < max) && (strVal(i.toInt) != '\u0000') do - bitStream.appendByte(strVal(i.toInt), false) - i += 1 - - i - } - - def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - bitStream.appendByte(null_character.toByte, false) - } - - def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - var i: Int = 0 - while i < null_character_size do - bitStream.appendByte(null_character(i), false) - i += 1 - } - - - def enc_String_Ascii_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { - enc_String_Ascii_private(max, strVal) - } - - def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_Ascii_private(max, strVal) - } - - def enc_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { - var i: Int = 0 - while i < max do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) - i += 1 - } - - def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { - var i: Int = 0 - while (i < max) && (strVal(i) != '\u0000') do - val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - BitStream_EncodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) - i += 1 - - i - } - - - def enc_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Unit = { - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - - def enc_IA5String_CharIndex_External_Field_Determinant(max: Long, strVal: Array[ASCIIChar]): Unit = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - def enc_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - val strLen: Int = strVal.length - BitStream_EncodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) - enc_String_CharIndex_private(max, allowedCharSet, strVal) - } - - - def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i < charactersToDecode do - bitStream.readByte() match - case None() => return None() - case Some(decodedCharacter) => - strVal(i) = decodedCharacter - i += 1 - Some(strVal) - } - - - def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { - dec_String_Ascii_private(max, max) - } - - def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i <= max do - bitStream.readByte() match - case None() => return None() - case Some(decodedCharacter) => - if decodedCharacter != null_character then - strVal(i) = decodedCharacter - i += 1 - else - strVal(i) = 0x0 - return Some(strVal) - - None() - - } - - def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { - val sz: Int = if null_character_size < 10 then null_character_size else 10 - val tmp: Array[Byte] = Array.fill(10)(0) - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - //read null_character_size characters into the tmp buffer - var j: Int = 0 - while j < null_character_size do - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub - j += 1 - - - var i: Int = 0 - while i <= max && !null_character.sameElements(tmp) do - strVal(i) = tmp(0) - i += 1 - j = 0 - while j < null_character_size - 1 do - tmp(j) = tmp(j + 1) - j += 1 - - bitStream.readByte() match - case None() => return None() - case Some(ub) => tmp(null_character_size - 1) = ub - - strVal(i) = 0x0 - - if !null_character.sameElements(tmp) then - return None() - - Some(strVal) - } - - - def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) - } - - def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_Ascii_private(max, if nCount <= max then nCount else max) - } - - def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { - val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) - var i: Int = 0 - while i < charactersToDecode do - BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match - case None() => return None() - case Some(charIndex) => - strVal(i) = allowedCharSet(charIndex.toInt) - i += 1 - - Some(strVal) - } - - def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { - dec_String_CharIndex_private(max, max, allowedCharSet) - } - - def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) - } - - - def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) - } - - - def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) - } - - def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { - val allowedCharSet: Array[ASCIIChar] = Array( - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, - 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, - 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, - 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, - 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, - 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F - ) - BitStream_DecodeConstraintWholeNumber(min, max) match - case None() => None() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) - } - - - /* Length Determinant functions*/ - def enc_Length(lengthValue: ULong, lengthSizeInBits: Int): Unit = { - /* encode length */ - enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) - } - - def dec_Length(lengthSizeInBits: Int): Option[ULong] = { - dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) - } - - def milbus_encode(v: Long): Long = { - if v == 32 then 0 else v - } - - def milbus_decode(v: Long): Long = { - if v == 0 then 32 else v - } - - def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } -} diff --git a/asn1scc/asn1jvm_Codec_PER.scala b/asn1scc/asn1jvm_Codec_PER.scala deleted file mode 100644 index 8a497030c..000000000 --- a/asn1scc/asn1jvm_Codec_PER.scala +++ /dev/null @@ -1,13 +0,0 @@ -package asn1scala - - -/** - * Get an instance of a PER coded bitstream - * @param count of elements in underlaying buffer - * @return PER coded bitstream - */ -def initPERCodec(count: Int): PER = { - PER(BitStream(Array.fill(count)(0))) -} - -case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scc/asn1jvm_Codec_UPER.scala b/asn1scc/asn1jvm_Codec_UPER.scala deleted file mode 100644 index 6e31d64f4..000000000 --- a/asn1scc/asn1jvm_Codec_UPER.scala +++ /dev/null @@ -1,199 +0,0 @@ -package asn1scala - -import stainless.math.BitVectors._ -import stainless.lang.{None => None, Option => Option, Some => Some, _} - -/** - * Get an instance of a UPER coded bitstream - * @param count of elements in underlaying buffer - * @return UPER coded bitstream - */ -def initUPERCodec(count: Int): UPER = { - UPER(BitStream(Array.fill(count)(0))) -} - -case class UPER(bitStream: BitStream) extends Codec { - - def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { - var lastOctet: Boolean = false - val tmp: Array[UByte] = Array.fill(16)(0) - var nSize: Int = 0 - - var siValue = siValueVal - var pSize = pSizeVal - - while !lastOctet do - decreases(siValue) - val curByte: UByte = (siValue % 128).toByte - siValue = siValue / 128 - lastOctet = siValue.toInt == 0 - tmp(nSize) = curByte - nSize += 1 - - var i: Int = 0 - while i < nSize do - decreases(nSize - i) - val curByte: UByte = if i == nSize - 1 then tmp(nSize - i - 1) else (tmp(nSize - i - 1) | 0x80).toByte - encodingBuf(pSize) = curByte - pSize += 1 - i += 1 - return pSize - } - - def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(0) * 40 + pVal.values(1)) - - i = 0 - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) - i += 1 - } - - def relativeOID_encode(pVal: Asn1ObjectIdentifier): Unit = { - //a subIdentifier (i.e. a component) should not take more than size(asn1SccUint) + 2 to be encoded - //(the above statement is true for 8 byte integers. If we ever user larger integer then it should be adjusted) - val tmp: Array[UByte] = Array.fill(OBJECT_IDENTIFIER_MAX_LENGTH * (NO_OF_BYTES_IN_JVM_LONG + 2))(0) - var totalSize: Int = 0 - - var i: Int = 0 - - while i < pVal.nCount do - decreases(pVal.nCount - i) - totalSize = objectIdentifier_subIdentifiers_encode(tmp, totalSize, pVal.values(i)) - i += 1 - - - if totalSize <= 0x7F then - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) - else - bitStream.appendBit(true) - BitStream_EncodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) - - i = 0 - while i < totalSize do - decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) - i += 1 - } - - def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { - var bLastOctet: Boolean = false - var curOctetValue: ULong = 0 - var siValue: ULong = 0 - var pRemainingOctets: Long = pRemainingOctetsVal - while pRemainingOctets > 0 && !bLastOctet do - decreases(pRemainingOctets) - bitStream.readByte() match - case None() => return None() - case Some(curByte) => - pRemainingOctets -= 1 - - bLastOctet = (curByte & 0x80) == 0 - curOctetValue = (curByte & 0x7F).toLong - siValue = siValue << 7 - siValue |= curOctetValue - - return Some((pRemainingOctets, siValue)) - } - - - def objectIdentifier_decode_length(): Option[Long] = { - var totalSize: Long = 0 - - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return None() - case Some(l) => totalSize = l - - if totalSize > 0x7F then - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match - case None() => return None() - case Some(l) => - totalSize <<= 8 - totalSize |= l - totalSize &= 0x7FFF - - return Some(totalSize) - } - - def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - - val pVal = ObjectIdentifier_Init() - - objectIdentifier_decode_length() match - case None() => return NoneMut() - case Some(l) => totalSize = l - - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - - pVal.nCount = 2 - pVal.values(0) = si / 40 - pVal.values(1) = si % 40 - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() - - } - - def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 - val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() - - objectIdentifier_decode_length() match - case None() => return NoneMut() - case Some(l) => totalSize = l - - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do - decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul - pVal.values(pVal.nCount) = si - pVal.nCount += 1 - - //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() - } -} diff --git a/asn1scc/asn1jvm_Helper.scala b/asn1scc/asn1jvm_Helper.scala deleted file mode 100644 index c2e1e400a..000000000 --- a/asn1scc/asn1jvm_Helper.scala +++ /dev/null @@ -1,196 +0,0 @@ -package asn1scala - -import stainless.* -import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} -import stainless.collection.* -import stainless.annotation.* -import stainless.proof.* -import stainless.math.* -import StaticChecks.* - -// all bits of the integer -val MASK_BYTE = 0xFF -val MASK_BYTE_L = 0xFFL -val MASK_SHORT_L = 0xFF_FFL -val MASK_INT_L = 0xFF_FF_FF_FFL - -// MSBs (neg bits of the integer) -val MASK_MSB_BYTE = 0x80L -val MASK_MSB_INT = 0x80_00_00_00L - -// pos bits of the integer -val MASK_POS_BYTE = 0x7FL -val MASK_POS_INT = 0x7F_FF_FF_FFL - -/* -* Meths to upcast unsigned integer data types on the JVM -*/ -extension (ub: UByte) { - def unsignedToLong: Long = ub & MASK_BYTE_L - def unsignedToInt: Int = ub.toInt & MASK_BYTE -} - -extension (us: UShort) { - def unsignedToLong: Long = us & MASK_SHORT_L -} - -extension (ui: UInt) { - def unsignedToLong: Long = ui & MASK_INT_L -} - -extension (i: Int) { - def toUnsignedByte: UByte = { - require(i >= 0 && i <= MASK_BYTE) - - if(i == MASK_MSB_BYTE) - (-MASK_MSB_BYTE).toByte - else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) - ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte - else - i.toByte - } -} - -extension (l: Long) { - def toUnsignedInt: UInt = { - require(l >= 0 && l <= MASK_INT_L) - - if(l == MASK_MSB_INT) - (-MASK_MSB_INT).toInt - else if ((l & MASK_MSB_INT) == MASK_MSB_INT) - ((l & MASK_POS_INT) - MASK_MSB_INT).toInt - else - l.toInt - } -} - -extension (b: Byte) { - def >>>>(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte - } - - def <<<<(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt << i) & MASK_BYTE).toUnsignedByte - } -} - - -def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { - if v >>> 8 == 0 then - (v, 0) - else if v >>> 16 == 0 then - (v >>> 8, 8) - else if v >>> 24 == 0 then - (v >>> 16, 16) - else - (v >>> 24, 24) -}.ensuring((v, n) => v >= 0 &&& v <= 0xFF &&& n >= 0 &&& n <= 24) - -def GetNumberOfBitsInLastByteRec (vVal: UInt, n: UInt): Int = { - require(vVal >= 0 && vVal <= 0xFF) - require(n >= 0 && n <= 8) - require(1<<(8-n) > vVal) - decreases(8-n) - - if(vVal == 0) then - n - else - GetNumberOfBitsInLastByteRec(vVal >>> 1, n+1) -} - -def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { - val (v, n) = GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(vVal) - n + GetNumberOfBitsInLastByteRec(v, 0) -} - -def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { - if v >>> 32 == 0 then - GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) - else - val h = (v >>> 32).toUnsignedInt - 32 + GetNumberOfBitsForNonNegativeInteger32(h) -}.ensuring(n => n >= 0 && n <= 64) - -def GetLengthInBytesOfUInt (v: ULong): Int = { - GetLengthInBytesOfSInt(v) // just call signed, is signed anyway -}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) - -def GetLengthInBytesOfSInt (v: Long): Int = { - max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte -}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) - -/** -Binary encoding will be used -REAL = M*B^E -where -M = S*N*2^F - -ENCODING is done within three parts -part 1 is 1 byte header -part 2 is 1 or more byte for exponent -part 3 is 3 or more byte for mantissa (N) - -First byte -S :0-->+, S:1-->-1 -Base will be always be 2 (implied by 6th and 5th bit which are zero) -ab: F (0..3) -cd:00 --> 1 byte for exponent as 2's complement -cd:01 --> 2 byte for exponent as 2's complement -cd:10 --> 3 byte for exponent as 2's complement -cd:11 --> 1 byte for encoding the length of the exponent, then the exponent - -8 7 6 5 4 3 2 1 -+-+-+-+-+-+-+-+-+ -|1|S|0|0|a|b|c|d| -+-+-+-+-+-+-+-+-+ - **/ - -def CalculateMantissaAndExponent(doubleAsLong64: Long): (UInt, ULong) = { - require({ - val rawExp = (doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits - rawExp >= 0 &&& rawExp <= ((1 << 11) - 2) // 2046, 2047 is the infinity case - never end up here with infinity - }) - - val exponent: UInt = ((doubleAsLong64 & ExpoBitMask) >>> DoubleNoOfMantissaBits).toInt - DoubleBias.toInt - DoubleNoOfMantissaBits.toInt - var mantissa: ULong = doubleAsLong64 & MantissaBitMask - mantissa = mantissa | MantissaExtraBit - - (exponent, mantissa) - -}.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) - &&& m >= 0 &&& m <= MantissaBitMask) - -def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { - ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) -} - -/** -Helper function for REAL encoding - -Negative Ints always need 4 bytes of space, the ASN.1 standard compacts those numbers down -to 8, 16 or 24 bits depending on the leading bytes full of 1s. - -Example: --4 in Int: 0b1111_..._1111_1100 ---> compacted to 0b1111_1100 - -The ASN.1 header holds the detail on how to interpret this number - **/ -def RemoveLeadingFFBytesIfNegative(v: Int): Int = { - if v >= 0 then - v - else if v >= Byte.MinValue then - v & 0xFF - else if v >= Short.MinValue then - v & 0xFF_FF - else if v >= -8_388_608 then - v & 0xFF_FF_FF - else - v -} - -sealed trait OptionMut[@mutable A] -case class NoneMut[@mutable A]() extends OptionMut[A] -case class SomeMut[@mutable A](v: A) extends OptionMut[A] diff --git a/asn1scc/asn1jvm_Verification.scala b/asn1scc/asn1jvm_Verification.scala deleted file mode 100644 index c51aea393..000000000 --- a/asn1scc/asn1jvm_Verification.scala +++ /dev/null @@ -1,193 +0,0 @@ -package asn1scala - -import stainless.* -import stainless.lang.* -import stainless.collection.* -import stainless.annotation.{wrapping => _, *} -import stainless.proof.* -import stainless.math.* -import StaticChecks.* - -val masksc: Array[Byte] = Array( - 0x00, // / 0000 0000 / - -0x80, // / 1000 0000 / - -0x40, // / 1100 0000 / - -0x20, // / 1110 0000 / - -0x10, // / 1111 0000 / - -0x08, // / 1111 1000 / - -0x04, // / 1111 1100 / - -0x02, // / 1111 1110 / -) - -def arrayRangesEqOffset[T](a1: Array[T], a2: Array[T], fromA1: Int, toA1: Int, fromA2: Int): Boolean = { - require(0 <= fromA1 && fromA1 <= toA1) - require(toA1 <= a1.length) - require(0 <= fromA2 && fromA2 <= a2.length - (toA1 - fromA1)) - decreases(toA1 - fromA1) - if (fromA1 == toA1) true - else a1(fromA1) == a2(fromA2) && arrayRangesEqOffset(a1, a2, fromA1 + 1, toA1, fromA2 + 1) -} - -def arrayCopyOffset[T](src: Array[T], dst: Array[T], fromSrc: Int, toSrc: Int, fromDst: Int): Unit = { - require(0 <= fromSrc && fromSrc <= toSrc) - require(toSrc <= src.length) - require(0 <= fromDst && fromDst <= dst.length - (toSrc - fromSrc)) - decreases(toSrc - fromSrc) - - if (fromSrc < toSrc) { - dst(fromDst) = src(fromSrc) - arrayCopyOffset(src, dst, fromSrc + 1, toSrc, fromDst + 1) - } -} - -def arrayCopyOffsetLen[T](src: Array[T], dst: Array[T], fromSrc: Int, fromDst: Int, len: Int): Unit = { - require(0 <= len && len <= src.length && len <= dst.length) - require(0 <= fromSrc && fromSrc <= src.length - len) - require(0 <= fromDst && fromDst <= dst.length - len) - arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) -} - -def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { - require(0 <= len && len <= src.length) - require(0 <= startInDst && startInDst <= src.length - len) - require(src.length <= dst.length) - arrayCopyOffset(src, dst, 0, len, startInDst) -} - -def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = - a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) - -// TODO: Reimplement in terms of arrayRangesEqOffset -def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - decreases(to - from) - if (from == to) true - else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) -} -@opaque @inlineOnce -def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { - require(0 <= at && at < a.length) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(0 <= i && i <= at) - require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) - decreases(i) - if (i == 0) () - else rec(i - 1) - }.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) - } - - rec(at) -}.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) -} - -def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { - require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) - val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt - val arrPrefixEnd = (toBit / 8).toInt - val fromBitIx = (fromBit / 8).toInt - val toBitIx = (toBit / 8).toInt - (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) -} - -def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { - require(0 <= from && from <= to && to <= 7) - ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) -} - -def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { - require(a1.length <= a2.length) - require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) - require(fromBit < a1.length.toLong * 8) - (fromBit < toBit) ==> { - val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) - val restFrom = (fromBit % 8).toInt - val restTo = (toBit % 8).toInt - ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { - if (fromBitIx == toBitIx) { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) - } else { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && - ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) - } - } - } -} - -@opaque @inlineOnce -def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - require(from <= at && at < to) - require(arrayPrefix(a1, a2, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= at) - require(arrayPrefix(a1, a2, i, to)) - decreases(to - i) - if (i == at) () - else rec(i + 1) - }.ensuring { _ => - a1(at) == a2(at) - } - - rec(from) -}.ensuring(_ => a1(at) == a2(at)) - -@opaque @inlineOnce -def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to < a1.length) - require(arrayPrefix(a1, a2, from, to)) - require(a1(to) == a2(to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= to) - require(arrayPrefix(a1, a2, i, to + 1)) - decreases(i) - if (i == from) () - else { - arrayPrefixImpliesEq(a1, a2, from, i - 1, to) - rec(i - 1) - } - }.ensuring { _ => - arrayPrefix(a1, a2, from, to + 1) - } - - rec(to) -}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) - -@opaque @inlineOnce -def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { - require(0 <= from && from <= mid && mid <= to) - require(a1.length <= a2.length && a2.length <= a3.length) - require(mid <= a1.length && to <= a2.length) - require(arrayPrefix(a1, a2, from, mid)) - require(arrayPrefix(a2, a3, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= mid) - require(arrayPrefix(a1, a2, i, mid)) - require(arrayPrefix(a2, a3, i, to)) - require(arrayPrefix(a1, a3, from, i)) - decreases(to - i) - if (i == mid) () - else { - arrayPrefixAppend(a1, a3, from, i) - rec(i + 1) - } - }.ensuring { _ => - arrayPrefix(a1, a3, from, mid) - } - rec(from) -}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) diff --git a/asn1scc/asn1scc.fsproj b/asn1scc/asn1scc.fsproj index dcba42c18..0589a4448 100644 --- a/asn1scc/asn1scc.fsproj +++ b/asn1scc/asn1scc.fsproj @@ -8,12 +8,24 @@ - - - - - - + + asn1jvm.scala + + + asn1jvm_Bitstream.scala + + + + + + + + + build.sbt + + + stainless-library_2.13-0.9.7.jar + @@ -87,20 +99,7 @@ - - - asn1jvm.scala - - - build.sbt - - - stainless-library_2.13-0.9.7.jar - - - asn1jvm_Bitstream.scala - - + From b642672cb098b890c29b2209560b9f66a8e8b9ee Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 30 Oct 2023 22:40:10 +0100 Subject: [PATCH 061/174] WIP: uper codec --- StgScala/uper_scala.stg | 30 ++++++++-------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 36 +++++++++---------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 8 ++--- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 4 +-- 4 files changed, 39 insertions(+), 39 deletions(-) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index efe6489a0..71386af55 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -95,7 +95,7 @@ codec.encodeConstraintWholeNumber(charIndex, 0, ) InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< asn1SccSint charIndex = 0; -val worked = BitStream_DecodeConstraintWholeNumber(pBitStrm, &charIndex, 0, ) +val worked = codec.decodeConstraintWholeNumber(&charIndex, 0, ) if !worked then ret =

[] = if (worked) then allowedCharSet[charIndex] else '\0' @@ -106,7 +106,7 @@ codec.encodeConstraintWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -BitStream_DecodeConstraintWholeNumberByte(pBitStrm, 0, 127) match // uper:109 +codec.decodeConstraintWholeNumberByte(0, 127) match // uper:109 case Some(c) =>

() = c case None() => @@ -122,7 +122,7 @@ codec.encodeConstraintWholeNumber(

, , ) >> IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:122 +codec.decodeConstraintWholeNumber(, ) match // uper:122 case Some(n) =>

= n case None() => @@ -277,7 +277,7 @@ Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, n >> Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match // uper:277 +codec.decodeConstraintWholeNumber(0, ) match // uper:277 case Some(x) => x match @@ -317,7 +317,7 @@ choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, >> choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match // uper:317 +codec.decodeConstraintWholeNumber(0, ) match // uper:317 case Some(choice) => choice match }; separator="\n"> @@ -444,7 +444,7 @@ codec.encodeConstraintWholeNumber(

nCount, , ) >> seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:444 +codec.decodeConstraintWholeNumber(, ) match // uper:444 case Some(n) =>

nCount = n.asInstanceOf[Int] case None() => @@ -475,7 +475,7 @@ if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCoun octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << // decode length -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:475 +codec.decodeConstraintWholeNumber(, ) match // uper:475 case Some(n) => assert(n >= 0)

nCount = n @@ -509,7 +509,7 @@ codec.encodeConstraintWholeNumber(

nCount, , ) >> bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match // uper:509 +codec.decodeConstraintWholeNumber(, ) match // uper:509 case Some(n) =>

nCount = n case None() => @@ -645,7 +645,7 @@ FixedSize_Fragmentation_sqf_64K_decode(p, sAcc,sCurOffset, sCurBlockSize, sBlock = 0; *pErrCode = ; for( = 0; ret && \< ; ++) { - ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) + ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) val check = (ret == 0) && ( == 0xC4); ret = if (check) then Right(0) else Left() if ret == 0 then @@ -671,7 +671,7 @@ for( = 0; ret && \< ; ++) { FixedSize_Fragmentation_sqf_small_block_decode(p, sAcc,sInternalItem, nBlockSize, sBlockId, sCurOffset, sCurBlockSize, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::=<< //decode a single Block with items = ; -ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) +ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) val check = (ret == 0) && ( == ); ret = if (check) then Right(0) else Left() if ret.isRight then @@ -693,11 +693,11 @@ if ret.isRight then FixedSize_Fragmentation_sqf_remaining_decode(p, sAcc,sInternalItem, bRemainingItemsWithinByte, nRemainingItemsVar, sCurOffset, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::= << //decode remaining items -ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, , 0, 0xFF) +ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) ret = ret && ( == ); -ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, , 0, 0xFFFF) +ret = codec.decodeConstraintWholeNumber(, 0, 0xFFFF) ret = ret && ((0x8000 & ) > 0) && ( (0x7FFF & ) == ); @@ -733,7 +733,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0 -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:733 +codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:733 case None() => return Left() case Some(x) => @@ -770,7 +770,7 @@ while(( & 0xC0) == 0xC0) { += += - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:770 + codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:770 case None() => return Left() case Some(x) => @@ -780,7 +780,7 @@ while(( & 0xC0) == 0xC0) { if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 - BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, 0xFF) match // uper:780 + codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:780 case None() => return Left() case Some(x) => diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index dcde69ff6..782c593ac 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -228,7 +228,7 @@ trait Codec { encodeNonNegativeInteger(v - min) } - def BitStream_DecodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { + def decodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { val range: ULong = (max - min) @@ -246,42 +246,42 @@ trait Codec { def BitStream_DecodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { - BitStream_DecodeConstraintWholeNumber(min.toLong, max.toLong) match + decodeConstraintWholeNumber(min.toLong, max.toLong) match case None() => None() case Some(l) => Some(l.toByte) } def BitStream_DecodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { - BitStream_DecodeConstraintWholeNumber(min, max) match + decodeConstraintWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toShort) } def BitStream_DecodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { - BitStream_DecodeConstraintWholeNumber(min, max) match + decodeConstraintWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toInt) } def BitStream_DecodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toByte) } def BitStream_DecodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toShort) } def BitStream_DecodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { - BitStream_DecodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toInt) } @@ -333,7 +333,7 @@ trait Codec { var nBytes: Long = 0 var v: Long = 0 - BitStream_DecodeConstraintWholeNumber(0, 255) match + decodeConstraintWholeNumber(0, 255) match case None() => return None() case Some(l) => nBytes = l @@ -356,7 +356,7 @@ trait Codec { var nBytes: Long = 0 var v: ULong = 0 - BitStream_DecodeConstraintWholeNumber(0, 255) match + decodeConstraintWholeNumber(0, 255) match case None() => return None() case Some(l) => nBytes = l @@ -393,7 +393,7 @@ trait Codec { var nBytes: Long = 0 - BitStream_DecodeConstraintWholeNumber(0, 255) match + decodeConstraintWholeNumber(0, 255) match case None() => return None() case Some(l) => nBytes = l @@ -772,7 +772,7 @@ trait Codec { var nCurOffset1: Long = 0 // get header data - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -807,7 +807,7 @@ trait Codec { nCurOffset1 += nCurBlockSize1 // get next header - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -816,7 +816,7 @@ trait Codec { nRemainingItemsVar1 <<= 8 // put upper at correct position // get size (lower byte) - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size @@ -867,7 +867,7 @@ trait Codec { if asn1SizeMax < 65536 then var nCount: Int = 0 if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + decodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match case None() => return NoneMut() case Some(l) => nCount = l.toInt else @@ -935,7 +935,7 @@ trait Codec { if (asn1SizeMax < 65536) { var nCount: Long = 0 if asn1SizeMin != asn1SizeMax then - BitStream_DecodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + decodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match case None() => return NoneMut() case Some(l) => nCount = l else @@ -948,7 +948,7 @@ trait Codec { var nCurBlockSize1: Long = 0 var nCurOffset1: Long = 0 var nLengthTmp1: Long = 0 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -977,13 +977,13 @@ trait Codec { arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 0150111ea..57c4e6d1c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -1042,7 +1042,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match + decodeConstraintWholeNumber(min, max) match case None() => None() case Some(nCount) => dec_String_Ascii_private(max, if nCount <= max then nCount else max) @@ -1052,7 +1052,7 @@ case class ACN(bitStream: BitStream) extends Codec { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i < charactersToDecode do - BitStream_DecodeConstraintWholeNumber(0, allowedCharSet.length - 1) match + decodeConstraintWholeNumber(0, allowedCharSet.length - 1) match case None() => return None() case Some(charIndex) => strVal(i) = allowedCharSet(charIndex.toInt) @@ -1071,7 +1071,7 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { - BitStream_DecodeConstraintWholeNumber(min, max) match + decodeConstraintWholeNumber(min, max) match case None() => None() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) @@ -1113,7 +1113,7 @@ case class ACN(bitStream: BitStream) extends Codec { 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) - BitStream_DecodeConstraintWholeNumber(min, max) match + decodeConstraintWholeNumber(min, max) match case None() => None() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index c8e43986a..bafa7291e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -117,12 +117,12 @@ case class UPER(bitStream: BitStream) extends Codec { def objectIdentifier_decode_length(): Option[Long] = { var totalSize: Long = 0 - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return None() case Some(l) => totalSize = l if totalSize > 0x7F then - BitStream_DecodeConstraintWholeNumber(0, 0xFF) match + decodeConstraintWholeNumber(0, 0xFF) match case None() => return None() case Some(l) => totalSize <<= 8 From cfd9353dcaab4193197851be9ac965831aa8df02 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Tue, 31 Oct 2023 13:10:01 +0100 Subject: [PATCH 062/174] OOP refactoring of UPER and ACN --- BackendAst/EncodeDecodeTestCase.fs | 7 +- CommonTypes/AbstractMacros.fs | 2 +- StgAda/test_cases_a.stg | 2 +- StgC/test_cases_c.stg | 2 +- StgScala/acn_scala.stg | 104 +++++++++--------- StgScala/test_cases_scala.stg | 12 +- StgScala/uper_scala.stg | 92 ++++++++-------- .../scala/asn1scala/asn1jvm_Bitstream.scala | 21 +++- .../main/scala/asn1scala/asn1jvm_Codec.scala | 70 ++++++++++++ 9 files changed, 201 insertions(+), 111 deletions(-) diff --git a/BackendAst/EncodeDecodeTestCase.fs b/BackendAst/EncodeDecodeTestCase.fs index 6335789a5..35553a317 100644 --- a/BackendAst/EncodeDecodeTestCase.fs +++ b/BackendAst/EncodeDecodeTestCase.fs @@ -114,7 +114,7 @@ let _createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1 printStatements [Encode_input; Decode_output; Validate_output; Compare_input_output; Write_bitstream_to_file] let func = - printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName "" (sNestedStatements.orElse "") + printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName "" (sNestedStatements.orElse "") "UPER" let funcDef = printCodec_body_header funcName modName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName let ret = { @@ -132,9 +132,10 @@ let createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : AcnFunction option) (decFunc : AcnFunction option) (us:State) = + //let sEnc = match ST.lang with | Scala -> "ACN" | _ -> lm.lg.atc.acnPrefix let sEnc = lm.lg.atc.acnPrefix - let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefintion) + let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefintion) let modName = ToC t.id.AcnAbsPath.Head let printCodec_body = lm.atc.PrintCodec_body @@ -201,7 +202,7 @@ let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A printStatements [Encode_input; Decode_output; Validate_output; Compare_input_output; Write_bitstream_to_file] - let func = printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName sEnc (sNestedStatements.orElse "") + let func = printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName sEnc (sNestedStatements.orElse "") "ACN" let funcDef = printCodec_body_header funcName modName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName let ret = diff --git a/CommonTypes/AbstractMacros.fs b/CommonTypes/AbstractMacros.fs index dbbed809f..b851bbd8b 100644 --- a/CommonTypes/AbstractMacros.fs +++ b/CommonTypes/AbstractMacros.fs @@ -514,7 +514,7 @@ Generated by the C stg macros with the following command abstract member Codec_declare_EncInDecOut_variable : sPrmName:string -> sType:string -> sPrmValue:string -> string; abstract member Codec_declare_DecIn_variable : sPrmName:string -> sType:string -> string; abstract member PrintCodec_spec : sFuncName:string -> sModName:string -> sTasName:string -> sStar:string -> sVal:string -> string; - abstract member PrintCodec_body : sModName:string -> sFuncName:string -> sTasName:string -> sStar:string -> sVal:string -> sEnc:string -> sNestedStatements:string -> string; + abstract member PrintCodec_body : sModName:string -> sFuncName:string -> sTasName:string -> sStar:string -> sVal:string -> sEnc:string -> sNestedStatements:string -> sCodecClass:string -> string; abstract member PrintCodec_body_XER : sModName:string -> sFuncName:string -> sTasName:string -> sStar:string -> sVal:string -> sEnc:string -> sNestedStatements:string -> string; abstract member PrintMain : sTestSuiteFilename:string -> string; abstract member PrintSuite_call_codec_generate_dat_file : sModName:string -> sTasName:string -> sAmber:string -> sEnc:string -> sStreamName:string -> string; diff --git a/StgAda/test_cases_a.stg b/StgAda/test_cases_a.stg index 07207f328..d95b32c9d 100644 --- a/StgAda/test_cases_a.stg +++ b/StgAda/test_cases_a.stg @@ -152,7 +152,7 @@ Codec_declare_DecIn_variable(sPrmName, sType) ::= "dec_ : ;" -PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements) ::= << +PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements, sCodecClass) ::= << function (:.; Filename : in String) return .TEST_CASE_RESULT is decodedPDU : .; diff --git a/StgC/test_cases_c.stg b/StgC/test_cases_c.stg index 929c7bc07..93de52549 100644 --- a/StgC/test_cases_c.stg +++ b/StgC/test_cases_c.stg @@ -135,7 +135,7 @@ PrintCodec_spec(sFuncName, sModName, sTasName, sStar, sVal) ::= << flag (const , int* pErrCode, const char* filename); >> -PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements) ::= << +PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements, sCodecClass) ::= << flag (const , int* pErrCode, const char* filename) { static decodedPDU; diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index bb26d6887..8dd01187f 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -18,7 +18,7 @@ EmitTypeAssignment_primitive_def_encode(sVarName, sStar, sFuncName, sTypeDefName >> EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << -def (@annotation.unused : , @annotation.unused pBitStrm: BitStream, bCheckConstraints: Boolean): Either[ErrorCode, Int] = // acn:21 +def (@annotation.unused : , @annotation.unused codec: ACN, bCheckConstraints: Boolean): Either[ErrorCode, Int] = // acn:21 { var ret: Either[ErrorCode, Int] = Right(0) @@ -42,7 +42,7 @@ EmitTypeAssignment_primitive_def_decode(sVarName, sStar, sFuncName, sTypeDefName >> EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << -def (@annotation.unused pBitStrm: BitStream): Either[ErrorCode, ] = +def (@annotation.unused codec: ACN): Either[ErrorCode, ] = { var : = () var ret: Either[ErrorCode, ] = Right() @@ -90,13 +90,13 @@ codec.alignTo() >> alignToNext_decode(sMainBody, sAligmentValue, nAligmentValue) ::= << -codec.alignTo(pBitStrm) +codec.alignTo() >> PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize(_encode(

)

, )" PositiveInteger_ConstSize_decode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize) match +codec.dec_Int_PositiveInteger_ConstSize() match case None() => return Left() case Some(x) =>

= x @@ -104,7 +104,7 @@ codec.dec_Int_PositiveInteger_ConstSize) match PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_8(_encode(

)

)" PositiveInteger_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_8() match case None() => return Left() case Some(x) =>

= x @@ -112,7 +112,7 @@ codec.dec_Int_PositiveInteger_ConstSize_8() match case None() => return Left() case Some(x) =>

= x @@ -120,7 +120,7 @@ codec.dec_Int_PositiveInteger_ConstSize_big_endian_16() match case None() => return Left() case Some(x) =>

= x @@ -319,7 +319,7 @@ codec.dec_Real_IEEE754_32_big_endian() match Real_64_big_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_big_endian(

)" Real_64_big_endian_decode(p, sErrCode) ::= << -codec.dec_Real_IEEE754_64_big_endian(match +codec.dec_Real_IEEE754_64_big_endian() match case None() => return Left() case Some(x) =>

= x >> @@ -333,7 +333,7 @@ codec.dec_Real_IEEE754_32_little_endian() match Real_64_little_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_little_endian(

)" Real_64_little_endian_decode(p, sErrCode) ::= << -codec.dec_Real_IEEE754_64_little_endian(match +codec.dec_Real_IEEE754_64_little_endian() match case None() => return Left() case Some(x) => @@ -345,7 +345,7 @@ Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse { var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - pBitStrm.appendBits(if

then true_data else false_data, ) + codec.appendBits(if

then true_data else false_data, ) } >> @@ -356,7 +356,7 @@ Boolean_decode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse var tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - BitStream_ReadBitPattern(pBitStrm, tmp, ) match + codec.BitStream_ReadBitPattern(tmp, ) match case None() => return Left() case Some(x) => @@ -370,7 +370,7 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - pBitStrm.appendBits(tmp, ) + codec.appendBits(tmp, ) } >> @@ -378,7 +378,7 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav Null_pattern_decode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << -BitStream_ReadBitPattern_ignore_value(pBitStrm, ) match +codec.BitStream_ReadBitPattern_ignore_value() match case None() => ret = Left() case Some(i) => ret = Right(i) @@ -386,7 +386,7 @@ BitStream_ReadBitPattern_ignore_value(pBitStrm, ) match { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - BitStream_ReadBitPattern(pBitStrm, tmp, ) match + codec.BitStream_ReadBitPattern(tmp, ) match case None() => ret = Left() case Some(b) => if !b then ret = Left() @@ -522,7 +522,7 @@ codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount.toInt) match +codec.BitStream_EncodeOctetString_no_length(

arr,

nCount.toInt) match case false => return Left() case true => ret = Right(0) >> @@ -530,20 +530,20 @@ BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount.to oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then

nCount = .asInstanceOf[Int] - BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.toInt) match + codec.BitStream_DecodeOctetString_no_length(

nCount.toInt) match case NoneMut() => return Left() case SomeMut(x) => x.copyToArray(

arr) >> oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -BitStream_EncodeOctetString_no_length(pBitStrm,

arr, ) match +codec.BitStream_EncodeOctetString_no_length(

arr, ) match case false => return Left() case true => ret = Right(0) >> oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then - BitStream_DecodeOctetString_no_length(pBitStrm, ) match + codec.BitStream_DecodeOctetString_no_length() match case NoneMut() => return Left() case SomeMut(x) =>

arr = x >> @@ -570,18 +570,18 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -pBitStrm.appendBits((byte[]){}, ) +codec.appendBits((byte[]){}, ) >> oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << = 0 ret = Right(0) -while ret.isRight && \< && ((checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, (byte[]){}, )) == 1)) do +while ret.isRight && \< && ((checkBitPatternPresentResult = codec.BitStream_checkBitPatternPresent((byte[]){}, )) == 1)) do += 1 if ret.isRight && ( == ) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(pBitStrm, (byte[]){}, ) + checkBitPatternPresentResult = codec.BitStream_checkBitPatternPresent((byte[]){}, ) if (ret && (checkBitPatternPresentResult == 0)) { ret = FALSE; /*COVERAGE_IGNORE*/ @@ -594,13 +594,13 @@ if (ret && (checkBitPatternPresentResult == 0)) { >> bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -pBitStrm.appendBits(

arr,

nCount) +codec.appendBits(

arr,

nCount) >> bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then

nCount = .asInstanceOf[Int] - pBitStrm.readBits(

nCount) match + codec.readBits(

nCount) match case NoneMut() => return Left() case SomeMut(arr) =>

arr = arr @@ -608,12 +608,12 @@ if (\<=) && (\<=) t >> bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -pBitStrm.appendBits(

arr, ) +codec.appendBits(

arr, ) >> bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then - pBitStrm.readBits() match + codec.readBits() match case NoneMut() => return Left() case SomeMut(arr) =>

arr = arr @@ -621,8 +621,8 @@ if (\<=) && (\<=) t >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -pBitStrm.appendBits(

arr,

nCount) -pBitStrm.appendBits((byte[]){}, ) +codec.appendBits(

arr,

nCount) +codec.appendBits((byte[]){}, ) >> bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << @@ -637,21 +637,21 @@ RefTypeParam_tmpVar(sName, sTypeDecl) ::= " " ReferenceType1_encode(p, sName, bAcnEncodeFuncRequiresResult, arrsArgs, arrsLocalPrms) ::= << = ;// 3031}; separator="\n"> -ret = _ACN_Encode(

, pBitStrm, pErrCode, FALSE, ) +ret = _ACN_Encode(

, codec, pErrCode, FALSE, ) >> ReferenceType1_decode(p, sName, bAcnEncodeFuncRequiresResult, arrsArgs, arrsLocalPrms) ::= << = ; // 3030}; separator="\n"> -ret = _ACN_Decode(

, pBitStrm, pErrCode, ) +ret = _ACN_Decode(

, codec, pErrCode, ) >> /* SEQUENCE*/ -sequence_presense_optChild_encode(p, sAcc, sChName, sErrCode) ::= "pBitStrm.appendBit(

exist.)" +sequence_presense_optChild_encode(p, sAcc, sChName, sErrCode) ::= "codec.appendBit(

exist.)" sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << -pBitStrm.readBit() match +codec.readBit() match case Some(bit) =>

exist. = bit case None() => @@ -799,11 +799,11 @@ else >> sequence_call_post_encoding_function(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << -(

, &, &, pBitStrm) +(

, &, &, codec) >> sequence_call_post_decoding_validator(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << -ret = (

, &, &, pBitStrm, pErrCode) +ret = (

, &, &, codec, pErrCode) >> /* SEQUENCE END */ @@ -822,7 +822,7 @@ case => ChoiceChild_encode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case () => - BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, ) + codec.BitStream_EncodeConstraintWholeNumber(, 0, ) >> @@ -841,7 +841,7 @@ Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_C >> Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << -BitStream_DecodeConstraintWholeNumber(pBitStrm, 0, ) match +codec.BitStream_DecodeConstraintWholeNumber(0, ) match case None() => return Left() case Some(x) => @@ -1019,7 +1019,7 @@ if ret.isRight then >> octet_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sExtField, sErrCode, soInner) ::= << -BitStream_EncodeOctetString_no_length(pBitStrm, arr, .asInstanceOf[Int]) match +codec.BitStream_EncodeOctetString_no_length(arr, .asInstanceOf[Int]) match case false => return Left() case true => @@ -1034,7 +1034,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then - BitStream_DecodeOctetString_no_length(pBitStrm, .asInstanceOf[Int]) match + codec.BitStream_DecodeOctetString_no_length(.asInstanceOf[Int]) match case NoneMut() => return Left() case SomeMut(arr) => @@ -1047,7 +1047,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -pBitStrm.appendBits(arr, .asInstanceOf[Int]) +codec.appendBits(arr, .asInstanceOf[Int]) >> bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << @@ -1056,7 +1056,7 @@ bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncodi /* decode to a temporary bitstream */ val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then - pBitStrm.readBits((int)) match + codec.readBits((int)) match case NoneMut() => return Left() case SomeMut(arr) => @@ -1080,15 +1080,15 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, nBits if ret.isRight then int nCount = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1) - BitStream_EncodeOctetString_no_length(pBitStrm, bitStrm.buf, nCount) match + codec.BitStream_EncodeOctetString_no_length(bitStrm.buf, nCount) match case false => return Left(pErrCode) case true => ret = Right(0) - BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount, , ) - BitStream_EncodeOctetString_no_length(pBitStrm, bitStrm.buf, nCount) match + codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) + codec.BitStream_EncodeOctetString_no_length(bitStrm.buf, nCount) match case false => return Left(pErrCode) case true => @@ -1105,7 +1105,7 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits val bitStrm: BitStream = BitStream_Init() - BitStream_DecodeOctetString_no_length(pBitStrm, ) match + codec.BitStream_DecodeOctetString_no_length() match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1113,14 +1113,14 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits var nCount: Int = 0 - BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match + codec.BitStream_DecodeConstraintWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => nCount = x if ret.isRight then - BitStream_DecodeOctetString_no_length(pBitStrm, nCount.asInstanceOf[Int]) + codec.BitStream_DecodeOctetString_no_length(nCount.asInstanceOf[Int]) case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1142,11 +1142,11 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit if ret.isRight then val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - pBitStrm.appendBits(bitStrm.buf, nCount); + codec.appendBits(bitStrm.buf, nCount); - BitStream_EncodeConstraintWholeNumber(pBitStrm, nCount, , ) - pBitStrm.appendBits(bitStrm.buf, nCount) + codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) + codec.appendBits(bitStrm.buf, nCount) } @@ -1156,10 +1156,10 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit /*open new scope to declare some variables*/ { /* decode to a temporary bitstream */ - val bitStrm: BitStream = BitStream_Init() + val codec: Codec = ACN(BitStream_Init()) - pBitStrm.readBits() match + codec.readBits() match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1170,14 +1170,14 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit var nCount: Int = 0 - BitStream_DecodeConstraintWholeNumber(pBitStrm, , ) match + codec.BitStream_DecodeConstraintWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => nCount = x ret = Right(0) - pBitStrm.readBits(nCount) match + codec.readBits(nCount) match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 6b9a99e51..792c223e7 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -53,16 +53,16 @@ import java.io._ Codec_Encode(sModName, sFuncName, sVal) ::= << // test_cases_scala.stg:54 // Encode value -(, bitStrm, true) match +(, codec, true) match case Left(_) => return Left(1) case Right(_) => () >> Codec_Decode(sModName, sFuncName, sTasName, sEnc, sAmber) ::= << // test_cases_scala.stg:62 -bitStrm.attachBuffer(bitStrm.buf) // TODO: reset curBit, curByte instead? +codec.bitStream.attachBuffer(codec.bitStream.buf) // TODO: reset curBit, curByte instead? // Decode value -(bitStrm) match +(codec) match case Left(_) => return Left(2) case Right(pVal) => decodedPDU = pVal >> @@ -99,7 +99,7 @@ Codec_write_bitstreamToFile() ::= << // test_cases_scala.stg:99 val file = new File(filename+".dat") val bw = new FileOutputStream(file) -bw.write(bitStrm.buf) +bw.write(codec.bitStream.buf) bw.close() >> @@ -125,14 +125,14 @@ PrintCodec_spec(sFuncName, sModName, sTasName, sStar, sVal) ::= << // test_cases_scala.stg:125 >> -PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements) ::= << +PrintCodec_body(sModName, sFuncName, sTasName, sStar, sVal, sEnc, sNestedStatements, sCodecClass) ::= << // test_cases_scala.stg:129 def (: , filename: String): Either[ErrorCode, Int] = { var ret: Either[ErrorCode, Int] = Right(0) var decodedPDU: = _Initialize() // TODO: does this always work? - val bitStrm = BitStream_Init(_REQUIRED_BYTES_FOR_ENCODING.toInt) // TODO: what to do with too large Longs? + val codec = initCodec(_REQUIRED_BYTES_FOR_ENCODING.toInt) // TODO: what to do with too large Longs? ret } diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 71386af55..e6ee12dc1 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -10,7 +10,7 @@ call_base_type_func_encode(p, sFuncName) ::= << return Left(err) >> call_base_type_func_decode(p, sFuncName) ::= << -codec.() match // uper:13 +(codec) match // uper:13 case Right(decData) =>

= decData case Left(err) => @@ -75,11 +75,11 @@ def (@annotation.unused codec: UPER): E >> InternalItem_oct_str_encode(p, sAcc, i, sErrCode) ::=<< -pBitStrm.appendByte0(

arr()) +codec.appendByte0(

arr()) >> InternalItem_oct_str_decode(p, sAcc, i, sErrCode) ::=<< -if !BitStream_ReadByte(pBitStrm,

arr()) then +if !codec.readByte(

arr()) then ret = Left() >> @@ -106,7 +106,7 @@ codec.encodeConstraintWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -codec.decodeConstraintWholeNumberByte(0, 127) match // uper:109 +codec.BitStream_DecodeConstraintWholeNumberByte(0, 127) match // uper:109 case Some(c) =>

() = c case None() => @@ -143,9 +143,9 @@ codec.decodeConstraintPosWholeNumber(, ) match // uper:135 >> /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" +IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.BitStream_EncodeUnConstraintWholeNumber(

);" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -BitStream_DecodeUnConstraintWholeNumber(pBitStrm) match // uper:145 +codec.BitStream_DecodeUnConstraintWholeNumber() match // uper:145 case Some(x) =>

= x case None() => @@ -153,23 +153,23 @@ BitStream_DecodeUnConstraintWholeNumber(pBitStrm) match // uper:145 >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" +IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.BitStream_EncodeUnConstraintWholeNumber(

);" IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << -if !BitStream_DecodeUnConstraintWholeNumber(pBitStrm,

) then +if !codec.BitStream_DecodeUnConstraintWholeNumber() then ret = if then 0 else >> /*case: A:: = INTEGER (-5..MAX) */ -IntSemiConstraint_encode(p, nMin, sErrCode) ::= "BitStream_EncodeSemiConstraintWholeNumber(pBitStrm,

, );" +IntSemiConstraint_encode(p, nMin, sErrCode) ::= "codec.BitStream_EncodeSemiConstraintWholeNumber(

, );" IntSemiConstraint_decode(p, nMin, sErrCode) ::= << -if !BitStream_DecodeSemiConstraintWholeNumber(pBitStrm,

, ) then +if !codec.BitStream_DecodeSemiConstraintWholeNumber() then ret = >> /*case: A:: = INTEGER (5..MAX) */ -IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "BitStream_EncodeSemiConstraintPosWholeNumber(pBitStrm,

, );" +IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "codec.BitStream_EncodeSemiConstraintPosWholeNumber(

, );" IntSemiConstraintPos_decode(p, nMin, sErrCode) ::= << -if !BitStream_DecodeSemiConstraintPosWholeNumber(pBitStrm,

, ) then +if !codec.BitStream_DecodeSemiConstraintPosWholeNumber() then ret = >> @@ -184,7 +184,7 @@ IntNoneRequired_decode(p, nConst, sErrCode) ::= << /*case: A:: = INTEGER (5..40,...) */ IntRootExt_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< -pBitStrm.appendBitZero() /* write extension bit*/ +codec.appendBitZero() /* write extension bit*/ >> @@ -193,7 +193,7 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< extBit: Ref[Boolean] = Ref(false) /* read extension bit*/ - val success = pBitStrm.readBit(extBit) + val success = codec.readBit(extBit) if success then if extBit == false then /* ext bit is zero ==> value is expecteted with root range*/ @@ -207,11 +207,11 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< /*case: A:: = INTEGER (5..40,..., 60..70) */ IntRootExt2_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< if then - pBitStrm.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ + codec.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ else /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ - pBitStrm.appendBitOne() + codec.appendBitOne() >> @@ -221,11 +221,11 @@ IntRootExt2_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=") +codec.appendBit(

) >> Boolean_decode(p, sErrCode) ::= << -pBitStrm.readBit() match // uper:225 +codec.readBit() match // uper:225 case Some(bit) =>

= bit case None() => @@ -241,21 +241,21 @@ codec.decodeReal() match // uper:234 return Left() >> -ObjectIdentifier_encode(p, sErrCode) ::= "ObjectIdentifier_uper_encode(pBitStrm,

);" +ObjectIdentifier_encode(p, sErrCode) ::= "codec.ObjectIdentifier_encode(

);" ObjectIdentifier_decode(p, sErrCode) ::= << -if !ObjectIdentifier_uper_decode(pBitStrm,

) then +if !codec.ObjectIdentifier_decode() then ret = >> -RelativeOID_encode(p, sErrCode) ::= "RelativeOID_uper_encode(pBitStrm,

);" +RelativeOID_encode(p, sErrCode) ::= "codec.RelativeOID_encode(

);" RelativeOID_decode(p, sErrCode) ::= << -if !RelativeOID_uper_decode(pBitStrm,

) then +if !codec.RelativeOID_decode() then return Left() >> -Time_encode(p, sTimeSubType, sErrCode) ::= "_uper_encode(pBitStrm,

);" +Time_encode(p, sTimeSubType, sErrCode) ::= "codec._encode(

);" Time_decode(p, sTimeSubType, sErrCode) ::= << -if !_uper_decode(pBitStrm,

) then +if !codec._decode() then return Left() >> @@ -330,16 +330,16 @@ codec.decodeConstraintWholeNumber(0, ) match // uper:317 /* CHOICE END*/ /* SEQUENCE START */ -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "pBitStrm.appendBit(

exist.);" +sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "codec.appendBit(

exist.);" sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << -pBitStrm.readBit() match // uper:332 +codec.readBit() match // uper:332 case Some(bit) =>

exist. = bit case None() => return Left() >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "pBitStrm.appendBit( )" +sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "codec.appendBit( )" sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << @@ -418,7 +418,7 @@ codec.encodeConstraintWholeNumber(nStringLength, , ) str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength = 0 -BitStream_DecodeConstraintWholeNumberInt(pBitStrm, , ) match // uper:418 +codec.BitStream_DecodeConstraintWholeNumberInt(, ) match // uper:418 case Some(n) => nStringLength = n

(nStringLength) = 0 // TODO do we need a 0 terminator? @@ -455,12 +455,12 @@ codec.decodeConstraintWholeNumber(, ) match // uper:444 >> octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << -if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr, .asInstanceOf[Int]) then +if !codec.BitStream_EncodeOctetString_no_length(

arr, .asInstanceOf[Int]) then ret = Left(446) >> octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << -BitStream_DecodeOctetString_no_length(pBitStrm, ) match // uper:460 +codec.BitStream_DecodeOctetString_no_length() match // uper:460 case SomeMut(x) => x.copyToArray(

arr) case NoneMut() => @@ -469,7 +469,7 @@ BitStream_DecodeOctetString_no_length(pBitStrm, ) match // uper:460 octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << codec.encodeConstraintWholeNumber(

nCount, , ) -if !BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount.asInstanceOf[Int]) then +if !codec.BitStream_EncodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) then ret = Left() >> @@ -483,7 +483,7 @@ codec.decodeConstraintWholeNumber(, ) match // uper:475 return Left() // decode payload -BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int]) match // uper:483 +codec.BitStream_DecodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // uper:483 case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -493,10 +493,10 @@ BitStream_DecodeOctetString_no_length(pBitStrm,

nCount.asInstanceOf[Int /* BIT STRING*/ bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast -pBitStrm.appendBits(

arr, .asInstanceOf[Int]) +codec.appendBits(

arr, .asInstanceOf[Int]) >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << -pBitStrm.readBits(.asInstanceOf[Int]) match // uper:496 +codec.readBits(.asInstanceOf[Int]) match // uper:496 case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -527,7 +527,7 @@ while( \< ) { codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) - pBitStrm.appendBits(&

arr[/8], (int)) + codec.appendBits(&

arr[/8], (int)) val =(int) @@ -547,7 +547,7 @@ FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize = ; codec.encodeConstraintWholeNumber(, 0, 0xFF) -pBitStrm.appendBits(&

arr[/8], (int)); +codec.appendBits(&

arr[/8], (int)); for(=(int); \< (int)( + ); ++) @@ -565,12 +565,12 @@ FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingIt codec.encodeConstraintWholeNumber(, 0, 0xFF) -pBitStrm.appendBit(true) +codec.appendBit(true) codec.encodeConstraintWholeNumber(, 0, 0x7FFF) -pBitStrm.appendBits(&

arr[/8], (int)); +codec.appendBits(&

arr[/8], (int)); for(=(int); \< (int)( + ); ++) @@ -606,7 +606,7 @@ while ( >= 0x4000 && \< (a codec.encodeConstraintWholeNumber(0xC1, 0, 0xFF) - pBitStrm.appendBits(&

arr[/8], (int)); + codec.appendBits(&

arr[/8], (int)); =.asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -623,11 +623,11 @@ while ( >= 0x4000 && \< (a if \<= 0x7F then codec.encodeConstraintWholeNumber(, 0, 0xFF) else - pBitStrm.appendBit(true) + codec.appendBit(true) codec.encodeConstraintWholeNumber(, 0, 0x7FFF) -pBitStrm.appendBits(&

arr[/8], (int)); +codec.appendBits(&

arr[/8], (int)); = .asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -650,7 +650,7 @@ for( = 0; ret && \< ; ++) { ret = if (check) then Right(0) else Left() if ret == 0 then - ret = pBitStrm.readBits(&

arr[/8], ).asInstanceOf[Int] + ret = codec.readBits(&

arr[/8], ).asInstanceOf[Int] ret = if (ret == 0) 0 else ; @@ -676,7 +676,7 @@ val check = (ret == 0) && ( == ); ret = if (check) then Right(0) else Left() if ret.isRight then - ret = pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong + ret = codec.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong ret = if (ret == 0) then Right(0) else Left() @@ -703,7 +703,7 @@ ret = ret && ((0x8000 & ) > 0) && ( (0x7FFF & if ret == 0 then - ret = pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong + ret = codec.readBits(&

arr[/8], .asInstanceOf[Int]); // TODO call wrong ret = if (ret.isRight) then Right(0) else Left() @@ -755,7 +755,7 @@ while(( & 0xC0) == 0xC0) { return Left() - if !pBitStrm.readBits(&

arr[/8], ) then + if !codec.readBits(&

arr[/8], ) then return = @@ -793,7 +793,7 @@ if ( + \<= ) then return Left() -if(!pBitStrm.readBits(&

arr[/8], .asInstanceOf[Int])) // TODO remove adress of operator +if(!codec.readBits(&

arr[/8], .asInstanceOf[Int])) // TODO remove adress of operator return diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 258fb739e..0af6dbfa8 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -489,11 +489,30 @@ case class BitStream( SomeMut(arr) } + def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { + val cb: Int = currentBit + val arr: Array[UByte] = Array.fill(nCount + 1)(0) + + if cb == 0 then + if currentByte + nCount > buf.length then + return NoneMut() + + arrayCopyOffset(buf, arr, currentByte, currentByte + nCount, 0) + currentByte += nCount + + else + readByteArray(nCount) match + case NoneMut() => return NoneMut() + case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) + + SomeMut(arr) + } + def readBits(nbits: Int): OptionMut[Array[UByte]] = { val bytesToRead: Int = nbits / 8 val remainingBits: UByte = (nbits % 8).toByte - readByteArray(bytesToRead) match + decodeOctetString_no_length(bytesToRead) match case NoneMut() => return NoneMut() case SomeMut(arr) => if remainingBits > 0 then diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 782c593ac..c55c9175b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1001,4 +1001,74 @@ trait Codec { } return NoneMut() } + + + + + + def appendBitOne(): Unit = { + bitStream.appendBitOne() + } + + def appendBitZero(): Unit = { + bitStream.appendBitZero() + } + + def appendNBitZero(nBitsVal: Int): Unit = { + bitStream.appendNBitZero(nBitsVal) + } + + def appendNBitOne(nBitsVal: Int): Unit = { + bitStream.appendNBitOne(nBitsVal) + } + + def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { + bitStream.appendBits(srcBuffer, nBits) + } + + def appendBit(v: Boolean): Unit = { + bitStream.appendBit(v) + } + + def readBit(): Option[Boolean] = { + bitStream.readBit() + } + + def peekBit(): Boolean = { + bitStream.peekBit() + } + + def appendByte(value: Byte, negate: Boolean): Unit = { + bitStream.appendByte(value, negate) + } + + def appendByte0(v: UByte): Boolean = { + bitStream.appendByte0(v) + } + + def readByte(): Option[UByte] = { + bitStream.readByte() + } + + + def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { + bitStream.appendByteArray(arr, arr_len) + } + + + def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { + bitStream.readByteArray(arr_len) + } + + def readBits(nbits: Int): OptionMut[Array[UByte]] = { + bitStream.readBits(nbits) + } + + def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { + bitStream.appendPartialByte(vVal, nbits, negate) + } + + def readPartialByte(nbits: UByte): Option[UByte] = { + bitStream.readPartialByte(nbits) + } } From e075dd1aa1dfb32149930c35598ed7b965e346a2 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Tue, 31 Oct 2023 14:58:56 +0100 Subject: [PATCH 063/174] rename some functions --- StgScala/acn_scala.stg | 32 +++++----- StgScala/uper_scala.stg | 36 ++++++------ .../scala/asn1scala/asn1jvm_Bitstream.scala | 3 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 58 +++++++++---------- 4 files changed, 64 insertions(+), 65 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 8dd01187f..37d0faac4 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -522,7 +522,7 @@ codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -codec.BitStream_EncodeOctetString_no_length(

arr,

nCount.toInt) match +codec.encodeOctetString_no_length(

arr,

nCount.toInt) match case false => return Left() case true => ret = Right(0) >> @@ -530,20 +530,20 @@ codec.BitStream_EncodeOctetString_no_length(

arr,

nCount.toInt) oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then

nCount = .asInstanceOf[Int] - codec.BitStream_DecodeOctetString_no_length(

nCount.toInt) match + codec.decodeOctetString_no_length(

nCount.toInt) match case NoneMut() => return Left() case SomeMut(x) => x.copyToArray(

arr) >> oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -codec.BitStream_EncodeOctetString_no_length(

arr, ) match +codec.encodeOctetString_no_length(

arr, ) match case false => return Left() case true => ret = Right(0) >> oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then - codec.BitStream_DecodeOctetString_no_length() match + codec.decodeOctetString_no_length() match case NoneMut() => return Left() case SomeMut(x) =>

arr = x >> @@ -576,12 +576,12 @@ codec.appendBits((byte[]){}, ) oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << = 0 ret = Right(0) -while ret.isRight && \< && ((checkBitPatternPresentResult = codec.BitStream_checkBitPatternPresent((byte[]){}, )) == 1)) do +while ret.isRight && \< && ((checkBitPatternPresentResult = codec.checkBitPatternPresent((byte[]){}, )) == 1)) do += 1 if ret.isRight && ( == ) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = codec.BitStream_checkBitPatternPresent((byte[]){}, ) + checkBitPatternPresentResult = codec.checkBitPatternPresent((byte[]){}, ) if (ret && (checkBitPatternPresentResult == 0)) { ret = FALSE; /*COVERAGE_IGNORE*/ @@ -841,7 +841,7 @@ Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_C >> Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << -codec.BitStream_DecodeConstraintWholeNumber(0, ) match +codec.decodeConstraintWholeNumber(0, ) match case None() => return Left() case Some(x) => @@ -1019,7 +1019,7 @@ if ret.isRight then >> octet_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sExtField, sErrCode, soInner) ::= << -codec.BitStream_EncodeOctetString_no_length(arr, .asInstanceOf[Int]) match +codec.encodeOctetString_no_length(arr, .asInstanceOf[Int]) match case false => return Left() case true => @@ -1034,7 +1034,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then - codec.BitStream_DecodeOctetString_no_length(.asInstanceOf[Int]) match + codec.decodeOctetString_no_length(.asInstanceOf[Int]) match case NoneMut() => return Left() case SomeMut(arr) => @@ -1080,15 +1080,15 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, nBits if ret.isRight then int nCount = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1) - codec.BitStream_EncodeOctetString_no_length(bitStrm.buf, nCount) match + codec.encodeOctetString_no_length(bitStrm.buf, nCount) match case false => return Left(pErrCode) case true => ret = Right(0) - codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) - codec.BitStream_EncodeOctetString_no_length(bitStrm.buf, nCount) match + codec.encodeConstraintWholeNumber(nCount, , ) + codec.encodeOctetString_no_length(bitStrm.buf, nCount) match case false => return Left(pErrCode) case true => @@ -1105,7 +1105,7 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits val bitStrm: BitStream = BitStream_Init() - codec.BitStream_DecodeOctetString_no_length() match + codec.decodeOctetString_no_length() match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1113,14 +1113,14 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits var nCount: Int = 0 - codec.BitStream_DecodeConstraintWholeNumber(, ) match + codec.decodeConstraintWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => nCount = x if ret.isRight then - codec.BitStream_DecodeOctetString_no_length(nCount.asInstanceOf[Int]) + codec.decodeOctetString_no_length(nCount.asInstanceOf[Int]) case NoneMut() => return Left(pErrCode) case SomeMut(arr) => @@ -1170,7 +1170,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit var nCount: Int = 0 - codec.BitStream_DecodeConstraintWholeNumber(, ) match + codec.decodeConstraintWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index e6ee12dc1..c5d8b254a 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -106,7 +106,7 @@ codec.encodeConstraintWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -codec.BitStream_DecodeConstraintWholeNumberByte(0, 127) match // uper:109 +codec.decodeConstraintWholeNumberByte(0, 127) match // uper:109 case Some(c) =>

() = c case None() => @@ -143,9 +143,9 @@ codec.decodeConstraintPosWholeNumber(, ) match // uper:135 >> /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.BitStream_EncodeUnConstraintWholeNumber(

);" +IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnConstraintWholeNumber(

)" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -codec.BitStream_DecodeUnConstraintWholeNumber() match // uper:145 +codec.decodeUnConstraintWholeNumber() match // uper:145 case Some(x) =>

= x case None() => @@ -153,23 +153,23 @@ codec.BitStream_DecodeUnConstraintWholeNumber() match // uper:145 >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.BitStream_EncodeUnConstraintWholeNumber(

);" +IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnConstraintWholeNumber(

)" IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << -if !codec.BitStream_DecodeUnConstraintWholeNumber() then +if !codec.decodeUnConstraintWholeNumber() then ret = if then 0 else >> /*case: A:: = INTEGER (-5..MAX) */ -IntSemiConstraint_encode(p, nMin, sErrCode) ::= "codec.BitStream_EncodeSemiConstraintWholeNumber(

, );" +IntSemiConstraint_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstraintWholeNumber(

, )" IntSemiConstraint_decode(p, nMin, sErrCode) ::= << -if !codec.BitStream_DecodeSemiConstraintWholeNumber() then +if !codec.decodeSemiConstraintWholeNumber() then ret = >> /*case: A:: = INTEGER (5..MAX) */ -IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "codec.BitStream_EncodeSemiConstraintPosWholeNumber(

, );" +IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstraintPosWholeNumber(

, )" IntSemiConstraintPos_decode(p, nMin, sErrCode) ::= << -if !codec.BitStream_DecodeSemiConstraintPosWholeNumber() then +if !codec.decodeSemiConstraintPosWholeNumber() then ret = >> @@ -418,7 +418,7 @@ codec.encodeConstraintWholeNumber(nStringLength, , ) str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength = 0 -codec.BitStream_DecodeConstraintWholeNumberInt(, ) match // uper:418 +codec.decodeConstraintWholeNumberInt(, ) match // uper:418 case Some(n) => nStringLength = n

(nStringLength) = 0 // TODO do we need a 0 terminator? @@ -455,12 +455,12 @@ codec.decodeConstraintWholeNumber(, ) match // uper:444 >> octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << -if !codec.BitStream_EncodeOctetString_no_length(

arr, .asInstanceOf[Int]) then +if !codec.encodeOctetString_no_length(

arr, .asInstanceOf[Int]) then ret = Left(446) >> octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << -codec.BitStream_DecodeOctetString_no_length() match // uper:460 +codec.decodeOctetString_no_length() match // uper:460 case SomeMut(x) => x.copyToArray(

arr) case NoneMut() => @@ -469,7 +469,7 @@ codec.BitStream_DecodeOctetString_no_length() match // uper:460 octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << codec.encodeConstraintWholeNumber(

nCount, , ) -if !codec.BitStream_EncodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) then +if !codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) then ret = Left() >> @@ -483,7 +483,7 @@ codec.decodeConstraintWholeNumber(, ) match // uper:475 return Left() // decode payload -codec.BitStream_DecodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // uper:483 +codec.decodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // uper:483 case SomeMut(a) => a.copyToArray(

arr) case NoneMut() => @@ -838,7 +838,7 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, nBit ret = (

, &bitStrm, false) // TODO call wrong if (ret) then { int nCount = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1); - ret = BitStream_EncodeOctetString(pBitStrm, arr, nCount, , ); + ret = pBitStrm.encodeOctetString(arr, nCount, , ); } } >> @@ -851,7 +851,7 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, nBit BitStream bitStrm; BitStream_Init(&bitStrm, arr, sizeof(arr)); int nCount; - ret = BitStream_DecodeOctetString(pBitStrm, arr, &nCount, , ); + ret = pBitStrm.decodeOctetString(arr, &nCount, , ); if (ret) then{ ret = (

, &bitStrm); } @@ -869,7 +869,7 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBi ret = (

, &bitStrm, false) if (ret) then { int nCount = bitStrm.currentByte*8 + bitStrm.currentBit; - ret = BitStream_EncodeBitString(pBitStrm, arr, nCount, , ); + ret = pBitStrm.encodeBitString(arr, nCount, , ); } } >> @@ -882,7 +882,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBi BitStream bitStrm; BitStream_Init(&bitStrm, arr, sizeof(arr)); int nCount; - ret = BitStream_DecodeBitString(pBitStrm, arr, &nCount, , ); + ret = pBitStrm.decodeBitString(arr, &nCount, , ); if (ret) then { ret = (

, &bitStrm) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 0af6dbfa8..668699768 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -491,7 +491,7 @@ case class BitStream( def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { val cb: Int = currentBit - val arr: Array[UByte] = Array.fill(nCount + 1)(0) + val arr: Array[UByte] = Array.fill(nCount+1)(0) if cb == 0 then if currentByte + nCount > buf.length then @@ -507,7 +507,6 @@ case class BitStream( SomeMut(arr) } - def readBits(nbits: Int): OptionMut[Array[UByte]] = { val bytesToRead: Int = nbits / 8 val remainingBits: UByte = (nbits % 8).toByte diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index c55c9175b..9c77d9c35 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -244,42 +244,42 @@ trait Codec { case Some(ul) => return Some(ul + min) } - def BitStream_DecodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + def decodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { decodeConstraintWholeNumber(min.toLong, max.toLong) match case None() => None() case Some(l) => Some(l.toByte) } - def BitStream_DecodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { + def decodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { decodeConstraintWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toShort) } - def BitStream_DecodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { + def decodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { decodeConstraintWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toInt) } - def BitStream_DecodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { + def decodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toByte) } - def BitStream_DecodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { + def decodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toShort) } - def BitStream_DecodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { + def decodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() @@ -302,7 +302,7 @@ trait Codec { case Some(uv) => Some(uv + min) } - def BitStream_EncodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { + def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { assert(v >= min) val nBytes: Int = GetLengthInBytesOfUInt((v - min)) @@ -315,7 +315,7 @@ trait Codec { encodeNonNegativeInteger((v - min)) } - def BitStream_EncodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { + def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { assert(v >= min) val nBytes: Int = GetLengthInBytesOfUInt(v - min) @@ -328,7 +328,7 @@ trait Codec { encodeNonNegativeInteger(v - min) } - def BitStream_DecodeSemiConstraintWholeNumber(min: Long): Option[Long] = { + def decodeSemiConstraintWholeNumber(min: Long): Option[Long] = { var nBytes: Long = 0 var v: Long = 0 @@ -352,7 +352,7 @@ trait Codec { return Some(v) } - def BitStream_DecodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { + def decodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { var nBytes: Long = 0 var v: ULong = 0 @@ -373,7 +373,7 @@ trait Codec { return Some(v) } - def BitStream_EncodeUnConstraintWholeNumber(v: Long): Unit = { + def encodeUnConstraintWholeNumber(v: Long): Unit = { val nBytes: Int = GetLengthInBytesOfSInt(v) /* encode length */ @@ -389,7 +389,7 @@ trait Codec { } - def BitStream_DecodeUnConstraintWholeNumber(): Option[Long] = { + def decodeUnConstraintWholeNumber(): Option[Long] = { var nBytes: Long = 0 @@ -611,7 +611,7 @@ trait Codec { Some(v) } - def BitStream_checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { + def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal val tmp_currentByte: Int = bitStream.currentByte val tmp_currentBit: Int = bitStream.currentBit @@ -650,14 +650,14 @@ trait Codec { return 2 } - def BitStream_ReadBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { var checkBitPatternPresentResult: Int = 0 var bitsRead: Int = 0 val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do decreases(nMaxReadBits - bitsRead) bitStream.readBit() match @@ -667,10 +667,10 @@ trait Codec { bitsRead += 1 if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = BitStream_checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) if checkBitPatternPresentResult != 2 then return NoneMut() @@ -678,7 +678,7 @@ trait Codec { return SomeMut((tmpStrm.buf, bitsRead)) } - def BitStream_EncodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { + def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { val cb = bitStream.currentBit var ret: Boolean = false @@ -694,7 +694,7 @@ trait Codec { ret } - def BitStream_DecodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { + def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { val cb: Int = bitStream.currentBit val arr: Array[UByte] = Array.fill(nCount + 1)(0) @@ -713,7 +713,7 @@ trait Codec { SomeMut(arr) } - def BitStream_EncodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { + def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { var nRemainingItemsVar1: Int = nCount var nCurBlockSize1: Int = 0 var nCurOffset1: Int = 0 @@ -760,7 +760,7 @@ trait Codec { return ret } - def BitStream_DecodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { + def decodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) @@ -847,22 +847,22 @@ trait Codec { NoneMut() } - def BitStream_EncodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + def encodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax if ret then if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - ret = BitStream_EncodeOctetString_no_length(arr, nCount) + ret = encodeOctetString_no_length(arr, nCount) else - ret = BitStream_EncodeOctetString_fragmentation(arr, nCount) + ret = encodeOctetString_fragmentation(arr, nCount) return ret } - def BitStream_DecodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + def decodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { if asn1SizeMax < 65536 then var nCount: Int = 0 @@ -874,16 +874,16 @@ trait Codec { nCount = asn1SizeMin.toInt if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then - return BitStream_DecodeOctetString_no_length(nCount) + return decodeOctetString_no_length(nCount) else return NoneMut() else - return BitStream_DecodeOctetString_fragmentation(asn1SizeMax) + return decodeOctetString_fragmentation(asn1SizeMax) } - def BitStream_EncodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) @@ -929,7 +929,7 @@ trait Codec { true } - def BitStream_DecodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + def decodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { require(asn1SizeMax <= Int.MaxValue) if (asn1SizeMax < 65536) { From 5db22c45bceb18678d70af5dee5efe21ad8065a9 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 1 Nov 2023 16:54:39 +0100 Subject: [PATCH 064/174] clean the appendBit function --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 40 +++++++++++++------ .../main/scala/asn1scala/asn1jvm_Codec.scala | 13 ------ 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 668699768..e94f7674c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -8,7 +8,6 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* - // TODO should be part of BitStream def isPrefix(b1: BitStream, b2: BitStream): Boolean = { b1.buf.length <= b2.buf.length && @@ -101,6 +100,18 @@ private val BitAccessMasks: Array[UByte] = Array( 0x01, // 1 / 0000 0001 / x01 ) +val masksb: Array[UByte] = Array( + 0x00, // 0 / 0000 0000 / x00 + 0x01, // 1 / 0000 0001 / x01 + 0x03, // 3 / 0000 0011 / x03 + 0x07, // 7 / 0000 0111 / x07 + 0x0F, // 15 / 0000 1111 / x0F + 0x1F, // 31 / 0001 1111 / x1F + 0x3F, // 63 / 0011 1111 / x3F + 0x7F, // 127 / 0111 1111 / x7F + -0x1, // -1 / 1111 1111 / xFF +) + case class BitStream( var buf: Array[Byte], var currentByte: Int = 0, // marks the currentByte that gets accessed @@ -169,6 +180,21 @@ case class BitStream( (cpy, cpy.readBit()) } + /** + * Append the bit b into the stream + * + * @param b bit that gets set + */ + def appendBit(b: Boolean): Unit = { + require(BitStream.validate_offset_bits(this, 1)) + if b then + buf(currentByte) = (buf(currentByte) | BitAccessMasks(currentBit)).toByte + else + buf(currentByte) = (buf(currentByte) & (~BitAccessMasks(currentBit))).toByte + + increaseBitIndex() + }.ensuring(_ => BitStream.invariant(this)) + /** * Append bit one. * @@ -286,19 +312,7 @@ case class BitStream( this.appendPartialByte(lastByte, remainingBits, false) } - def appendBit(v: Boolean): Unit = { - require(BitStream.validate_offset_bits(this, 1)) - if v then - buf(currentByte) = (buf(currentByte) | BitAccessMasks(currentBit)).toByte - else - val negMask = ~BitAccessMasks(currentBit) - buf(currentByte) = (buf(currentByte) & negMask).toByte - - increaseBitIndex() - }.ensuring(_ => BitStream.invariant(this)) - // TODO check if needs Marios implementation - def readBit(): Option[Boolean] = { require(BitStream.validate_offset_bit(this)) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 9c77d9c35..9456ad1df 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -8,19 +8,6 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* -// TODO move to Bitstream if only used there -val masksb: Array[UByte] = Array( - 0x00, // 0 / 0000 0000 / x00 - 0x01, // 1 / 0000 0001 / x01 - 0x03, // 3 / 0000 0011 / x03 - 0x07, // 7 / 0000 0111 / x07 - 0x0F, // 15 / 0000 1111 / x0F - 0x1F, // 31 / 0001 1111 / x1F - 0x3F, // 63 / 0011 1111 / x3F - 0x7F, // 127 / 0111 1111 / x7F - -0x1, // -1 / 1111 1111 / xFF -) - val masks2: Array[UInt] = Array( 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 0x000000FF, // 255 / 0000 0000 0000 0000 0000 0000 1111 1111 / 0x0000 00FF From 0e8ea575cece526fec96c3120d15e21e59ee0a42 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 1 Nov 2023 22:23:31 +0100 Subject: [PATCH 065/174] extreme simplification of bitstream append functions --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 191 +++++++----------- 1 file changed, 72 insertions(+), 119 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index e94f7674c..3e9f96747 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -89,6 +89,7 @@ object BitStream { } } +// TODO - if currentBit is 0 then the MSB gets set - is this by design? Big Endian? private val BitAccessMasks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 0x40, // 64 / 0100 0000 / x40 @@ -184,9 +185,16 @@ case class BitStream( * Append the bit b into the stream * * @param b bit that gets set + * + * Example + * cur bit = 3 + * + * |x|x|x|b|?|?|?|?| + * 0 1 2 3 4 5 6 7 + * */ def appendBit(b: Boolean): Unit = { - require(BitStream.validate_offset_bits(this, 1)) + require(BitStream.validate_offset_bit(this)) if b then buf(currentByte) = (buf(currentByte) | BitAccessMasks(currentBit)).toByte else @@ -195,122 +203,76 @@ case class BitStream( increaseBitIndex() }.ensuring(_ => BitStream.invariant(this)) - /** - * Append bit one. - * - * Example - * cur bit = 3 - * x x x | - * |_|_|_|_|_|_|_|_| - * 0 1 2 3 4 5 6 7 - * - * xxxy???? - * or 00010000 - * ------------- - * xxx1???? - * */ - @opaque - @inlineOnce def appendBitOne(): Unit = { require(BitStream.validate_offset_bit(this)) - @ghost val oldpBitStrm = snapshot(this) - - val newB = (buf(currentByte) | BitAccessMasks(currentBit)).toByte - buf(currentByte) = newB - - ghostExpr { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte, newB) - } - increaseBitIndex() - - }.ensuring { _ => - val w1 = old(this) - val w2 = this - w2.bitIndex() == w1.bitIndex() + 1 - &&& isValidPair(w1, w2) - &&& { - val (r1, r2) = reader(w1, w2) - val (r2Got, bitGot) = readBitPure() - bitGot.get == true && r2Got == r2 - } - &&& BitStream.invariant(this) + appendBit(true) } - /** - * Append zero bit. - * - * Example - * cur bit = 3 - * x x x | - * |_|_|_|_|_|_|_|_| - * 0 1 2 3 4 5 6 7 - * - * x x x y ? ? ? ? - * and 1 1 1 0 1 1 1 1 - * ---------------- - * --> x x x 0 ? ? ? ? - * */ - - // TODO replace with addBit(false)? def appendBitZero(): Unit = { - require(BitStream.validate_offset_bits(this, 1)) - val negMask = ~BitAccessMasks(currentBit) - buf(currentByte) = (buf(currentByte) & negMask).toByte + require(BitStream.validate_offset_bit(this)) - increaseBitIndex() - }.ensuring(_ => BitStream.invariant(this)) + appendBit(false) + } + def appendNBitZero(nBits: Int): Unit = { + require(0 <= nBits) + require(BitStream.validate_offset_bits(this, nBits)) + decreases(nBits) - // TODO what are you? it does not append even though it has append in the name - // TODO replace with loop that calls appendBitZero - def appendNBitZero(nBitsVal: Int): Unit = { - require(0 <= nBitsVal) - require(BitStream.validate_offset_bits(this, nBitsVal)) + if nBits == 0 then + return; - val nBits = nBitsVal % 8 - val nBytes = nBitsVal / 8 + appendBitZero() + appendNBitZero(nBits - 1) - var new_currentBit: Int = currentBit + nBits - var new_currentByte: Int = currentByte + nBytes + }.ensuring(_ => BitStream.invariant(this)) - if new_currentBit > 7 then - new_currentBit = new_currentBit % 8 - new_currentByte += 1 + def appendNBitOne(nBits: Int): Unit = { + require(0 <= nBits) + require(BitStream.validate_offset_bits(this, nBits)) + decreases(nBits) - currentBit = new_currentBit - currentByte = new_currentByte + if nBits == 0 then + return; + appendBitOne() + appendNBitOne(nBits - 1) }.ensuring(_ => BitStream.invariant(this)) + /** + * Append bit with bitNr from b to bitstream + * + * bit 0 is the MSB, bit 7 is the LSB + * + * @param b byte that gets the bit extracted from + * @param bitNr 0 to 7 - number of the bit + */ - def appendNBitOne(nBitsVal: Int): Unit = { - require(0 <= nBitsVal) - require(BitStream.validate_offset_bits(this, nBitsVal)) - var nBits = nBitsVal + private def appendBitFromByte(b: Byte, bitNr: Int): Unit = { + require(bitNr >= 0 && bitNr < NO_OF_BITS_IN_BYTE) + require(BitStream.validate_offset_bit(this)) - (while nBits > 0 do - decreases(nBits) - appendBitOne() - nBits -= 1 - ).invariant(nBits >= 0 &&& BitStream.validate_offset_bits(this, nBits)) - () - } + val bitPosInByte = 1 << ((NO_OF_BITS_IN_BYTE - 1) - bitNr) + appendBit((b.unsignedToInt & bitPosInByte) > 0) + + }.ensuring(_ => BitStream.invariant(this)) def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { - require(0 <= nBits && nBits / 8 < srcBuffer.length) + require(nBits >= 0 && nBits / 8 < srcBuffer.length) require(BitStream.validate_offset_bits(this, nBits)) - var lastByte: UByte = 0 - val bytesToEncode: Int = nBits / 8 - val remainingBits: UByte = (nBits % 8).toByte + var i = 0 + (while(i < nBits) do + decreases(nBits - i) - appendByteArray(srcBuffer, bytesToEncode) + appendBitFromByte(srcBuffer(i / NO_OF_BITS_IN_BYTE), i % NO_OF_BITS_IN_BYTE) - if remainingBits > 0 then - lastByte = ((srcBuffer(bytesToEncode) & 0xFF) >>> (8 - remainingBits)).toByte - this.appendPartialByte(lastByte, remainingBits, false) - } + i += 1 + ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) + + () // TODO why do I need this for stainless? + }.ensuring(_ => BitStream.invariant(this)) // TODO check if needs Marios implementation def readBit(): Option[Boolean] = { @@ -419,26 +381,18 @@ case class BitStream( } &&& BitStream.invariant(this) } + // TODO remove Boolean as return value def appendByte0(v: UByte): Boolean = { require(BitStream.validate_offset_bytes(this, 1)) - val cb: UByte = currentBit.toByte - val ncb: UByte = (8 - cb).toByte - var mask = ~masksb(ncb) + var i = 0 + (while i < NO_OF_BITS_IN_BYTE do + decreases(NO_OF_BITS_IN_BYTE - i) - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v >>>> cb)).toByte - currentByte += 1 + appendBitFromByte(v, i) - if cb > 0 then - if currentByte >= buf.length then - return false - mask = ~mask - ghostExpr { - ensureInvariant() - } - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v <<<< ncb)).toByte + i += 1 + ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) true }.ensuring(_ => BitStream.invariant(this)) @@ -461,25 +415,24 @@ case class BitStream( None() } + def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { + require(0 <= noOfBytes && noOfBytes <= arr.length) + require(BitStream.validate_offset_bytes(this, noOfBytes)) - def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { - require(0 <= arr_len && arr_len <= arr.length) - require(BitStream.validate_offset_bytes(this, arr_len)) - - if !(currentByte.toLong + arr_len < buf.length || (currentBit == 0 && currentByte.toLong + arr_len <= buf.length)) then - return false + // TODO do we need this check? +// if !(currentByte.toLong + noOfBytes < buf.length || (currentBit == 0 && currentByte.toLong + noOfBytes <= buf.length)) then +// return false var i: Int = 0 - (while i < arr_len do - decreases(arr_len - i) - this.appendByte0(arr(i)) + (while i < noOfBytes do + decreases(noOfBytes - i) + appendByte0(arr(i)) i += 1 - ).invariant(0 <= i &&& i <= arr_len &&& BitStream.validate_offset_bytes(this, arr_len - i)) + ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) true }.ensuring(_ => BitStream.invariant(this)) - def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { require(0 < arr_len && arr_len <= buf.length) require(BitStream.validate_offset_bytes(this, arr_len)) From 23d1c1502c4376b66f30b03d6e81d163daa9a6ce Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 2 Nov 2023 18:32:04 +0100 Subject: [PATCH 066/174] remove appendByte0 - that does that same as appendByte --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 59 ++++++++++--------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 24 ++++---- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 56 +++++++++--------- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 4 +- 4 files changed, 72 insertions(+), 71 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 3e9f96747..7b9da7e5e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -89,7 +89,7 @@ object BitStream { } } -// TODO - if currentBit is 0 then the MSB gets set - is this by design? Big Endian? +// TODO - if currentBit is 0 then the MSB gets set - is this by design? Big Endian? This makes no sense private val BitAccessMasks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 0x40, // 64 / 0100 0000 / x40 @@ -209,6 +209,20 @@ case class BitStream( appendBit(true) } + def appendNBitOne(nBits: Int): Unit = { + require(nBits >= 0) + require(BitStream.validate_offset_bits(this, nBits)) + + var i = 0 + (while i < nBits do + decreases(nBits - i) + + appendBitOne() + + i += 1 + ).invariant(i >= 0 &&& i <= nBits) + }.ensuring(_ => BitStream.invariant(this)) + def appendBitZero(): Unit = { require(BitStream.validate_offset_bit(this)) @@ -218,26 +232,16 @@ case class BitStream( def appendNBitZero(nBits: Int): Unit = { require(0 <= nBits) require(BitStream.validate_offset_bits(this, nBits)) - decreases(nBits) - - if nBits == 0 then - return; - - appendBitZero() - appendNBitZero(nBits - 1) - }.ensuring(_ => BitStream.invariant(this)) + var i = 0 + (while i < nBits do + decreases(nBits - i) - def appendNBitOne(nBits: Int): Unit = { - require(0 <= nBits) - require(BitStream.validate_offset_bits(this, nBits)) - decreases(nBits) + appendBitZero() - if nBits == 0 then - return; + i += 1 + ).invariant(i >= 0 &&& i <= nBits) - appendBitOne() - appendNBitOne(nBits - 1) }.ensuring(_ => BitStream.invariant(this)) /** @@ -270,10 +274,13 @@ case class BitStream( i += 1 ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) - - () // TODO why do I need this for stainless? }.ensuring(_ => BitStream.invariant(this)) + def peekBit(): Boolean = { + require(BitStream.validate_offset_bit(this)) + ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 + } + // TODO check if needs Marios implementation def readBit(): Option[Boolean] = { require(BitStream.validate_offset_bit(this)) @@ -287,11 +294,6 @@ case class BitStream( None() }.ensuring(_ => BitStream.invariant(this)) - def peekBit(): Boolean = { - require(currentByte < buf.length) - ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 - } - /** * Append byte. * @@ -313,6 +315,7 @@ case class BitStream( * * */ + /* @opaque @inlineOnce def appendByte(value: Byte, negate: Boolean): Unit = { @@ -379,10 +382,9 @@ case class BitStream( val (r2Got, vGot) = readBytePure(r1) ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 } &&& BitStream.invariant(this) - } + }*/ - // TODO remove Boolean as return value - def appendByte0(v: UByte): Boolean = { + def appendByte(v: UByte): Unit = { require(BitStream.validate_offset_bytes(this, 1)) var i = 0 @@ -394,7 +396,6 @@ case class BitStream( i += 1 ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) - true }.ensuring(_ => BitStream.invariant(this)) def readByte(): Option[UByte] = { @@ -426,7 +427,7 @@ case class BitStream( var i: Int = 0 (while i < noOfBytes do decreases(noOfBytes - i) - appendByte0(arr(i)) + appendByte(arr(i)) i += 1 ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 9456ad1df..e32c8471b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -106,7 +106,12 @@ trait Codec { decreases(cc) val t1: UInt = v.toInt & masks2(cc >>> 3) cc -= 8 - bitStream.appendByte((t1 >>> cc).toByte, negate) + + var b = t1 >>> cc + if negate then + b = ~b + + bitStream.appendByte(b.toUnsignedByte) } def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { @@ -722,9 +727,9 @@ trait Codec { encodeConstraintWholeNumber(0xC1, 0, 0xFF) var i1: Int = nCurOffset1 - while i1 < nCurBlockSize1 + nCurOffset1 && ret do + while i1 < nCurBlockSize1 + nCurOffset1 do decreases(nCurBlockSize1 + nCurOffset1 - i1) - ret = bitStream.appendByte0(arr(i1)) + bitStream.appendByte(arr(i1)) i1 += 1 nCurOffset1 += nCurBlockSize1 @@ -739,9 +744,9 @@ trait Codec { var i1: Int = nCurOffset1 - while i1 < (nCurOffset1 + nRemainingItemsVar1) && ret do + while i1 < (nCurOffset1 + nRemainingItemsVar1) do decreases(nCurOffset1 + nRemainingItemsVar1 - i1) - ret = bitStream.appendByte0(arr(i1)) + bitStream.appendByte(arr(i1)) i1 += 1 return ret @@ -1025,19 +1030,14 @@ trait Codec { bitStream.peekBit() } - def appendByte(value: Byte, negate: Boolean): Unit = { - bitStream.appendByte(value, negate) - } - - def appendByte0(v: UByte): Boolean = { - bitStream.appendByte0(v) + def appendByte(value: Byte): Unit = { + bitStream.appendByte(value) } def readByte(): Option[UByte] = { bitStream.readByte() } - def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { bitStream.appendByteArray(arr, arr_len) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 57c4e6d1c..bd87eeedb 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -59,7 +59,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { - bitStream.appendByte0(intVal.toByte) + bitStream.appendByte(intVal.toByte) CHECK_BIT_STREAM(bitStream) } @@ -70,8 +70,8 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < size do - val ByteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) + val byteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte + bitStream.appendByte(byteToEncode) mask >>>= 8 i += 1 @@ -95,8 +95,8 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < size do - val ByteToEncode: Byte = tmp.toByte - bitStream.appendByte0(ByteToEncode) + val byteToEncode: Byte = tmp.toByte + bitStream.appendByte(byteToEncode) tmp >>>= 8 i += 1 @@ -197,8 +197,8 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < nBytes do - val ByteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - bitStream.appendByte0(ByteToEncode) + val byteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte + bitStream.appendByte(byteToEncode) vv <<= 8 i += 1 } @@ -208,7 +208,7 @@ case class ACN(bitStream: BitStream) extends Codec { val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte /* encode length */ - bitStream.appendByte0(nBytes) + bitStream.appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(intVal, nBytes) @@ -346,7 +346,7 @@ case class ACN(bitStream: BitStream) extends Codec { val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte /* encode length */ - bitStream.appendByte0(nBytes) + bitStream.appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(int2uint(intVal), nBytes) @@ -434,7 +434,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { val nNibbles: Int = get_Int_Size_BCD(intVal) /* encode length */ - bitStream.appendByte0(nNibbles.toByte) + bitStream.appendByte(nNibbles.toByte) /* Encode Number */ enc_Int_BCD_ConstSize(intVal, nNibbles) @@ -496,7 +496,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i = encodedSizeInBytes - 1 while i >= 0 do - bitStream.appendByte0((tmp(i) + '0').toByte) + bitStream.appendByte((tmp(i) + '0').toByte) i -= 1 CHECK_BIT_STREAM(bitStream) @@ -507,7 +507,7 @@ case class ACN(bitStream: BitStream) extends Codec { val absIntVal: ULong = if intVal >= 0 then intVal else -intVal /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then '+' else '-') enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) } @@ -579,15 +579,15 @@ case class ACN(bitStream: BitStream) extends Codec { val (digitsArray100, nChars) = getIntegerDigits(absIntVal) /* encode length, plus 1 for sign */ - bitStream.appendByte0((nChars + 1).toByte) + bitStream.appendByte((nChars + 1).toByte) /* encode sign */ - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then '+' else '-') /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) + bitStream.appendByte(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -597,11 +597,11 @@ case class ACN(bitStream: BitStream) extends Codec { val (digitsArray100, nChars) = getIntegerDigits(intVal) /* encode length */ - bitStream.appendByte0(nChars) + bitStream.appendByte(nChars) /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) + bitStream.appendByte(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -626,12 +626,12 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 // TODO: size_t? while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte0(digitsArray100(i)) + bitStream.appendByte(digitsArray100(i)) i += 1 i = 0 while i < null_characters_size do - bitStream.appendByte0(null_characters(i)) + bitStream.appendByte(null_characters(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -639,7 +639,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { val absValue: ULong = if intVal >= 0 then intVal else -intVal - bitStream.appendByte0(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then '+' else '-') enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) } @@ -749,7 +749,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < 4 do - bitStream.appendByte0(b(i)) + bitStream.appendByte(b(i)) i += 1 } @@ -785,7 +785,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < 8 do - bitStream.appendByte0(b(i)) + bitStream.appendByte(b(i)) i += 1 } @@ -808,7 +808,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 3 while i >= 0 do - bitStream.appendByte0(b(i)) + bitStream.appendByte(b(i)) i -= 1 } @@ -836,7 +836,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 7 while i >= 0 do - bitStream.appendByte0(b(i)) + bitStream.appendByte(b(i)) i -= 1 } @@ -858,14 +858,14 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { var i: Long = 0 while i < max do - bitStream.appendByte(strVal(i.toInt), false) + bitStream.appendByte(strVal(i.toInt)) i += 1 } def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { var i: Long = 0 while (i < max) && (strVal(i.toInt) != '\u0000') do - bitStream.appendByte(strVal(i.toInt), false) + bitStream.appendByte(strVal(i.toInt)) i += 1 i @@ -873,14 +873,14 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { enc_String_Ascii_private(max, strVal) - bitStream.appendByte(null_character.toByte, false) + bitStream.appendByte(null_character.toByte) } def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { enc_String_Ascii_private(max, strVal) var i: Int = 0 while i < null_character_size do - bitStream.appendByte(null_character(i), false) + bitStream.appendByte(null_character(i)) i += 1 } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index bafa7291e..63b203c42 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -62,7 +62,7 @@ case class UPER(bitStream: BitStream) extends Codec { i = 0 while i < totalSize do decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) + bitStream.appendByte(tmp(i)) i += 1 } @@ -89,7 +89,7 @@ case class UPER(bitStream: BitStream) extends Codec { i = 0 while i < totalSize do decreases(totalSize - i) - bitStream.appendByte0(tmp(i)) + bitStream.appendByte(tmp(i)) i += 1 } From 5c6a029d6f1d87d4352eaaee54a7b3f6f308f977 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 3 Nov 2023 11:03:56 +0100 Subject: [PATCH 067/174] removed old code // Bookmark: marios verficatiorn of the old code is here --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 75 +------------------ 1 file changed, 3 insertions(+), 72 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 7b9da7e5e..a6d9d22aa 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -258,7 +258,7 @@ case class BitStream( require(BitStream.validate_offset_bit(this)) val bitPosInByte = 1 << ((NO_OF_BITS_IN_BYTE - 1) - bitNr) - appendBit((b.unsignedToInt & bitPosInByte) > 0) + appendBit((b.unsignedToInt & bitPosInByte) != 0) }.ensuring(_ => BitStream.invariant(this)) @@ -281,7 +281,7 @@ case class BitStream( ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 } - // TODO check if needs Marios implementation + // TODO change return value? def readBit(): Option[Boolean] = { require(BitStream.validate_offset_bit(this)) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 @@ -295,7 +295,7 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) /** - * Append byte. + * Append byte (old implementation) * * Example * cur bit = 3 @@ -315,75 +315,6 @@ case class BitStream( * * */ - /* - @opaque - @inlineOnce - def appendByte(value: Byte, negate: Boolean): Unit = { - require(BitStream.validate_offset_bytes(this, 1)) - @ghost val oldpBitStrm = snapshot(this) - val cb = currentBit.toByte - val ncb = (8 - cb).toByte - var mask = (~masksb(ncb)).toByte - - var v = value - if negate then - v = (~v).toByte - - buf(currentByte) = (buf(currentByte) & mask).toByte // set bits right of currentbit to zero (where our value will be inserted) - buf(currentByte) = (buf(currentByte) | (v >>>> cb)).toByte // set value into bits right of currentbit, but keep bits to the left - currentByte += 1 - - ghostExpr { - check( - (oldpBitStrm.currentByte < oldpBitStrm.buf.length) ==> - bytePrefix( - oldpBitStrm.buf(oldpBitStrm.currentByte), - buf(oldpBitStrm.currentByte), - 0, oldpBitStrm.currentBit)) - } - @ghost val old2pBitStrm = snapshot(this) - - if cb > 0 then - mask = (~mask).toByte - buf(currentByte) = (buf(currentByte) & mask).toByte // set bits to the left of currentbit in next byte to zero (where the rest of our value will be inserted) - buf(currentByte) = (buf(currentByte) | (v <<<< ncb)).toByte // set value into the bits left of currentbit, but keep the bits to the right - - ghostExpr { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte - 1, buf(currentByte - 1)) - assert(arrayPrefix(oldpBitStrm.buf, old2pBitStrm.buf, 0, currentByte - 1)) - - if (cb > 0) { - arrayUpdatedAtPrefixLemma(oldpBitStrm.buf, currentByte, buf(currentByte)) - arrayUpdatedAtPrefixLemma(old2pBitStrm.buf, currentByte, buf(currentByte)) - arrayPrefixTransitive( - oldpBitStrm.buf, - old2pBitStrm.buf, - buf,0, currentByte - 1, currentByte - ) - check(arrayPrefix( - oldpBitStrm.buf, - buf, - 0, - oldpBitStrm.currentByte - )) - } else { - check(arrayPrefix( - oldpBitStrm.buf, - buf,0, - oldpBitStrm.currentByte - )) - } - } - }.ensuring { _ => - val w1 = old(this) - val w2 = this - w2.bitIndex() == w1.bitIndex() + 8 &&& isValidPair(w1, w2) &&& { - val (r1, r2) = reader(w1, w2) - val (r2Got, vGot) = readBytePure(r1) - ((!negate && vGot.get == value) || (negate && vGot.get == ~value)) && r2Got == r2 - } &&& BitStream.invariant(this) - }*/ - def appendByte(v: UByte): Unit = { require(BitStream.validate_offset_bytes(this, 1)) From 145bd7a382fc37aa85dad537f23c00e924ca484f Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 3 Nov 2023 12:50:44 +0100 Subject: [PATCH 068/174] readByte added --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 114 ++++++++++-------- .../main/scala/asn1scala/asn1jvm_Helper.scala | 5 +- 2 files changed, 68 insertions(+), 51 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index a6d9d22aa..2e0dc4eab 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -276,24 +276,6 @@ case class BitStream( ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) }.ensuring(_ => BitStream.invariant(this)) - def peekBit(): Boolean = { - require(BitStream.validate_offset_bit(this)) - ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 - } - - // TODO change return value? - def readBit(): Option[Boolean] = { - require(BitStream.validate_offset_bit(this)) - val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 - - increaseBitIndex() - - if currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8 then - Some(ret) - else - None() - }.ensuring(_ => BitStream.invariant(this)) - /** * Append byte (old implementation) * @@ -305,13 +287,13 @@ case class BitStream( * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 * * first byte - * xxx????? + * xxx????? * and 11100000 (mask) * -------------- - * xxx00000 + * xxx00000 * or 000bbbbb * -------------- - * xxxbbbbb + * xxxbbbbb * * */ @@ -325,26 +307,76 @@ case class BitStream( appendBitFromByte(v, i) i += 1 - ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) + ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) }.ensuring(_ => BitStream.invariant(this)) - def readByte(): Option[UByte] = { - require(BitStream.validate_offset_bytes(this, 1)) - - val cb: UByte = currentBit.toByte - val ncb: UByte = (8 - cb).toByte + def peekBit(): Boolean = { + require(BitStream.validate_offset_bit(this)) + ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 + } - var v: UByte = buf(currentByte) <<<< cb - currentByte += 1 + // TODO change return value? + def readBit(): Option[Boolean] = { + require(BitStream.validate_offset_bit(this)) + val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 - if cb > 0 then - v = (v | (buf(currentByte) >>>> ncb)).toByte + increaseBitIndex() - if BitStream.invariant(this) then - Some(v) + if currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8 then + Some(ret) else None() + }.ensuring(_ => BitStream.invariant(this)) + + def readBits(nbits: Int): OptionMut[Array[UByte]] = { + val bytesToRead: Int = nbits / 8 + val remainingBits: UByte = (nbits % 8).toByte + + decodeOctetString_no_length(bytesToRead) match + case NoneMut() => return NoneMut() + case SomeMut(arr) => + if remainingBits > 0 then + this.readPartialByte(remainingBits) match + case None() => return NoneMut() + case Some(ub) => arr(bytesToRead) = ub + arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte + SomeMut(arr) + else + SomeMut(arr) + } + + def readByte(): Option[UByte] = { + require(BitStream.validate_offset_bits(this, 8)) + + var ret = 0 + var i = 0 + (while i < NO_OF_BITS_IN_BYTE do + decreases(NO_OF_BITS_IN_BYTE - i) + + readBit() match + case None() => + return None() + case Some(b) => + ret = ret | (if b then BitAccessMasks(i) else 0) + i += 1 + ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) + + Some(ret.toUnsignedByte) + +// val cb: UByte = currentBit.toByte +// val ncb: UByte = (8 - cb).toByte +// +// var v: UByte = buf(currentByte) <<<< cb +// currentByte += 1 +// +// if cb > 0 then +// v = (v | (buf(currentByte) >>>> ncb)).toByte +// +// if BitStream.invariant(this) then +// Some(v) +// else +// None() } def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { @@ -406,22 +438,6 @@ case class BitStream( SomeMut(arr) } - def readBits(nbits: Int): OptionMut[Array[UByte]] = { - val bytesToRead: Int = nbits / 8 - val remainingBits: UByte = (nbits % 8).toByte - - decodeOctetString_no_length(bytesToRead) match - case NoneMut() => return NoneMut() - case SomeMut(arr) => - if remainingBits > 0 then - this.readPartialByte(remainingBits) match - case None() => return NoneMut() - case Some(ub) => arr(bytesToRead) = ub - arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte - SomeMut(arr) - else - SomeMut(arr) - } /* nbits 1..7*/ def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index aee7187ad..2ddcd53d0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -40,9 +40,10 @@ extension (ui: UInt) { extension (i: Int) { def toUnsignedByte: UByte = { - require(i >= 0 && i <= MASK_BYTE) - if(i == MASK_MSB_BYTE) + var iVal = i & MASK_BYTE + + if(iVal == MASK_MSB_BYTE) (-MASK_MSB_BYTE).toByte else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte From e228c8aa2bfd1f73169c032a9a239edb59943a60 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 3 Nov 2023 19:48:34 +0100 Subject: [PATCH 069/174] simplified useless array copy --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 253 ++++++++---------- .../main/scala/asn1scala/asn1jvm_Helper.scala | 37 +-- 2 files changed, 129 insertions(+), 161 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 2e0dc4eab..4d790f08e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -65,7 +65,7 @@ object BitStream { @ghost def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { - require(0 <= bits) + require(bits >= 0) val nBits = bits % 8 val nBytes = bits / 8 @@ -89,7 +89,6 @@ object BitStream { } } -// TODO - if currentBit is 0 then the MSB gets set - is this by design? Big Endian? This makes no sense private val BitAccessMasks: Array[UByte] = Array( -0x80, // -128 / 1000 0000 / x80 0x40, // 64 / 0100 0000 / x40 @@ -138,8 +137,9 @@ case class BitStream( BitStream.invariant(this) } + // TODO not used @inlineOnce @opaque @ghost - def ensureInvariant(): Unit = { + private def ensureInvariant(): Unit = { }.ensuring(_ => BitStream.invariant(currentByte, currentBit, buf.length) ) @@ -181,6 +181,8 @@ case class BitStream( (cpy, cpy.readBit()) } + // ****************** Append Bit Functions ********************** + /** * Append the bit b into the stream * @@ -230,7 +232,7 @@ case class BitStream( } def appendNBitZero(nBits: Int): Unit = { - require(0 <= nBits) + require(nBits >= 0) require(BitStream.validate_offset_bits(this, nBits)) var i = 0 @@ -276,6 +278,52 @@ case class BitStream( ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) }.ensuring(_ => BitStream.invariant(this)) + // ****************** Append Byte Functions ********************** + + def appendPartialByte(vVal: UByte, nBits: Int, negate: Boolean): Unit = { + require(nBits >= 0) + require(BitStream.validate_offset_bits(this, nBits)) + + val totalBits = currentBit + nBits + val ncb = 8 - currentBit + + var v = vVal + if negate then + v = (masksb(nBits) & (~v)).toByte + + val mask1: UByte = (~masksb(ncb)).toByte + + if (totalBits <= 8) { + //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; + val mask2: UByte = masksb(8 - totalBits) + val mask: UByte = (mask1 | mask2).toByte + //e.g. current bit = 3 --> mask = 1110 0000 + //nbits = 3 --> totalBits = 6 + // mask= 1110 0000 + // and 0000 0011 <- masks[totalBits - 1] + // ----------- + // final mask 1110 0011 + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v << (8 - totalBits))).toByte + currentBit += nBits + if currentBit == 8 then + currentBit = 0 + currentByte += 1 + + } else { + val totalBitsForNextByte: UByte = (totalBits - 8).toByte + buf(currentByte) = (buf(currentByte) & mask1).toByte + buf(currentByte) = (buf(currentByte) | (v >>> totalBitsForNextByte)).toByte + currentByte += 1 + val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte + buf(currentByte) = (buf(currentByte) & mask).toByte + buf(currentByte) = (buf(currentByte) | (v << (8 - totalBitsForNextByte))).toByte + currentBit = totalBitsForNextByte.toInt + } + +// assert(currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8) + }.ensuring(_ => BitStream.invariant(this)) + /** * Append byte (old implementation) * @@ -311,11 +359,29 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) + def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { + require(0 <= noOfBytes && noOfBytes <= arr.length) + require(BitStream.validate_offset_bytes(this, noOfBytes)) + + var i: Int = 0 + (while i < noOfBytes do + decreases(noOfBytes - i) + appendByte(arr(i)) + i += 1 + ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) + + true + }.ensuring(_ => BitStream.invariant(this)) + + // ****************** Peak Functions ********************** + def peekBit(): Boolean = { require(BitStream.validate_offset_bit(this)) ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 } + // ****************** Read Bit Functions ********************** + // TODO change return value? def readBit(): Option[Boolean] = { require(BitStream.validate_offset_bit(this)) @@ -329,22 +395,29 @@ case class BitStream( None() }.ensuring(_ => BitStream.invariant(this)) - def readBits(nbits: Int): OptionMut[Array[UByte]] = { - val bytesToRead: Int = nbits / 8 - val remainingBits: UByte = (nbits % 8).toByte - - decodeOctetString_no_length(bytesToRead) match - case NoneMut() => return NoneMut() - case SomeMut(arr) => - if remainingBits > 0 then - this.readPartialByte(remainingBits) match - case None() => return NoneMut() - case Some(ub) => arr(bytesToRead) = ub - arr(bytesToRead) = (arr(bytesToRead) << (8 - remainingBits)).toByte - SomeMut(arr) - else - SomeMut(arr) - } + def readBits(nBits: Int): OptionMut[Array[UByte]] = { + require(nBits > 0 && (nBits <= Integer.MAX_VALUE - NO_OF_BITS_IN_BYTE)) // TODO remaining bits in stream as upper bound, not MAX_VAL + require(BitStream.validate_offset_bits(this, nBits)) + + val arr: Array[UByte] = Array.fill((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE)(0) + + var i = 0 + (while i < nBits do + decreases(nBits - i) + + readBit() match + case None() => + return NoneMut() + case Some(b) => + arr(i / NO_OF_BITS_IN_BYTE) |||= (if b then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) + + i += 1 + ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) + + SomeMut(arr) + }.ensuring(_ => BitStream.invariant(this)) + + // ****************** Read Byte Functions ********************** def readByte(): Option[UByte] = { require(BitStream.validate_offset_bits(this, 8)) @@ -363,151 +436,41 @@ case class BitStream( ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) Some(ret.toUnsignedByte) - -// val cb: UByte = currentBit.toByte -// val ncb: UByte = (8 - cb).toByte -// -// var v: UByte = buf(currentByte) <<<< cb -// currentByte += 1 -// -// if cb > 0 then -// v = (v | (buf(currentByte) >>>> ncb)).toByte -// -// if BitStream.invariant(this) then -// Some(v) -// else -// None() - } - - def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { - require(0 <= noOfBytes && noOfBytes <= arr.length) - require(BitStream.validate_offset_bytes(this, noOfBytes)) - - // TODO do we need this check? -// if !(currentByte.toLong + noOfBytes < buf.length || (currentBit == 0 && currentByte.toLong + noOfBytes <= buf.length)) then -// return false - - var i: Int = 0 - (while i < noOfBytes do - decreases(noOfBytes - i) - appendByte(arr(i)) - i += 1 - ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) - - true }.ensuring(_ => BitStream.invariant(this)) - def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { - require(0 < arr_len && arr_len <= buf.length) - require(BitStream.validate_offset_bytes(this, arr_len)) - val arr: Array[UByte] = Array.fill(arr_len)(0) - - val cb = currentBit - val ncb = 8 - cb - - if !(currentByte.toLong + arr_len < buf.length || (currentBit == 0 && currentByte.toLong + arr_len <= buf.length)) then - return NoneMut() - - var i: Int = 0 - (while i < arr_len do - decreases(arr_len - i) - this.readByte() match - case Some(v) => arr(i) = v - case None() => return NoneMut() - i += 1 - ).invariant(0 <= i &&& i <= arr_len &&& i <= arr.length &&& BitStream.validate_offset_bytes(this, arr_len - i) &&& BitStream.invariant(this)) - - SomeMut(arr) - } - - def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { - val cb: Int = currentBit - val arr: Array[UByte] = Array.fill(nCount+1)(0) - - if cb == 0 then - if currentByte + nCount > buf.length then - return NoneMut() - - arrayCopyOffset(buf, arr, currentByte, currentByte + nCount, 0) - currentByte += nCount - - else - readByteArray(nCount) match - case NoneMut() => return NoneMut() - case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) - - SomeMut(arr) - } - - /* nbits 1..7*/ - def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { - val cb: UByte = currentBit.toByte - val totalBits: UByte = (cb + nbits).toByte - val ncb: UByte = (8 - cb).toByte + def readByteArray(nBytes: Int): OptionMut[Array[UByte]] = { + require(0 < nBytes && nBytes <= buf.length) + require(BitStream.validate_offset_bytes(this, nBytes)) - var v = vVal - if negate then - v = (masksb(nbits) & (~v)).toByte - - val mask1: UByte = (~masksb(ncb)).toByte - - if (totalBits <= 8) { - //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; - val mask2: UByte = masksb(8 - totalBits) - val mask: UByte = (mask1 | mask2).toByte - //e.g. current bit = 3 --> mask = 1110 0000 - //nbits = 3 --> totalBits = 6 - // mask= 1110 0000 - // and 0000 0011 <- masks[totalBits - 1] - // ----------- - // final mask 1110 0011 - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v << (8 - totalBits))).toByte - currentBit += nbits.toInt - if currentBit == 8 then - currentBit = 0 - currentByte += 1 - - } else { - val totalBitsForNextByte: UByte = (totalBits - 8).toByte - buf(currentByte) = (buf(currentByte) & mask1).toByte - buf(currentByte) = (buf(currentByte) | (v >>> totalBitsForNextByte)).toByte - currentByte += 1 - val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v << (8 - totalBitsForNextByte))).toByte - currentBit = totalBitsForNextByte.toInt - } + readBits(nBytes * NO_OF_BITS_IN_BYTE) + }.ensuring(_ => BitStream.invariant(this)) - assert(currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8) - } /* nbits 1..7*/ - def readPartialByte(nbits: UByte): Option[UByte] = { - require(0 < nbits && nbits < 8) - require(BitStream.validate_offset_bits(this, nbits)) + def readPartialByte(nBits: Int): Option[UByte] = { + require(0 < nBits && nBits < 8) + require(BitStream.validate_offset_bits(this, nBits)) var v: UByte = 0 - val cb: UByte = currentBit.toByte - val totalBits: UByte = (cb + nbits).toByte + val totalBits = currentBit + nBits if (totalBits <= 8) { - v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nbits)).toByte + v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nBits)).toByte ghostExpr { - BitStream.validate_offset_bits(this, nbits) + BitStream.validate_offset_bits(this, nBits) } - if currentBit + nbits >= 8 then - currentBit = (currentBit + nbits) % 8 + if currentBit + nBits >= 8 then + currentBit = (currentBit + nBits) % 8 currentByte += 1 else - currentBit += nbits.toInt + currentBit += nBits } else { var totalBitsForNextByte: UByte = (totalBits - 8).toByte v = (buf(currentByte) <<<< totalBitsForNextByte) currentByte += 1 v = (v | buf(currentByte) >>>> (8 - totalBitsForNextByte)).toByte - v = (v & masksb(nbits)).toByte + v = (v & masksb(nBits)).toByte currentBit = totalBitsForNextByte.toInt } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index 2ddcd53d0..63f4da62a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -7,6 +7,7 @@ import stainless.annotation.* import stainless.proof.* import stainless.math.* import StaticChecks.* +import scala.annotation.targetName // all bits of the integer val MASK_BYTE = 0xFF @@ -25,9 +26,26 @@ val MASK_POS_INT = 0x7F_FF_FF_FFL /* * Meths to upcast unsigned integer data types on the JVM */ -extension (ub: UByte) { - def unsignedToLong: Long = ub & MASK_BYTE_L - def unsignedToInt: Int = ub.toInt & MASK_BYTE +extension (ubL: UByte) { + def unsignedToLong: Long = ubL & MASK_BYTE_L + def unsignedToInt: Int = ubL.toInt & MASK_BYTE + + @targetName("unsigned right shift on Bytes") + def >>>>(i: Int): UByte = { + require(i >= 0 && i <= NO_OF_BITS_IN_BYTE) + ((ubL.toInt & MASK_BYTE) >>> i).toUnsignedByte + } + + @targetName("left shift on Bytes") + def <<<<(i: Int): UByte = { + require(i >= 0 && i <= NO_OF_BITS_IN_BYTE) + ((ubL.toInt << i) & MASK_BYTE).toUnsignedByte + } + + @targetName("binary OR on Bytes") + def |||(ubR: Byte): UByte = { + (ubL.toInt | ubR.toInt).toUnsignedByte + } } extension (us: UShort) { @@ -65,19 +83,6 @@ extension (l: Long) { } } -extension (b: Byte) { - def >>>>(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt & MASK_BYTE) >>> i).toUnsignedByte - } - - def <<<<(i: Int): Byte = { - require(i >= 0 && i <= 8) - ((b.toInt << i) & MASK_BYTE).toUnsignedByte - } -} - - def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { if v >>> 8 == 0 then (v, 0) From cb918273ff287b11430bfe79b209210f46787868 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 3 Nov 2023 22:12:51 +0100 Subject: [PATCH 070/174] comment on how appendPartialByte works --- .../main/scala/asn1scala/asn1jvm_Bitstream.scala | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 4d790f08e..7b2a704ed 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -280,6 +280,22 @@ case class BitStream( // ****************** Append Byte Functions ********************** + /** + * Append part of a byte to the bitstream + * + * @param v value that should be partially added + * @param nBits that should get taken from v - counting starts with the LSB + * @param negate + * + * Example: + * + * nBits = 3 + * MSB = 2^7 LSB = 2^0 + * v = 1 0 0 1 0 1 1 0 + * x1 x2 x3 + * x1 to x3 get added to the bitstream - starting with x1 + * + */ def appendPartialByte(vVal: UByte, nBits: Int, negate: Boolean): Unit = { require(nBits >= 0) require(BitStream.validate_offset_bits(this, nBits)) From 43c99b9d533e92e0b956d3076c00d81ad0852f6d Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Sat, 4 Nov 2023 16:15:17 +0100 Subject: [PATCH 071/174] simple appentPartialByte added --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 51 ++++--------------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 5 +- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 4 +- 3 files changed, 16 insertions(+), 44 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 7b2a704ed..a9257dbb3 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -249,7 +249,8 @@ case class BitStream( /** * Append bit with bitNr from b to bitstream * - * bit 0 is the MSB, bit 7 is the LSB + * bit 0 is the MSB, bit 7 is the LSB, ASN.1 standard declares bit 1 as MSB, + * bit 8 as LSB - but we start from 0 in CS * * @param b byte that gets the bit extracted from * @param bitNr 0 to 7 - number of the bit @@ -285,7 +286,6 @@ case class BitStream( * * @param v value that should be partially added * @param nBits that should get taken from v - counting starts with the LSB - * @param negate * * Example: * @@ -296,48 +296,19 @@ case class BitStream( * x1 to x3 get added to the bitstream - starting with x1 * */ - def appendPartialByte(vVal: UByte, nBits: Int, negate: Boolean): Unit = { - require(nBits >= 0) - require(BitStream.validate_offset_bits(this, nBits)) - - val totalBits = currentBit + nBits - val ncb = 8 - currentBit - var v = vVal - if negate then - v = (masksb(nBits) & (~v)).toByte - - val mask1: UByte = (~masksb(ncb)).toByte + def appendPartialByte(v: UByte, nBits: Int): Unit = { + require(nBits >= 0 &&& nBits <= NO_OF_BITS_IN_BYTE) + require(BitStream.validate_offset_bits(this, nBits)) - if (totalBits <= 8) { - //static UByte masksb[] = { 0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; - val mask2: UByte = masksb(8 - totalBits) - val mask: UByte = (mask1 | mask2).toByte - //e.g. current bit = 3 --> mask = 1110 0000 - //nbits = 3 --> totalBits = 6 - // mask= 1110 0000 - // and 0000 0011 <- masks[totalBits - 1] - // ----------- - // final mask 1110 0011 - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v << (8 - totalBits))).toByte - currentBit += nBits - if currentBit == 8 then - currentBit = 0 - currentByte += 1 + var i = 0 + (while i < nBits do + decreases(nBits - i) - } else { - val totalBitsForNextByte: UByte = (totalBits - 8).toByte - buf(currentByte) = (buf(currentByte) & mask1).toByte - buf(currentByte) = (buf(currentByte) | (v >>> totalBitsForNextByte)).toByte - currentByte += 1 - val mask: UByte = (~masksb(8 - totalBitsForNextByte)).toByte - buf(currentByte) = (buf(currentByte) & mask).toByte - buf(currentByte) = (buf(currentByte) | (v << (8 - totalBitsForNextByte))).toByte - currentBit = totalBitsForNextByte.toInt - } + appendBitFromByte(v, NO_OF_BITS_IN_BYTE - nBits + i) -// assert(currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8) + i += 1 + ).invariant(i >= 0 && i <= nBits) }.ensuring(_ => BitStream.invariant(this)) /** diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index e32c8471b..47a89d228 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -100,7 +100,8 @@ trait Codec { pbits = cc % 8 if pbits > 0 then cc -= pbits - bitStream.appendPartialByte((v >>> cc).toByte, pbits.toByte, negate) + var b = (v >>> cc).toByte + bitStream.appendPartialByte(if negate then (~b).toByte else b, pbits.toByte) while cc > 0 do decreases(cc) @@ -1052,7 +1053,7 @@ trait Codec { } def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { - bitStream.appendPartialByte(vVal, nbits, negate) + bitStream.appendPartialByte(vVal, nbits) } def readPartialByte(nbits: UByte): Option[UByte] = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index bd87eeedb..e1529e473 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -408,7 +408,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = encodedSizeInNibbles - 1 while i >= 0 do - bitStream.appendPartialByte(tmp(i).toByte, 4, false) + bitStream.appendPartialByte(tmp(i).toByte, 4) i -= 1 CHECK_BIT_STREAM(bitStream) @@ -458,7 +458,7 @@ case class ACN(bitStream: BitStream) extends Codec { /* Encode Number */ enc_Int_BCD_ConstSize(intVal, nNibbles) - bitStream.appendPartialByte(0xF, 4, false) + bitStream.appendPartialByte(0xF, 4) CHECK_BIT_STREAM(bitStream) } From ec1b2f6362ff5fb5cd9ba874d2d8a11b02735c9e Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 6 Nov 2023 15:01:52 +0100 Subject: [PATCH 072/174] - replace Char with Byte representation - OptionMut for ACN --- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 95 ++++++++++--------- 1 file changed, 51 insertions(+), 44 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index e1529e473..4b04c678c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -5,6 +5,13 @@ import stainless.lang.{None, Option, Some} val FAILED_READ_ERR_CODE = 5400 +val CHAR_MINUS: ASCIIChar = 45 +val CHAR_PLUS: ASCIIChar = 43 +val CHAR_ZERO: ASCIIChar = 48 +val CHAR_NINE: ASCIIChar = 57 +val CHAR_0000: ASCIIChar = 0 + + // TODO remove / replace by invariant def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) @@ -496,7 +503,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i = encodedSizeInBytes - 1 while i >= 0 do - bitStream.appendByte((tmp(i) + '0').toByte) + bitStream.appendByte((tmp(i) + CHAR_ZERO).toByte) i -= 1 CHECK_BIT_STREAM(bitStream) @@ -507,7 +514,7 @@ case class ACN(bitStream: BitStream) extends Codec { val absIntVal: ULong = if intVal >= 0 then intVal else -intVal /* encode sign */ - bitStream.appendByte(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) } @@ -520,10 +527,10 @@ case class ACN(bitStream: BitStream) extends Codec { bitStream.readByte() match case None() => return None() case Some(digit) => - assert(digit >= '0' && digit <= '9') + assert(digit >= CHAR_ZERO && digit <= CHAR_NINE) ret *= 10 - ret += (digit.toInt - '0').toByte + ret += (digit.toInt - CHAR_ZERO).toByte encodedSizeInBytesVar -= 1 @@ -535,9 +542,9 @@ case class ACN(bitStream: BitStream) extends Codec { case None() => None() case Some(digit) => var sign: Int = 1 - if digit == '+' then + if digit == CHAR_PLUS then sign = 1 - else if digit == '-' then + else if digit == CHAR_MINUS then sign = -1 else assert(false) @@ -557,7 +564,7 @@ case class ACN(bitStream: BitStream) extends Codec { if intVar > 0 then while intVar > 0 && totalDigits < 100 do - reversedDigitsArray(totalDigits) = ('0' + (intVar % 10)).toByte + reversedDigitsArray(totalDigits) = (CHAR_ZERO + (intVar % 10)).toByte totalDigits = (totalDigits + 1).toByte intVar /= 10 @@ -567,7 +574,7 @@ case class ACN(bitStream: BitStream) extends Codec { i -= 1 else - digitsArray100(0) = '0' + digitsArray100(0) = CHAR_ZERO totalDigits = 1 (digitsArray100, totalDigits) @@ -582,7 +589,7 @@ case class ACN(bitStream: BitStream) extends Codec { bitStream.appendByte((nChars + 1).toByte) /* encode sign */ - bitStream.appendByte(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) /* encode digits */ var i: Int = 0 @@ -639,7 +646,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { val absValue: ULong = if intVal >= 0 then intVal else -intVal - bitStream.appendByte(if intVal >= 0 then '+' else '-') + bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) } @@ -660,7 +667,7 @@ case class ACN(bitStream: BitStream) extends Codec { j += 1 var i: Long = 0 - while !null_characters.sameElements(tmp) do + while !arraySameElements(null_characters, tmp) do digit = tmp(0) i += 1 @@ -673,7 +680,7 @@ case class ACN(bitStream: BitStream) extends Codec { case None() => return None() case Some(ub) => tmp(null_characters_size - 1) = ub - digit = (digit - '0').toByte + digit = (digit - CHAR_ZERO).toByte ret *= 10 ret += digit @@ -688,8 +695,8 @@ case class ACN(bitStream: BitStream) extends Codec { bitStream.readByte() match case None() => None() case Some(digit) => - assert(digit == '-' || digit == '+') - if digit == '-' then + assert(digit == CHAR_MINUS || digit == CHAR_PLUS) + if digit == CHAR_MINUS then isNegative = true dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match @@ -864,7 +871,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { var i: Long = 0 - while (i < max) && (strVal(i.toInt) != '\u0000') do + while (i < max) && (strVal(i.toInt) != CHAR_0000) do bitStream.appendByte(strVal(i.toInt)) i += 1 @@ -905,7 +912,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_CharIndex_private(max: Long, allowedCharSet: Array[Byte], strVal: Array[ASCIIChar]): Long = { var i: Int = 0 - while (i < max) && (strVal(i) != '\u0000') do + while (i < max) && (strVal(i) != CHAR_0000) do val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) encodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) i += 1 @@ -967,42 +974,42 @@ case class ACN(bitStream: BitStream) extends Codec { } - def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_private(max: Long, charactersToDecode: Long): OptionMut[Array[ASCIIChar]] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i < charactersToDecode do bitStream.readByte() match - case None() => return None() + case None() => return NoneMut() case Some(decodedCharacter) => strVal(i) = decodedCharacter i += 1 - Some(strVal) + SomeMut(strVal) } - def dec_String_Ascii_FixSize(max: Long): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_FixSize(max: Long): OptionMut[Array[ASCIIChar]] = { dec_String_Ascii_private(max, max) } - def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): OptionMut[Array[ASCIIChar]] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i <= max do bitStream.readByte() match - case None() => return None() + case None() => return NoneMut() case Some(decodedCharacter) => if decodedCharacter != null_character then strVal(i) = decodedCharacter i += 1 else strVal(i) = 0x0 - return Some(strVal) + return SomeMut(strVal) - None() + NoneMut() } - def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): OptionMut[Array[ASCIIChar]] = { val sz: Int = if null_character_size < 10 then null_character_size else 10 val tmp: Array[Byte] = Array.fill(10)(0) val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) @@ -1010,13 +1017,13 @@ case class ACN(bitStream: BitStream) extends Codec { var j: Int = 0 while j < null_character_size do bitStream.readByte() match - case None() => return None() + case None() => return NoneMut() case Some(ub) => tmp(j) = ub j += 1 var i: Int = 0 - while i <= max && !null_character.sameElements(tmp) do + while i <= max && !arraySameElements(null_character, tmp) do strVal(i) = tmp(0) i += 1 j = 0 @@ -1025,60 +1032,60 @@ case class ACN(bitStream: BitStream) extends Codec { j += 1 bitStream.readByte() match - case None() => return None() + case None() => return NoneMut() case Some(ub) => tmp(null_character_size - 1) = ub strVal(i) = 0x0 - if !null_character.sameElements(tmp) then - return None() + if !arraySameElements(null_character, tmp) then + return NoneMut() - Some(strVal) + SomeMut(strVal) } - def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) } - def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): OptionMut[Array[ASCIIChar]] = { decodeConstraintWholeNumber(min, max) match - case None() => None() + case None() => NoneMut() case Some(nCount) => dec_String_Ascii_private(max, if nCount <= max then nCount else max) } - def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Option[Array[ASCIIChar]] = { + def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): OptionMut[Array[ASCIIChar]] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i < charactersToDecode do decodeConstraintWholeNumber(0, allowedCharSet.length - 1) match - case None() => return None() + case None() => return NoneMut() case Some(charIndex) => strVal(i) = allowedCharSet(charIndex.toInt) i += 1 - Some(strVal) + SomeMut(strVal) } - def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Option[Array[ASCIIChar]] = { + def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): OptionMut[Array[ASCIIChar]] = { dec_String_CharIndex_private(max, max, allowedCharSet) } - def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) } - def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Option[Array[ASCIIChar]] = { + def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): OptionMut[Array[ASCIIChar]] = { decodeConstraintWholeNumber(min, max) match - case None() => None() + case None() => NoneMut() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) } - def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Option[Array[ASCIIChar]] = { + def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { val allowedCharSet: Array[ASCIIChar] = Array( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, @@ -1097,7 +1104,7 @@ case class ACN(bitStream: BitStream) extends Codec { dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) } - def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Option[Array[ASCIIChar]] = { + def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): OptionMut[Array[ASCIIChar]] = { val allowedCharSet: Array[ASCIIChar] = Array( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, @@ -1114,7 +1121,7 @@ case class ACN(bitStream: BitStream) extends Codec { 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) decodeConstraintWholeNumber(min, max) match - case None() => None() + case None() => NoneMut() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) } From e98ea6e5e3ac44bff8e3134ada5b8358df196a5a Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 6 Nov 2023 15:12:27 +0100 Subject: [PATCH 073/174] renaming & different return vals --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 101 ++++++++---------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 41 +++---- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 58 +++++----- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 2 +- 4 files changed, 98 insertions(+), 104 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index a9257dbb3..0e78dc20c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -25,12 +25,12 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { (r1, r2) } -@ghost @pure -def readBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { - require(BitStream.validate_offset_bytes(pBitStrm, 1)) - val cpy = snapshot(pBitStrm) - (cpy, cpy.readByte()) -} +//@ghost @pure +//def readBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { +// require(BitStream.validate_offset_bytes(pBitStrm, 1)) +// val cpy = snapshot(pBitStrm) +// (cpy, cpy.readByte()) +//} // END TODO should be part of BitStream @@ -173,13 +173,13 @@ case class BitStream( ret } - @ghost - @pure - private def readBitPure(): (BitStream, Option[Boolean]) = { - require(BitStream.validate_offset_bit(this)) - val cpy = snapshot(this) - (cpy, cpy.readBit()) - } +// @ghost +// @pure +// private def readBitPure(): (BitStream, Option[Boolean]) = { +// require(BitStream.validate_offset_bit(this)) +// val cpy = snapshot(this) +// (cpy, cpy.readBit()) +// } // ****************** Append Bit Functions ********************** @@ -291,8 +291,11 @@ case class BitStream( * * nBits = 3 * MSB = 2^7 LSB = 2^0 + * | | * v = 1 0 0 1 0 1 1 0 + * | | | * x1 x2 x3 + * * x1 to x3 get added to the bitstream - starting with x1 * */ @@ -312,41 +315,40 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) /** - * Append byte (old implementation) + * Append whole byte to bitstream + * + * The MSB is written first into the bitstream * * Example - * cur bit = 3 - * | - * x x x b b b b b b b b - * |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| - * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 + * cur bit on Bitstream = 3 + * + * MSB LSB + * | | + * x x x b b b b b b b b + * _ _ _ _ _ _ _ _ _ _ _ _ _ + * 0 1 2 3 4 5 6 7 0 1 2 3 4 ... * - * first byte - * xxx????? - * and 11100000 (mask) - * -------------- - * xxx00000 - * or 000bbbbb - * -------------- - * xxxbbbbb + * Result: Pos 3 (MSB of v) to 10 (LSB of v) are written * * */ def appendByte(v: UByte): Unit = { require(BitStream.validate_offset_bytes(this, 1)) - var i = 0 - (while i < NO_OF_BITS_IN_BYTE do - decreases(NO_OF_BITS_IN_BYTE - i) - - appendBitFromByte(v, i) - - i += 1 - ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) + appendPartialByte(v, NO_OF_BITS_IN_BYTE) }.ensuring(_ => BitStream.invariant(this)) - def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { + /** + * NBytes of the given array is added to the bitstream + * + * The MSB of the arr[0] is written first + * + * @param arr is the source array + * @param noOfBytes that get written into the bitstream + * + */ + def appendByteArray(arr: Array[UByte], noOfBytes: Int): Unit = { require(0 <= noOfBytes && noOfBytes <= arr.length) require(BitStream.validate_offset_bytes(this, noOfBytes)) @@ -355,9 +357,8 @@ case class BitStream( decreases(noOfBytes - i) appendByte(arr(i)) i += 1 - ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) + ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) - true }.ensuring(_ => BitStream.invariant(this)) // ****************** Peak Functions ********************** @@ -369,17 +370,13 @@ case class BitStream( // ****************** Read Bit Functions ********************** - // TODO change return value? - def readBit(): Option[Boolean] = { + def readBit(): Boolean = { require(BitStream.validate_offset_bit(this)) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 increaseBitIndex() - if currentByte.toLong * 8 + currentBit <= buf.length.toLong * 8 then - Some(ret) - else - None() + ret }.ensuring(_ => BitStream.invariant(this)) def readBits(nBits: Int): OptionMut[Array[UByte]] = { @@ -392,11 +389,7 @@ case class BitStream( (while i < nBits do decreases(nBits - i) - readBit() match - case None() => - return NoneMut() - case Some(b) => - arr(i / NO_OF_BITS_IN_BYTE) |||= (if b then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) + arr(i / NO_OF_BITS_IN_BYTE) |||= (if readBit() then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) i += 1 ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) @@ -406,7 +399,7 @@ case class BitStream( // ****************** Read Byte Functions ********************** - def readByte(): Option[UByte] = { + def readByte(): UByte = { require(BitStream.validate_offset_bits(this, 8)) var ret = 0 @@ -414,15 +407,11 @@ case class BitStream( (while i < NO_OF_BITS_IN_BYTE do decreases(NO_OF_BITS_IN_BYTE - i) - readBit() match - case None() => - return None() - case Some(b) => - ret = ret | (if b then BitAccessMasks(i) else 0) + ret |= (if readBit() then BitAccessMasks(i) else 0) i += 1 ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) - Some(ret.toUnsignedByte) + ret.toUnsignedByte }.ensuring(_ => BitStream.invariant(this)) def readByteArray(nBytes: Int): OptionMut[Array[UByte]] = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 47a89d228..946823eee 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -124,7 +124,7 @@ trait Codec { decreases(nBits) v = v << 8 - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) @@ -334,7 +334,7 @@ trait Codec { while i < nBytes do decreases(nBytes - i) - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -357,7 +357,7 @@ trait Codec { while i < nBytes do decreases(nBytes - i) - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -398,7 +398,7 @@ trait Codec { while i < nBytes do decreases(nBytes - i) - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong @@ -505,7 +505,7 @@ trait Codec { } private def decodeRealBitString(): Option[Long] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(length) => // 8.5.2 Plus Zero @@ -516,7 +516,7 @@ trait Codec { if length < 0 || length > DoubleMaxLengthOfSentBytes then return None() - bitStream.readByte() match + readByte() match case None() => None() case Some(header) => // 8.5.6 a) @@ -574,7 +574,7 @@ trait Codec { (while i < expLen do decreases(expLen - i) - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) @@ -588,7 +588,7 @@ trait Codec { (while j < length do decreases(length - j) - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) @@ -617,7 +617,7 @@ trait Codec { while bit_terminated_pattern_size_in_bits >= 8 do decreases(bit_terminated_pattern_size_in_bits) - bitStream.readByte() match + readByte() match case None() => return 0 case Some(ub) => tmp_byte = ub @@ -653,7 +653,7 @@ trait Codec { checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do decreases(nMaxReadBits - bitsRead) - bitStream.readBit() match + readBit() match case None() => return NoneMut() case Some(bitVal) => tmpStrm.appendBit(bitVal) @@ -677,12 +677,13 @@ trait Codec { if cb == 0 then ret = bitStream.currentByte + nCount <= bitStream.buf.length - if ret then + if(ret) { copyToArray(arr, bitStream.buf, bitStream.currentByte, nCount) bitStream.currentByte += nCount + } - else - ret = bitStream.appendByteArray(arr, nCount) + else // TODO appendByteArray does not return a boolean value anymore + bitStream.appendByteArray(arr, nCount) ret } @@ -789,7 +790,7 @@ trait Codec { var i1: Int = nCurOffset1.toInt while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) - bitStream.readByte() match + readByte() match case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 @@ -821,7 +822,7 @@ trait Codec { // fill last payload fragment into dest while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) - bitStream.readByte() match + readByte() match case None() => return NoneMut() case Some(ub) => arr(i1) = ub i1 += 1 @@ -1024,7 +1025,7 @@ trait Codec { } def readBit(): Option[Boolean] = { - bitStream.readBit() + Some(bitStream.readBit()) } def peekBit(): Boolean = { @@ -1036,11 +1037,15 @@ trait Codec { } def readByte(): Option[UByte] = { - bitStream.readByte() + // TODO + Some(bitStream.readByte()) } def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { + // TODO + bitStream.appendByteArray(arr, arr_len) + true } @@ -1052,7 +1057,7 @@ trait Codec { bitStream.readBits(nbits) } - def appendPartialByte(vVal: UByte, nbits: UByte, negate: Boolean): Unit = { + def appendPartialByte(vVal: UByte, nbits: UByte): Unit = { bitStream.appendPartialByte(vVal, nbits) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index e1529e473..717200446 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -124,7 +124,7 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(ub) => Some(ub & 0xFF) } @@ -134,7 +134,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < SizeInBytes do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => ret <<= 8 @@ -163,7 +163,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < SizeInBytes do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => tmp = ub & 0xFF @@ -218,12 +218,12 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { var v: ULong = 0 - bitStream.readByte() match + readByte() match case None() => return None() case Some(nBytes) => var i: Int = 0 while i < nBytes do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => v = (v << 8) | (ub & 0xFF) @@ -283,14 +283,14 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < nBytes do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => pIntVal = (pIntVal << 8) | (ub & 0xFF) i += 1 if rstBits > 0 then - bitStream.readPartialByte(rstBits.toByte) match + readPartialByte(rstBits.toByte) match case None() => return None() case Some(ub) => pIntVal = (pIntVal << rstBits) | (ub & 0xFF) @@ -358,12 +358,12 @@ case class ACN(bitStream: BitStream) extends Codec { var v: ULong = 0 var isNegative: Boolean = false - bitStream.readByte() match + readByte() match case None() => None() case Some(nBytes) => var i: Int = 0 while i < nBytes do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => if i == 0 && (ub & 0x80) > 0 then @@ -444,7 +444,7 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) } @@ -458,7 +458,7 @@ case class ACN(bitStream: BitStream) extends Codec { /* Encode Number */ enc_Int_BCD_ConstSize(intVal, nNibbles) - bitStream.appendPartialByte(0xF, 4) + appendPartialByte(0xF, 4) CHECK_BIT_STREAM(bitStream) } @@ -517,7 +517,7 @@ case class ACN(bitStream: BitStream) extends Codec { var ret: ULong = 0 while encodedSizeInBytesVar > 0 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(digit) => assert(digit >= '0' && digit <= '9') @@ -531,7 +531,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(digit) => var sign: Int = 1 @@ -609,13 +609,13 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) } def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { - bitStream.readByte() match + readByte() match case None() => None() case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) } @@ -654,7 +654,7 @@ case class ACN(bitStream: BitStream) extends Codec { //read null_character_size characters into the tmp buffer var j: Int = 0 while j < null_characters_size do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -669,7 +669,7 @@ case class ACN(bitStream: BitStream) extends Codec { tmp(j) = tmp(j + 1) j += 1 - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => tmp(null_characters_size - 1) = ub @@ -685,7 +685,7 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { var isNegative: Boolean = false - bitStream.readByte() match + readByte() match case None() => None() case Some(digit) => assert(digit == '-' || digit == '+') @@ -707,7 +707,7 @@ case class ACN(bitStream: BitStream) extends Codec { var pBoolValue: Boolean = true var i: Int = 0 while i < nBytesToRead do - bitStream.readByte() match + readByte() match case None() => return None() case Some(curByte) => if curByte != patternToRead(i) then @@ -731,7 +731,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < nBytesToRead do - bitStream.readByte() match + readByte() match case None() => return Left(FAILED_READ_ERR_CODE) case Some(_) => i += 1 @@ -757,7 +757,7 @@ case class ACN(bitStream: BitStream) extends Codec { val b: Array[Byte] = Array.fill(4)(0) var i: Int = 0 while i < 4 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -770,7 +770,7 @@ case class ACN(bitStream: BitStream) extends Codec { val b: Array[Byte] = Array.fill(4)(0) var i: Int = 0 while i < 4 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -793,7 +793,7 @@ case class ACN(bitStream: BitStream) extends Codec { val b: Array[Byte] = Array.fill(8)(0) var i: Int = 0 while i < 8 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => b(i) = ub i += 1 @@ -822,7 +822,7 @@ case class ACN(bitStream: BitStream) extends Codec { val b: Array[Byte] = Array.fill(4)(0) var i: Int = 3 while i >= 0 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -844,7 +844,7 @@ case class ACN(bitStream: BitStream) extends Codec { val b: Array[Byte] = Array.fill(8)(0) var i: Int = 7 while i >= 0 do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => b(i) = ub i -= 1 @@ -971,7 +971,7 @@ case class ACN(bitStream: BitStream) extends Codec { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i < charactersToDecode do - bitStream.readByte() match + readByte() match case None() => return None() case Some(decodedCharacter) => strVal(i) = decodedCharacter @@ -988,7 +988,7 @@ case class ACN(bitStream: BitStream) extends Codec { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i <= max do - bitStream.readByte() match + readByte() match case None() => return None() case Some(decodedCharacter) => if decodedCharacter != null_character then @@ -1009,7 +1009,7 @@ case class ACN(bitStream: BitStream) extends Codec { //read null_character_size characters into the tmp buffer var j: Int = 0 while j < null_character_size do - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => tmp(j) = ub j += 1 @@ -1024,7 +1024,7 @@ case class ACN(bitStream: BitStream) extends Codec { tmp(j) = tmp(j + 1) j += 1 - bitStream.readByte() match + readByte() match case None() => return None() case Some(ub) => tmp(null_character_size - 1) = ub diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 63b203c42..b701ead43 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -100,7 +100,7 @@ case class UPER(bitStream: BitStream) extends Codec { var pRemainingOctets: Long = pRemainingOctetsVal while pRemainingOctets > 0 && !bLastOctet do decreases(pRemainingOctets) - bitStream.readByte() match + readByte() match case None() => return None() case Some(curByte) => pRemainingOctets -= 1 From 7bb82e4dcc99ab1e8d570eaf0f5d4db6c435c8fe Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 6 Nov 2023 15:18:12 +0100 Subject: [PATCH 074/174] remove optionMut from readBits in bitstream --- .../main/scala/asn1scala/asn1jvm_Bitstream.scala | 8 +++++--- .../src/main/scala/asn1scala/asn1jvm_Codec.scala | 13 +++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 0e78dc20c..2a00a9103 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -355,7 +355,9 @@ case class BitStream( var i: Int = 0 (while i < noOfBytes do decreases(noOfBytes - i) + appendByte(arr(i)) + i += 1 ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) @@ -379,7 +381,7 @@ case class BitStream( ret }.ensuring(_ => BitStream.invariant(this)) - def readBits(nBits: Int): OptionMut[Array[UByte]] = { + def readBits(nBits: Int): Array[UByte] = { require(nBits > 0 && (nBits <= Integer.MAX_VALUE - NO_OF_BITS_IN_BYTE)) // TODO remaining bits in stream as upper bound, not MAX_VAL require(BitStream.validate_offset_bits(this, nBits)) @@ -394,7 +396,7 @@ case class BitStream( i += 1 ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) - SomeMut(arr) + arr }.ensuring(_ => BitStream.invariant(this)) // ****************** Read Byte Functions ********************** @@ -414,7 +416,7 @@ case class BitStream( ret.toUnsignedByte }.ensuring(_ => BitStream.invariant(this)) - def readByteArray(nBytes: Int): OptionMut[Array[UByte]] = { + def readByteArray(nBytes: Int): Array[UByte] = { require(0 < nBytes && nBytes <= buf.length) require(BitStream.validate_offset_bytes(this, nBytes)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 946823eee..6e97e06eb 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -700,7 +700,7 @@ trait Codec { bitStream.currentByte += nCount else - bitStream.readByteArray(nCount) match + readByteArray(nCount) match case NoneMut() => return NoneMut() case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) @@ -935,7 +935,7 @@ trait Codec { else nCount = asn1SizeMin - return bitStream.readBits(nCount.toInt) + return readBits(nCount.toInt) } else { var nRemainingItemsVar1: Long = 0 @@ -965,7 +965,7 @@ trait Codec { return NoneMut() /*COVERAGE_IGNORE*/ - bitStream.readBits(nCurBlockSize1.toInt) match + readBits(nCurBlockSize1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) @@ -985,7 +985,7 @@ trait Codec { if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - bitStream.readBits(nRemainingItemsVar1.toInt) match + readBits(nRemainingItemsVar1.toInt) match case NoneMut() => return NoneMut() case SomeMut(t) => arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) @@ -1050,11 +1050,12 @@ trait Codec { def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { - bitStream.readByteArray(arr_len) + // TODO + SomeMut(bitStream.readByteArray(arr_len)) } def readBits(nbits: Int): OptionMut[Array[UByte]] = { - bitStream.readBits(nbits) + readBits(nbits) } def appendPartialByte(vVal: UByte, nbits: UByte): Unit = { From c818a1713d626b0a1bd3d10218e5d4c80e3f49c8 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 6 Nov 2023 15:24:25 +0100 Subject: [PATCH 075/174] introduce remainingBits for BitStream --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 108 +++++++----------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 3 +- 2 files changed, 46 insertions(+), 65 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 2a00a9103..913eb8c35 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -27,7 +27,7 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { //@ghost @pure //def readBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { -// require(BitStream.validate_offset_bytes(pBitStrm, 1)) +// require(pBitStrm.validate_offset_bytes(1)) // val cpy = snapshot(pBitStrm) // (cpy, cpy.readByte()) //} @@ -46,47 +46,6 @@ object BitStream { 0 <= currentBit && currentBit <= 7 &&& 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) } - - @ghost - def validate_offset_bit(pBitStrm: BitStream): Boolean = { - // var new_currentBit: Int = pBitStrm.currentBit + 1 - // var new_currentByte: Int = pBitStrm.currentByte - // - // if new_currentBit > 7 then - // new_currentBit = new_currentBit % 8 - // new_currentByte += 1 - // - // 0 <= new_currentBit - // && new_currentBit <= 7 - // && 0 <= new_currentByte - // && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && pBitStrm.currentByte <= pBitStrm.buf.length)) - pBitStrm.currentByte < pBitStrm.buf.length - } - - @ghost - def validate_offset_bits(pBitStrm: BitStream, bits: Int = 0): Boolean = { - require(bits >= 0) - val nBits = bits % 8 - val nBytes = bits / 8 - - var new_currentByte: Long = pBitStrm.currentByte.toLong + nBytes - var new_currentBit: Long = pBitStrm.currentBit.toLong + nBits - - if new_currentBit > 7 then - new_currentBit = new_currentBit % 8 - new_currentByte += 1 - - 0 <= new_currentBit - && new_currentBit <= 7 - && 0 <= new_currentByte - && (new_currentByte < pBitStrm.buf.length || (new_currentBit == 0 && new_currentByte <= pBitStrm.buf.length)) - } - - @ghost - def validate_offset_bytes(pBitStrm: BitStream, bytes: Int = 0): Boolean = { - val new_currentByte: Long = pBitStrm.currentByte.toLong + bytes - new_currentByte < pBitStrm.buf.length || (pBitStrm.currentBit == 0 && new_currentByte <= pBitStrm.buf.length) - } } private val BitAccessMasks: Array[UByte] = Array( @@ -119,6 +78,24 @@ case class BitStream( ) { // all BisStream instances satisfy the following: require(BitStream.invariant(currentByte, currentBit, buf.length)) + private var remainingBits: Long = buf.length.toLong * 8 + + @ghost + def validate_offset_bit(): Boolean = { + remainingBits >= 1 + } + + @ghost + def validate_offset_bits(bits: Int = 0): Boolean = { + require(bits >= 0) + remainingBits >= bits + } + + @ghost + def validate_offset_bytes(bytes: Int = 0): Boolean = { + require(bytes >= 0) + remainingBits >= bytes.toLong * 8 + } def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong @@ -131,6 +108,8 @@ case class BitStream( else currentBit = 0 currentByte += 1 + + remainingBits -= 1 }.ensuring {_ => val oldBitStrm = old(this) oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& @@ -154,6 +133,7 @@ case class BitStream( this.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... currentByte = 0 currentBit = 0 + remainingBits = buf.length.toLong * 8 }.ensuring(_ => this.buf == buf && currentByte == 0 && currentBit == 0) /** @@ -176,7 +156,7 @@ case class BitStream( // @ghost // @pure // private def readBitPure(): (BitStream, Option[Boolean]) = { -// require(BitStream.validate_offset_bit(this)) +// require(validate_offset_bit()) // val cpy = snapshot(this) // (cpy, cpy.readBit()) // } @@ -196,7 +176,7 @@ case class BitStream( * */ def appendBit(b: Boolean): Unit = { - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) if b then buf(currentByte) = (buf(currentByte) | BitAccessMasks(currentBit)).toByte else @@ -206,14 +186,14 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) def appendBitOne(): Unit = { - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) appendBit(true) } def appendNBitOne(nBits: Int): Unit = { require(nBits >= 0) - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) var i = 0 (while i < nBits do @@ -226,14 +206,14 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) def appendBitZero(): Unit = { - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) appendBit(false) } def appendNBitZero(nBits: Int): Unit = { require(nBits >= 0) - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) var i = 0 (while i < nBits do @@ -258,7 +238,7 @@ case class BitStream( private def appendBitFromByte(b: Byte, bitNr: Int): Unit = { require(bitNr >= 0 && bitNr < NO_OF_BITS_IN_BYTE) - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) val bitPosInByte = 1 << ((NO_OF_BITS_IN_BYTE - 1) - bitNr) appendBit((b.unsignedToInt & bitPosInByte) != 0) @@ -267,7 +247,7 @@ case class BitStream( def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { require(nBits >= 0 && nBits / 8 < srcBuffer.length) - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) var i = 0 (while(i < nBits) do @@ -276,7 +256,7 @@ case class BitStream( appendBitFromByte(srcBuffer(i / NO_OF_BITS_IN_BYTE), i % NO_OF_BITS_IN_BYTE) i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) }.ensuring(_ => BitStream.invariant(this)) // ****************** Append Byte Functions ********************** @@ -302,7 +282,7 @@ case class BitStream( def appendPartialByte(v: UByte, nBits: Int): Unit = { require(nBits >= 0 &&& nBits <= NO_OF_BITS_IN_BYTE) - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) var i = 0 (while i < nBits do @@ -333,7 +313,7 @@ case class BitStream( * */ def appendByte(v: UByte): Unit = { - require(BitStream.validate_offset_bytes(this, 1)) + require(validate_offset_bytes(1)) appendPartialByte(v, NO_OF_BITS_IN_BYTE) @@ -350,7 +330,7 @@ case class BitStream( */ def appendByteArray(arr: Array[UByte], noOfBytes: Int): Unit = { require(0 <= noOfBytes && noOfBytes <= arr.length) - require(BitStream.validate_offset_bytes(this, noOfBytes)) + require(validate_offset_bytes(noOfBytes)) var i: Int = 0 (while i < noOfBytes do @@ -359,21 +339,21 @@ case class BitStream( appendByte(arr(i)) i += 1 - ).invariant(0 <= i &&& i <= noOfBytes &&& BitStream.validate_offset_bytes(this, noOfBytes - i)) + ).invariant(0 <= i &&& i <= noOfBytes &&& validate_offset_bytes(noOfBytes - i)) }.ensuring(_ => BitStream.invariant(this)) // ****************** Peak Functions ********************** def peekBit(): Boolean = { - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 } // ****************** Read Bit Functions ********************** def readBit(): Boolean = { - require(BitStream.validate_offset_bit(this)) + require(validate_offset_bit()) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 increaseBitIndex() @@ -383,7 +363,7 @@ case class BitStream( def readBits(nBits: Int): Array[UByte] = { require(nBits > 0 && (nBits <= Integer.MAX_VALUE - NO_OF_BITS_IN_BYTE)) // TODO remaining bits in stream as upper bound, not MAX_VAL - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) val arr: Array[UByte] = Array.fill((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE)(0) @@ -394,7 +374,7 @@ case class BitStream( arr(i / NO_OF_BITS_IN_BYTE) |||= (if readBit() then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& BitStream.validate_offset_bits(this, nBits - i)) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) arr }.ensuring(_ => BitStream.invariant(this)) @@ -402,7 +382,7 @@ case class BitStream( // ****************** Read Byte Functions ********************** def readByte(): UByte = { - require(BitStream.validate_offset_bits(this, 8)) + require(validate_offset_bits(8)) var ret = 0 var i = 0 @@ -411,14 +391,14 @@ case class BitStream( ret |= (if readBit() then BitAccessMasks(i) else 0) i += 1 - ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& BitStream.validate_offset_bits(this, NO_OF_BITS_IN_BYTE - i)) + ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& validate_offset_bits(NO_OF_BITS_IN_BYTE - i)) ret.toUnsignedByte }.ensuring(_ => BitStream.invariant(this)) def readByteArray(nBytes: Int): Array[UByte] = { require(0 < nBytes && nBytes <= buf.length) - require(BitStream.validate_offset_bytes(this, nBytes)) + require(validate_offset_bytes(nBytes)) readBits(nBytes * NO_OF_BITS_IN_BYTE) }.ensuring(_ => BitStream.invariant(this)) @@ -427,7 +407,7 @@ case class BitStream( /* nbits 1..7*/ def readPartialByte(nBits: Int): Option[UByte] = { require(0 < nBits && nBits < 8) - require(BitStream.validate_offset_bits(this, nBits)) + require(validate_offset_bits(nBits)) var v: UByte = 0 val totalBits = currentBit + nBits @@ -435,7 +415,7 @@ case class BitStream( if (totalBits <= 8) { v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nBits)).toByte ghostExpr { - BitStream.validate_offset_bits(this, nBits) + validate_offset_bits(nBits) } if currentBit + nBits >= 8 then currentBit = (currentBit + nBits) % 8 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 6e97e06eb..f6e8f7ae9 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1029,7 +1029,7 @@ trait Codec { } def peekBit(): Boolean = { - bitStream.peekBit() + bitStream.peekBit() } def appendByte(value: Byte): Unit = { @@ -1063,6 +1063,7 @@ trait Codec { } def readPartialByte(nbits: UByte): Option[UByte] = { + assert(bitStream.validate_offset_bits(nbits)) bitStream.readPartialByte(nbits) } } From 6d01eb5fe2bc58e9a96c3885e3cbaeeb26399ae2 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 6 Nov 2023 15:24:56 +0100 Subject: [PATCH 076/174] comment --- asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 2a00a9103..9dc0e6a1e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -249,7 +249,7 @@ case class BitStream( /** * Append bit with bitNr from b to bitstream * - * bit 0 is the MSB, bit 7 is the LSB, ASN.1 standard declares bit 1 as MSB, + * bit 0 is the MSB, bit 7 is the LSB, ASN.1? / ESA? declares bit 1 as MSB, * bit 8 as LSB - but we start from 0 in CS * * @param b byte that gets the bit extracted from From df18f0eb15286e00ef1a2d448e9cb6601cee2e70 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 6 Nov 2023 15:33:42 +0100 Subject: [PATCH 077/174] remove option from readPartialByte --- .../src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 11 +++-------- .../src/main/scala/asn1scala/asn1jvm_Codec.scala | 11 +++++++---- .../src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala | 8 ++++---- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index c2bdfcbad..1f191f933 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -99,7 +99,7 @@ case class BitStream( def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong - }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong) + }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) def increaseBitIndex(): Unit = { require(currentByte < buf.length) @@ -405,7 +405,7 @@ case class BitStream( /* nbits 1..7*/ - def readPartialByte(nBits: Int): Option[UByte] = { + def readPartialByte(nBits: Int): UByte = { require(0 < nBits && nBits < 8) require(validate_offset_bits(nBits)) @@ -431,11 +431,6 @@ case class BitStream( v = (v & masksb(nBits)).toByte currentBit = totalBitsForNextByte.toInt } - - if BitStream.invariant(this) then - Some(v) - else - None() + v } - } // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index f6e8f7ae9..3119fcdd5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -135,7 +135,7 @@ trait Codec { if nBits != 0 then v = v << nBits - bitStream.readPartialByte(nBits.toByte) match + readPartialByte(nBits.toByte) match case None() => return None() case Some(ub) => v = v | (ub & 0xFF) @@ -629,7 +629,7 @@ trait Codec { i += 1 if bit_terminated_pattern_size_in_bits > 0 then - bitStream.readPartialByte(bit_terminated_pattern_size_in_bits) match + readPartialByte(bit_terminated_pattern_size_in_bits) match case None() => return 0 case Some(ub) => tmp_byte = ub @@ -1063,7 +1063,10 @@ trait Codec { } def readPartialByte(nbits: UByte): Option[UByte] = { - assert(bitStream.validate_offset_bits(nbits)) - bitStream.readPartialByte(nbits) + val isValidPrecondition = bitStream.validate_offset_bits(nbits) + assert(isValidPrecondition) + isValidPrecondition match + case true => Some(bitStream.readPartialByte(nbits)) + case false => None() } } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 1da3f0ecb..5e218c26b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -427,7 +427,7 @@ case class ACN(bitStream: BitStream) extends Codec { var encodedSizeInNibblesVar = encodedSizeInNibbles while encodedSizeInNibblesVar > 0 do - bitStream.readPartialByte(4) match + readPartialByte(4) match case None() => return None() case Some(digit) => ret *= 10 @@ -474,7 +474,7 @@ case class ACN(bitStream: BitStream) extends Codec { var ret: ULong = 0 while true do - bitStream.readPartialByte(4) match + readPartialByte(4) match case None() => return None() case Some(digit) => if (digit > 9) @@ -722,7 +722,7 @@ case class ACN(bitStream: BitStream) extends Codec { i += 1 if nRemainingBitsToRead > 0 then - bitStream.readPartialByte(nRemainingBitsToRead.toByte) match + readPartialByte(nRemainingBitsToRead.toByte) match case None() => return None() case Some(curByte) => if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then @@ -743,7 +743,7 @@ case class ACN(bitStream: BitStream) extends Codec { case Some(_) => i += 1 if nRemainingBitsToRead > 0 then - if bitStream.readPartialByte(nRemainingBitsToRead.toByte).isEmpty then + if readPartialByte(nRemainingBitsToRead.toByte).isEmpty then return Left(FAILED_READ_ERR_CODE) Right(0) From 7d0f2cb92c698d621807dde9620c8a70bffbe93f Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 6 Nov 2023 15:49:20 +0100 Subject: [PATCH 078/174] fix readBits --- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 3119fcdd5..92ddc53ad 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1055,7 +1055,8 @@ trait Codec { } def readBits(nbits: Int): OptionMut[Array[UByte]] = { - readBits(nbits) + // TODO + SomeMut(bitStream.readBits(nbits)) } def appendPartialByte(vVal: UByte, nbits: UByte): Unit = { From a4ceca941b977b0e59b5214dcd5f1ee8b72449af Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 6 Nov 2023 16:15:33 +0100 Subject: [PATCH 079/174] rewrote readpartialbyte --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 102 +++++++++++------- 1 file changed, 63 insertions(+), 39 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 1f191f933..83452648e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -125,9 +125,10 @@ case class BitStream( /** * Set new internal buffer + * * @param buf Byte array that should be attached to this BitStream + * */ - @extern def attachBuffer(buf: Array[UByte]): Unit = { this.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... @@ -137,14 +138,14 @@ case class BitStream( }.ensuring(_ => this.buf == buf && currentByte == 0 && currentBit == 0) /** - * * Return count of bytes that got already fully or partially written - * Example: - * Currentbyte = 4, currentBit = 2 --> 5 - * Currentbyte = 14, currentBit = 0 --> 14 * * @return the number of used bytes so far * + * Example: + * Currentbyte = 4, currentBit = 2 --> 5 + * Currentbyte = 14, currentBit = 0 --> 14 + * */ def getLength(): Int = { var ret: Int = currentByte @@ -229,13 +230,14 @@ case class BitStream( /** * Append bit with bitNr from b to bitstream * + * @param b byte that gets the bit extracted from + * @param bitNr 0 to 7 - number of the bit + * + * Remarks: * bit 0 is the MSB, bit 7 is the LSB, ASN.1? / ESA? declares bit 1 as MSB, * bit 8 as LSB - but we start from 0 in CS * - * @param b byte that gets the bit extracted from - * @param bitNr 0 to 7 - number of the bit */ - private def appendBitFromByte(b: Byte, bitNr: Int): Unit = { require(bitNr >= 0 && bitNr < NO_OF_BITS_IN_BYTE) require(validate_offset_bit()) @@ -274,9 +276,9 @@ case class BitStream( * | | * v = 1 0 0 1 0 1 1 0 * | | | - * x1 x2 x3 + * b1 b2 b3 * - * x1 to x3 get added to the bitstream - starting with x1 + * b1 to b3 get added to the bitstream - starting with b1 * */ @@ -294,12 +296,16 @@ case class BitStream( ).invariant(i >= 0 && i <= nBits) }.ensuring(_ => BitStream.invariant(this)) + /** * Append whole byte to bitstream * + * @param v gets appended to the bitstream + * + * Remarks: * The MSB is written first into the bitstream * - * Example + * Example: * cur bit on Bitstream = 3 * * MSB LSB @@ -308,10 +314,9 @@ case class BitStream( * _ _ _ _ _ _ _ _ _ _ _ _ _ * 0 1 2 3 4 5 6 7 0 1 2 3 4 ... * - * Result: Pos 3 (MSB of v) to 10 (LSB of v) are written + * Pos 3 (MSB of v) to 10 (LSB of v) are written * * */ - def appendByte(v: UByte): Unit = { require(validate_offset_bytes(1)) @@ -322,11 +327,12 @@ case class BitStream( /** * NBytes of the given array is added to the bitstream * - * The MSB of the arr[0] is written first - * * @param arr is the source array * @param noOfBytes that get written into the bitstream * + * Remarks: + * The MSB of the arr[0] is written first + * */ def appendByteArray(arr: Array[UByte], noOfBytes: Int): Unit = { require(0 <= noOfBytes && noOfBytes <= arr.length) @@ -404,33 +410,51 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) - /* nbits 1..7*/ + /** + * Read nBits from Bitstream into Byte + * + * @param nBits get read from the bitstream + * @return combined bits into Byte + * + * Remarks: + * nBits starts at LSB and goes upward + * + * Example: + * cur bit on Bitstream = 2 + * nBits = 3 + * + * Bitstream: + * x x b1 b2 b3 + * _ _ _ _ _ _ _ _ + * 0 1 2 3 4 5 6 ... + * + * Return Val: + * MSB LSB + * | | + * v = 0 0 0 0 0 _ _ _ + * 7 6 5 4 3 2 1 0 + * | | | + * b1 b2 b3 + * + * b1 to b3 are extracted from the bitstream + * and written into v + * + */ def readPartialByte(nBits: Int): UByte = { require(0 < nBits && nBits < 8) require(validate_offset_bits(nBits)) - var v: UByte = 0 - val totalBits = currentBit + nBits - - if (totalBits <= 8) { - v = ((buf(currentByte) >>>> (8 - totalBits)) & masksb(nBits)).toByte - ghostExpr { - validate_offset_bits(nBits) - } - if currentBit + nBits >= 8 then - currentBit = (currentBit + nBits) % 8 - currentByte += 1 - else - currentBit += nBits - - } else { - var totalBitsForNextByte: UByte = (totalBits - 8).toByte - v = (buf(currentByte) <<<< totalBitsForNextByte) - currentByte += 1 - v = (v | buf(currentByte) >>>> (8 - totalBitsForNextByte)).toByte - v = (v & masksb(nBits)).toByte - currentBit = totalBitsForNextByte.toInt - } + var v = 0.toByte + var i = 0 + (while i < nBits do + decreases(nBits - i) + + v |||= (if readBit() then BitAccessMasks(NO_OF_BITS_IN_BYTE - nBits + i) else 0) + + i += 1 + ).invariant(i >= 0 && i <= nBits) + v - } + }.ensuring(_ => BitStream.invariant(this)) + } // BitStream class From 26b3ab5c9469afc8ab4a16a26e8bca98580f8347 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Tue, 7 Nov 2023 00:31:29 +0100 Subject: [PATCH 080/174] comments added --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 83452648e..0250815b6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -186,12 +186,21 @@ case class BitStream( increaseBitIndex() }.ensuring(_ => BitStream.invariant(this)) + /** + * Append a set bit + */ def appendBitOne(): Unit = { require(validate_offset_bit()) appendBit(true) } + /** + * Append n set bits to bitstream + * + * @param nBits number of bits + * + */ def appendNBitOne(nBits: Int): Unit = { require(nBits >= 0) require(validate_offset_bits(nBits)) @@ -206,12 +215,21 @@ case class BitStream( ).invariant(i >= 0 &&& i <= nBits) }.ensuring(_ => BitStream.invariant(this)) + /** + * Append cleared bit to bitstream + */ def appendBitZero(): Unit = { require(validate_offset_bit()) appendBit(false) } + /** + * Append n cleared bit to bitstream + * + * @param nBits number of bits + * + */ def appendNBitZero(nBits: Int): Unit = { require(nBits >= 0) require(validate_offset_bits(nBits)) @@ -247,6 +265,16 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) + /** + * Append nBits from srcBuffer to bitstream + * + * @param srcBuffer source of the bits to add + * @param nBits number of bits to add + * + * Remarks: + * bit 0 is the MSB of the first byte of srcBuffer + * + */ def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { require(nBits >= 0 && nBits / 8 < srcBuffer.length) require(validate_offset_bits(nBits)) @@ -351,6 +379,12 @@ case class BitStream( // ****************** Peak Functions ********************** + /** + * Preview the next bit on the bitstream + * + * @return peeked bit + * + */ def peekBit(): Boolean = { require(validate_offset_bit()) ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 @@ -358,6 +392,12 @@ case class BitStream( // ****************** Read Bit Functions ********************** + /** + * Read single bit from the bitstream + * + * @return next bit on the bitstream + * + */ def readBit(): Boolean = { require(validate_offset_bit()) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 @@ -367,6 +407,16 @@ case class BitStream( ret }.ensuring(_ => BitStream.invariant(this)) + /** + * Read multiple bits from the bitstream + * + * @param nBits number of bits to read + * @return array of read bits + * + * Remarks: + * First bit is written into the MSB of Byte 0 + * + */ def readBits(nBits: Int): Array[UByte] = { require(nBits > 0 && (nBits <= Integer.MAX_VALUE - NO_OF_BITS_IN_BYTE)) // TODO remaining bits in stream as upper bound, not MAX_VAL require(validate_offset_bits(nBits)) @@ -387,6 +437,15 @@ case class BitStream( // ****************** Read Byte Functions ********************** + /** + * Read whole byte from the bitstream + * + * @return byte read from bitstream + * + * Remarks: + * First bit read from bitstream is the return bytes MSB + * + */ def readByte(): UByte = { require(validate_offset_bits(8)) From 4eff09c1b6efe6c96376b1eea85679ba6a37b7f6 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Tue, 7 Nov 2023 08:35:15 +0100 Subject: [PATCH 081/174] - finish implementing BitStream access functions on Codec - redirect direct access on BitStream functions --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 5 + .../main/scala/asn1scala/asn1jvm_Codec.scala | 132 ++++++++++++------ .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 60 ++++---- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 8 +- 4 files changed, 129 insertions(+), 76 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 0250815b6..f819fecd2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -91,6 +91,11 @@ case class BitStream( remainingBits >= bits } + @ghost + def validate_offset_byte(): Boolean = { + remainingBits >= 8 + } + @ghost def validate_offset_bytes(bytes: Int = 0): Boolean = { require(bytes >= 0) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 92ddc53ad..ebee793f1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -101,7 +101,7 @@ trait Codec { if pbits > 0 then cc -= pbits var b = (v >>> cc).toByte - bitStream.appendPartialByte(if negate then (~b).toByte else b, pbits.toByte) + appendPartialByte(if negate then (~b).toByte else b, pbits.toByte) while cc > 0 do decreases(cc) @@ -112,7 +112,7 @@ trait Codec { if negate then b = ~b - bitStream.appendByte(b.toUnsignedByte) + appendByte(b.toUnsignedByte) } def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { @@ -151,7 +151,7 @@ trait Codec { encodeNonNegativeInteger32Neg(hi, false) val nBits: Int = GetNumberOfBitsForNonNegativeInteger(lo.toLong << 32 >>> 32) // TODO: is this easier? - bitStream.appendNBitZero(32 - nBits) + appendNBitZero(32 - nBits) encodeNonNegativeInteger32Neg(lo, false) } @@ -189,7 +189,7 @@ trait Codec { if negate then lo = ~lo val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) - bitStream.appendNBitZero(32 - nBits) + appendNBitZero(32 - nBits) encodeNonNegativeInteger32Neg(lo, false) } @@ -203,7 +203,7 @@ trait Codec { val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) - bitStream.appendNBitZero(nRangeBits - nBits); + appendNBitZero(nRangeBits - nBits); encodeNonNegativeInteger((v - min)) } @@ -217,7 +217,7 @@ trait Codec { return val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - bitStream.appendNBitZero(nRangeBits - nBits) + appendNBitZero(nRangeBits - nBits) encodeNonNegativeInteger(v - min) } @@ -303,7 +303,7 @@ trait Codec { encodeConstraintWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) + appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) /*Encode number */ encodeNonNegativeInteger((v - min)) } @@ -316,7 +316,7 @@ trait Codec { encodeConstraintWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) + appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) /*Encode number */ encodeNonNegativeInteger(v - min) } @@ -374,7 +374,7 @@ trait Codec { /*8 bits, first bit is always 0*/ if v >= 0 then - bitStream.appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) + appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) encodeNonNegativeInteger(v) else bitStream.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) @@ -390,7 +390,7 @@ trait Codec { case None() => return None() case Some(l) => nBytes = l - val valIsNegative: Boolean = bitStream.peekBit() + val valIsNegative: Boolean = peekBit() var v: Long = if valIsNegative then Long.MaxValue else 0 @@ -485,13 +485,13 @@ trait Codec { /* encode exponent */ if exponent >= 0 then // fill with zeros to have a whole byte - bitStream.appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) + appendNBitZero(nExpLen * 8 - GetNumberOfBitsForNonNegativeInteger(exponent)) encodeNonNegativeInteger(exponent) else encodeNonNegativeInteger(compactExp) /* encode mantissa */ - bitStream.appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) + appendNBitZero(nManLen * 8 - GetNumberOfBitsForNonNegativeInteger(mantissa)) encodeNonNegativeInteger(mantissa) } @@ -567,7 +567,7 @@ trait Codec { return None() // decode exponent - val expIsNegative = bitStream.peekBit() + val expIsNegative = peekBit() var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 var i: Int = 0 @@ -668,7 +668,7 @@ trait Codec { if checkBitPatternPresentResult != 2 then return NoneMut() - return SomeMut((tmpStrm.buf, bitsRead)) + SomeMut((tmpStrm.buf, bitsRead)) } def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { @@ -683,7 +683,7 @@ trait Codec { } else // TODO appendByteArray does not return a boolean value anymore - bitStream.appendByteArray(arr, nCount) + appendByteArray(arr, nCount) ret } @@ -731,7 +731,7 @@ trait Codec { var i1: Int = nCurOffset1 while i1 < nCurBlockSize1 + nCurOffset1 do decreases(nCurBlockSize1 + nCurOffset1 - i1) - bitStream.appendByte(arr(i1)) + appendByte(arr(i1)) i1 += 1 nCurOffset1 += nCurBlockSize1 @@ -741,14 +741,14 @@ trait Codec { if nRemainingItemsVar1 <= 0x7F then encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) else - bitStream.appendBit(true) + appendBit(true) encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) var i1: Int = nCurOffset1 while i1 < (nCurOffset1 + nRemainingItemsVar1) do decreases(nCurOffset1 + nRemainingItemsVar1 - i1) - bitStream.appendByte(arr(i1)) + appendByte(arr(i1)) i1 += 1 return ret @@ -882,7 +882,7 @@ trait Codec { if asn1SizeMin != asn1SizeMax then encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - bitStream.appendBits(arr, nCount) + appendBits(arr, nCount) else var nRemainingItemsVar1: Long = nCount.toLong @@ -906,7 +906,7 @@ trait Codec { encodeConstraintWholeNumber(0xC1, 0, 0xFF) val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) - bitStream.appendBits(t, nCurBlockSize1.toInt) + appendBits(t, nCurBlockSize1.toInt) nCurOffset1 += nCurBlockSize1 nRemainingItemsVar1 -= nCurBlockSize1 @@ -914,11 +914,11 @@ trait Codec { if nRemainingItemsVar1 <= 0x7F then encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) else - bitStream.appendBit(true) + appendBit(true) encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) - bitStream.appendBits(t, nRemainingItemsVar1.toInt) + appendBits(t, nRemainingItemsVar1.toInt) true } @@ -1001,31 +1001,59 @@ trait Codec { def appendBitOne(): Unit = { - bitStream.appendBitOne() + val isValidPrecondition = bitStream.validate_offset_bit() + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendBitOne() + case false => () } def appendBitZero(): Unit = { - bitStream.appendBitZero() + val isValidPrecondition = bitStream.validate_offset_bit() + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendBitZero() + case false => () } - def appendNBitZero(nBitsVal: Int): Unit = { - bitStream.appendNBitZero(nBitsVal) + def appendNBitZero(nBits: Int): Unit = { + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendNBitZero(nBits) + case false => () } - def appendNBitOne(nBitsVal: Int): Unit = { - bitStream.appendNBitOne(nBitsVal) + def appendNBitOne(nBits: Int): Unit = { + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendNBitOne(nBits) + case false => () } def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { - bitStream.appendBits(srcBuffer, nBits) + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendBits(srcBuffer, nBits) + case false => () } def appendBit(v: Boolean): Unit = { + val isValidPrecondition = bitStream.validate_offset_bit() + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendBit(v) } def readBit(): Option[Boolean] = { - Some(bitStream.readBit()) + val isValidPrecondition = bitStream.validate_offset_bit() + assert(isValidPrecondition) + isValidPrecondition match + case true => Some(bitStream.readBit()) + case false => None() } def peekBit(): Boolean = { @@ -1033,34 +1061,54 @@ trait Codec { } def appendByte(value: Byte): Unit = { - bitStream.appendByte(value) + val isValidPrecondition = bitStream.validate_offset_byte() + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendByte(value) + case false => () } def readByte(): Option[UByte] = { - // TODO - Some(bitStream.readByte()) + val isValidPrecondition = bitStream.validate_offset_byte() + assert(isValidPrecondition) + isValidPrecondition match + case true => Some(bitStream.readByte()) + case false => None() } def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { - // TODO - - bitStream.appendByteArray(arr, arr_len) - true + val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + assert(isValidPrecondition) + isValidPrecondition match + case true => + bitStream.appendByteArray(arr, arr_len) + true + case false => false } def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { - // TODO - SomeMut(bitStream.readByteArray(arr_len)) + val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + assert(isValidPrecondition) + isValidPrecondition match + case true => SomeMut(bitStream.readByteArray(arr_len)) + case false => NoneMut() } def readBits(nbits: Int): OptionMut[Array[UByte]] = { - // TODO - SomeMut(bitStream.readBits(nbits)) + val isValidPrecondition = bitStream.validate_offset_bits(nbits) + assert(isValidPrecondition) + isValidPrecondition match + case true => SomeMut(bitStream.readBits(nbits)) + case false => NoneMut() } def appendPartialByte(vVal: UByte, nbits: UByte): Unit = { - bitStream.appendPartialByte(vVal, nbits) + val isValidPrecondition = bitStream.validate_offset_bits(nbits) + assert(isValidPrecondition) + isValidPrecondition match + case true => bitStream.appendPartialByte(vVal, nbits) + case false => () } def readPartialByte(nbits: UByte): Option[UByte] = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 5e218c26b..b0238a615 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -58,7 +58,7 @@ case class ACN(bitStream: BitStream) extends Codec { val nBits: Int = GetNumberOfBitsForNonNegativeInteger(intVal) /* put required zeros*/ // TODO what if nBits > encodedSizeInBits ?? - bitStream.appendNBitZero(encodedSizeInBits - nBits) + appendNBitZero(encodedSizeInBits - nBits) /*Encode number */ encodeNonNegativeInteger(intVal) @@ -66,7 +66,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { - bitStream.appendByte(intVal.toByte) + appendByte(intVal.toByte) CHECK_BIT_STREAM(bitStream) } @@ -78,7 +78,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < size do val byteToEncode: Byte = ((tmp & mask) >>> ((size - i - 1) * 8)).toByte - bitStream.appendByte(byteToEncode) + appendByte(byteToEncode) mask >>>= 8 i += 1 @@ -103,7 +103,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < size do val byteToEncode: Byte = tmp.toByte - bitStream.appendByte(byteToEncode) + appendByte(byteToEncode) tmp >>>= 8 i += 1 @@ -205,7 +205,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < nBytes do val byteToEncode: Byte = ((vv & MAX_BYTE_MASK) >>> ((NO_OF_BYTES_IN_JVM_LONG - 1) * 8)).toByte - bitStream.appendByte(byteToEncode) + appendByte(byteToEncode) vv <<= 8 i += 1 } @@ -215,7 +215,7 @@ case class ACN(bitStream: BitStream) extends Codec { val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte /* encode length */ - bitStream.appendByte(nBytes) + appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(intVal, nBytes) @@ -242,11 +242,11 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_Int_TwosComplement_ConstSize(intVal: Long, encodedSizeInBits: Int): Unit = { if intVal >= 0 then - bitStream.appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) + appendNBitZero(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(intVal)) encodeNonNegativeInteger(intVal) else - bitStream.appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) + appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) encodeNonNegativeIntegerNeg(-intVal - 1, true) CHECK_BIT_STREAM(bitStream) @@ -282,7 +282,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { - val valIsNegative: Boolean = bitStream.peekBit() + val valIsNegative: Boolean = peekBit() val nBytes: Int = encodedSizeInBits / 8 val rstBits: Int = encodedSizeInBits % 8 @@ -353,7 +353,7 @@ case class ACN(bitStream: BitStream) extends Codec { val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte /* encode length */ - bitStream.appendByte(nBytes) + appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(int2uint(intVal), nBytes) @@ -415,7 +415,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = encodedSizeInNibbles - 1 while i >= 0 do - bitStream.appendPartialByte(tmp(i).toByte, 4) + appendPartialByte(tmp(i).toByte, 4) i -= 1 CHECK_BIT_STREAM(bitStream) @@ -441,7 +441,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_Int_BCD_VarSize_LengthEmbedded(intVal: ULong): Unit = { val nNibbles: Int = get_Int_Size_BCD(intVal) /* encode length */ - bitStream.appendByte(nNibbles.toByte) + appendByte(nNibbles.toByte) /* Encode Number */ enc_Int_BCD_ConstSize(intVal, nNibbles) @@ -503,7 +503,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i = encodedSizeInBytes - 1 while i >= 0 do - bitStream.appendByte((tmp(i) + CHAR_ZERO).toByte) + appendByte((tmp(i) + CHAR_ZERO).toByte) i -= 1 CHECK_BIT_STREAM(bitStream) @@ -514,7 +514,7 @@ case class ACN(bitStream: BitStream) extends Codec { val absIntVal: ULong = if intVal >= 0 then intVal else -intVal /* encode sign */ - bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) + appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) } @@ -586,15 +586,15 @@ case class ACN(bitStream: BitStream) extends Codec { val (digitsArray100, nChars) = getIntegerDigits(absIntVal) /* encode length, plus 1 for sign */ - bitStream.appendByte((nChars + 1).toByte) + appendByte((nChars + 1).toByte) /* encode sign */ - bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) + appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte(digitsArray100(i)) + appendByte(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -604,11 +604,11 @@ case class ACN(bitStream: BitStream) extends Codec { val (digitsArray100, nChars) = getIntegerDigits(intVal) /* encode length */ - bitStream.appendByte(nChars) + appendByte(nChars) /* encode digits */ var i: Int = 0 while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte(digitsArray100(i)) + appendByte(digitsArray100(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -633,12 +633,12 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 // TODO: size_t? while i < 100 && digitsArray100(i) != 0x0 do - bitStream.appendByte(digitsArray100(i)) + appendByte(digitsArray100(i)) i += 1 i = 0 while i < null_characters_size do - bitStream.appendByte(null_characters(i)) + appendByte(null_characters(i)) i += 1 CHECK_BIT_STREAM(bitStream) @@ -646,7 +646,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { val absValue: ULong = if intVal >= 0 then intVal else -intVal - bitStream.appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) + appendByte(if intVal >= 0 then CHAR_PLUS else CHAR_MINUS) enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) } @@ -756,7 +756,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < 4 do - bitStream.appendByte(b(i)) + appendByte(b(i)) i += 1 } @@ -792,7 +792,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < 8 do - bitStream.appendByte(b(i)) + appendByte(b(i)) i += 1 } @@ -815,7 +815,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 3 while i >= 0 do - bitStream.appendByte(b(i)) + appendByte(b(i)) i -= 1 } @@ -843,7 +843,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 7 while i >= 0 do - bitStream.appendByte(b(i)) + appendByte(b(i)) i -= 1 } @@ -865,14 +865,14 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { var i: Long = 0 while i < max do - bitStream.appendByte(strVal(i.toInt)) + appendByte(strVal(i.toInt)) i += 1 } def enc_String_Ascii_private(max: Long, strVal: Array[ASCIIChar]): Long = { var i: Long = 0 while (i < max) && (strVal(i.toInt) != CHAR_0000) do - bitStream.appendByte(strVal(i.toInt)) + appendByte(strVal(i.toInt)) i += 1 i @@ -880,14 +880,14 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_Null_Teminated(max: Long, null_character: Byte, strVal: Array[ASCIIChar]): Unit = { enc_String_Ascii_private(max, strVal) - bitStream.appendByte(null_character.toByte) + appendByte(null_character.toByte) } def enc_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[Byte], null_character_size: Int, strVal: Array[ASCIIChar]): Unit = { enc_String_Ascii_private(max, strVal) var i: Int = 0 while i < null_character_size do - bitStream.appendByte(null_character(i)) + appendByte(null_character(i)) i += 1 } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index b701ead43..bd008fb3f 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -56,13 +56,13 @@ case class UPER(bitStream: BitStream) extends Codec { if totalSize <= 0x7F then encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) else - bitStream.appendBit(true) + appendBit(true) encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do decreases(totalSize - i) - bitStream.appendByte(tmp(i)) + appendByte(tmp(i)) i += 1 } @@ -83,13 +83,13 @@ case class UPER(bitStream: BitStream) extends Codec { if totalSize <= 0x7F then encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) else - bitStream.appendBit(true) + appendBit(true) encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do decreases(totalSize - i) - bitStream.appendByte(tmp(i)) + appendByte(tmp(i)) i += 1 } From 5a0891d8b189235c7121dcbb8b8b23d24901b437 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Tue, 7 Nov 2023 16:43:36 +0100 Subject: [PATCH 082/174] some return type fixes --- StgScala/acn_scala.stg | 4 ++-- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 37d0faac4..999b688bd 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -516,8 +516,8 @@ codec.enc_IA5String_CharIndex_External_Field_Determinant(,

) Acn_IA5String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) match - case None() => return Left() - case Some(x) =>

= x + case NoneMut() => return Left() + case SomeMut(x) =>

= x >> diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index ebee793f1..cc8b925bc 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -682,8 +682,8 @@ trait Codec { bitStream.currentByte += nCount } - else // TODO appendByteArray does not return a boolean value anymore - appendByteArray(arr, nCount) + else + ret = appendByteArray(arr, nCount) ret } From e3b2876459fcf05aa4ec6afa570f2f4b5977c5c3 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 9 Nov 2023 00:00:44 +0100 Subject: [PATCH 083/174] Verified 764 / 769 --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 111 +++++++++--------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_PER.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 2 +- .../main/scala/asn1scala/asn1jvm_Helper.scala | 8 +- 6 files changed, 63 insertions(+), 64 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index f819fecd2..e1d78253a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -8,22 +8,22 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* -// TODO should be part of BitStream -def isPrefix(b1: BitStream, b2: BitStream): Boolean = { - b1.buf.length <= b2.buf.length && - b1.bitIndex() <= b2.bitIndex() && - (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex()) -} - -def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) - -@ghost -def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { - require(isValidPair(w1, w2)) - val r1 = BitStream(snapshot(w2.buf), w1.currentByte, w1.currentBit) - val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) - (r1, r2) -} +//// TODO should be part of BitStream +//def isPrefix(b1: BitStream, b2: BitStream): Boolean = { +// b1.buf.length <= b2.buf.length && +// b1.bitIndex() <= b2.bitIndex() && +// (b1.buf.length != 0) ==> arrayBitPrefix(b1.buf, b2.buf, 0, b1.bitIndex()) +//} +// +//def isValidPair(w1: BitStream, w2: BitStream): Boolean = isPrefix(w1, w2) + +//@ghost +//def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { +// require(isValidPair(w1, w2)) +// val r1 = BitStream(snapshot(w2.buf), w1.currentByte, w1.currentBit) +// val r2 = BitStream(snapshot(w2.buf), w2.currentByte, w2.currentBit) +// (r1, r2) +//} //@ghost @pure //def readBytePure(pBitStrm: BitStream): (BitStream, Option[Byte]) = { @@ -36,15 +36,18 @@ def reader(w1: BitStream, w2: BitStream): (BitStream, BitStream) = { object BitStream { + @pure @inline - def invariant(pBitStrm: BitStream): Boolean = { - BitStream.invariant(pBitStrm.currentByte, pBitStrm.currentBit, pBitStrm.buf.length) + def invariant(bs: BitStream): Boolean = { + invariant(bs.remainingBits, bs.currentBit, bs.currentByte, bs.buf.length) } + @pure @inline - def invariant(currentByte: Int, currentBit: Int, buf_length: Int): Boolean = { - 0 <= currentBit && currentBit <= 7 &&& - 0 <= currentByte && (currentByte < buf_length || (currentBit == 0 && currentByte <= buf_length)) + def invariant(remainingBits: Long, currentBit: Int, currentByte: Int, buffLength: Int): Boolean = { + remainingBits == ((buffLength.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit)) && + currentBit >= 0 && currentBit < NO_OF_BITS_IN_BYTE && + currentByte >= 0 && ((currentByte < buffLength) | (currentBit == 0 && currentByte == buffLength)) } } @@ -59,6 +62,7 @@ private val BitAccessMasks: Array[UByte] = Array( 0x01, // 1 / 0000 0001 / x01 ) +// TODO maybe remove, only needed in old verification step val masksb: Array[UByte] = Array( 0x00, // 0 / 0000 0000 / x00 0x01, // 1 / 0000 0001 / x01 @@ -73,41 +77,41 @@ val masksb: Array[UByte] = Array( case class BitStream( var buf: Array[Byte], + private var remainingBits: Long, var currentByte: Int = 0, // marks the currentByte that gets accessed var currentBit: Int = 0, // marks the next bit that gets accessed ) { // all BisStream instances satisfy the following: - require(BitStream.invariant(currentByte, currentBit, buf.length)) - - private var remainingBits: Long = buf.length.toLong * 8 + require(BitStream.invariant(remainingBits, currentBit, currentByte, buf.length)) @ghost def validate_offset_bit(): Boolean = { remainingBits >= 1 - } + }.ensuring(_ => BitStream.invariant(this)) @ghost def validate_offset_bits(bits: Int = 0): Boolean = { require(bits >= 0) remainingBits >= bits - } + }.ensuring(_ => BitStream.invariant(this)) @ghost def validate_offset_byte(): Boolean = { - remainingBits >= 8 - } + remainingBits >= NO_OF_BITS_IN_BYTE + }.ensuring(_ => BitStream.invariant(this)) @ghost - def validate_offset_bytes(bytes: Int = 0): Boolean = { + def validate_offset_bytes(bytes: Int): Boolean = { require(bytes >= 0) - remainingBits >= bytes.toLong * 8 - } + bytes <= remainingBits / NO_OF_BITS_IN_BYTE + }.ensuring(_ => BitStream.invariant(this)) def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) - def increaseBitIndex(): Unit = { - require(currentByte < buf.length) + private def increaseBitIndex(): Unit = { + require(remainingBits > 0) + if currentBit < 7 then currentBit += 1 else @@ -115,19 +119,14 @@ case class BitStream( currentByte += 1 remainingBits -= 1 + }.ensuring {_ => val oldBitStrm = old(this) oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& + oldBitStrm.remainingBits - remainingBits == 1 &&& BitStream.invariant(this) } - // TODO not used - @inlineOnce @opaque @ghost - private def ensureInvariant(): Unit = { - }.ensuring(_ => - BitStream.invariant(currentByte, currentBit, buf.length) - ) - /** * Set new internal buffer * @@ -136,7 +135,7 @@ case class BitStream( */ @extern def attachBuffer(buf: Array[UByte]): Unit = { - this.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... + this.buf = buf // Illegal aliasing, therefore we need to workaround this with @extern... currentByte = 0 currentBit = 0 remainingBits = buf.length.toLong * 8 @@ -217,7 +216,7 @@ case class BitStream( appendBitOne() i += 1 - ).invariant(i >= 0 &&& i <= nBits) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) }.ensuring(_ => BitStream.invariant(this)) /** @@ -227,7 +226,7 @@ case class BitStream( require(validate_offset_bit()) appendBit(false) - } + }.ensuring(_ => BitStream.invariant(this)) /** * Append n cleared bit to bitstream @@ -246,7 +245,7 @@ case class BitStream( appendBitZero() i += 1 - ).invariant(i >= 0 &&& i <= nBits) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) }.ensuring(_ => BitStream.invariant(this)) @@ -326,10 +325,9 @@ case class BitStream( appendBitFromByte(v, NO_OF_BITS_IN_BYTE - nBits + i) i += 1 - ).invariant(i >= 0 && i <= nBits) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) }.ensuring(_ => BitStream.invariant(this)) - /** * Append whole byte to bitstream * @@ -390,10 +388,11 @@ case class BitStream( * @return peeked bit * */ + @pure def peekBit(): Boolean = { require(validate_offset_bit()) ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 - } + }.ensuring(_ => BitStream.invariant(this)) // ****************** Read Bit Functions ********************** @@ -404,6 +403,7 @@ case class BitStream( * */ def readBit(): Boolean = { + require(BitStream.invariant(this)) require(validate_offset_bit()) val ret = (buf(currentByte) & BitAccessMasks(currentBit)) != 0 @@ -423,19 +423,19 @@ case class BitStream( * */ def readBits(nBits: Int): Array[UByte] = { - require(nBits > 0 && (nBits <= Integer.MAX_VALUE - NO_OF_BITS_IN_BYTE)) // TODO remaining bits in stream as upper bound, not MAX_VAL - require(validate_offset_bits(nBits)) + require(nBits >= 0 && validate_offset_bits(nBits)) - val arr: Array[UByte] = Array.fill((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE)(0) + val arr: Array[UByte] = Array.fill(((nBits.toLong + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt)(0) var i = 0 (while i < nBits do decreases(nBits - i) - arr(i / NO_OF_BITS_IN_BYTE) |||= (if readBit() then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) + arr(i / NO_OF_BITS_IN_BYTE) |||= (if readBit() then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i) && + arr.length == ((nBits.toLong + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) // TODO stainless counter examples with wrong array sizes otherwise arr }.ensuring(_ => BitStream.invariant(this)) @@ -467,7 +467,8 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) def readByteArray(nBytes: Int): Array[UByte] = { - require(0 < nBytes && nBytes <= buf.length) + require(nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) + require(nBytes >= 0 && nBytes <= remainingBits / NO_OF_BITS_IN_BYTE) require(validate_offset_bytes(nBytes)) readBits(nBytes * NO_OF_BITS_IN_BYTE) @@ -505,7 +506,7 @@ case class BitStream( * */ def readPartialByte(nBits: Int): UByte = { - require(0 < nBits && nBits < 8) + require(nBits >= 0 && nBits < NO_OF_BITS_IN_BYTE) require(validate_offset_bits(nBits)) var v = 0.toByte @@ -516,7 +517,7 @@ case class BitStream( v |||= (if readBit() then BitAccessMasks(NO_OF_BITS_IN_BYTE - nBits + i) else 0) i += 1 - ).invariant(i >= 0 && i <= nBits) + ).invariant(i >= 0 && i <= nBits && validate_offset_bits(nBits - i)) v }.ensuring(_ => BitStream.invariant(this)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index cc8b925bc..51657eb64 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -48,7 +48,7 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { // TODO remove def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), 0, 0) + BitStream(Array.fill(count)(0), count.toLong * 8, 0, 0) } /** diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index b0238a615..f3d9b38fe 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -23,7 +23,7 @@ def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { * @return ACN coded bitstream */ def initACNCodec(count: Int): ACN = { - ACN(BitStream(Array.fill(count)(0))) + ACN(BitStream(Array.fill(count)(0), count.toLong * 8)) } case class ACN(bitStream: BitStream) extends Codec { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala index 8a497030c..be4b77a1e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala @@ -7,7 +7,7 @@ package asn1scala * @return PER coded bitstream */ def initPERCodec(count: Int): PER = { - PER(BitStream(Array.fill(count)(0))) + PER(BitStream(Array.fill(count)(0), count.toLong * 8)) } case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index bd008fb3f..c762ae5d2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -9,7 +9,7 @@ import stainless.lang.{None => None, Option => Option, Some => Some, _} * @return UPER coded bitstream */ def initUPERCodec(count: Int): UPER = { - UPER(BitStream(Array.fill(count)(0))) + UPER(BitStream(Array.fill(count)(0), count.toLong * 8)) } case class UPER(bitStream: BitStream) extends Codec { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index 63f4da62a..b2a3defe5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -59,14 +59,12 @@ extension (ui: UInt) { extension (i: Int) { def toUnsignedByte: UByte = { - var iVal = i & MASK_BYTE - - if(iVal == MASK_MSB_BYTE) + if((i & MASK_BYTE) == MASK_MSB_BYTE) (-MASK_MSB_BYTE).toByte else if ((i & MASK_MSB_BYTE) == MASK_MSB_BYTE) ((i & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte else - i.toByte + (i & MASK_BYTE).toByte } } @@ -166,7 +164,7 @@ def CalculateMantissaAndExponent(doubleAsLong64: Long): (UInt, ULong) = { (exponent, mantissa) }.ensuring((e, m) => e >= (-DoubleBias - DoubleNoOfMantissaBits) &&& e <= (DoubleBias - DoubleNoOfMantissaBits) - &&& m >= 0 &&& m <= MantissaBitMask) + &&& m >= 0 &&& m <= (MantissaBitMask | MantissaExtraBit)) def GetDoubleBitStringByMantissaAndExp(mantissa: ULong, exponentVal: Int): Long = { ((exponentVal + DoubleBias + DoubleNoOfMantissaBits) << DoubleNoOfMantissaBits) | (mantissa & MantissaBitMask) From 1e13e171e9addfb4022beebceeb5d63ddad612fb Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 9 Nov 2023 13:28:55 +0100 Subject: [PATCH 084/174] avoid direct access on bitStream currentBit/currentByte/buf --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 17 ++++++ .../main/scala/asn1scala/asn1jvm_Codec.scala | 46 ++++----------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 58 +------------------ 3 files changed, 30 insertions(+), 91 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index e1d78253a..81d3ac1a5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -522,4 +522,21 @@ case class BitStream( v }.ensuring(_ => BitStream.invariant(this)) + + // ************** Aligning functions ********* + def alignToByte(): Unit = { + if currentBit != 0 then + currentBit = 0 + currentByte += 1 + } + + def alignToShort(): Unit = { + alignToByte() + currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + } + + def alignToInt(): Unit = { + alignToByte() + currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + } } // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 51657eb64..26aec0f6e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -377,7 +377,7 @@ trait Codec { appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) encodeNonNegativeInteger(v) else - bitStream.appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) + appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) encodeNonNegativeIntegerNeg((-v - 1), true) } @@ -547,8 +547,7 @@ trait Codec { private def decodeRealFromBitStream(lengthVal: Int, header: UByte): Option[Long] = { require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) - require(bitStream.buf.length > lengthVal) - require(bitStream.currentByte < bitStream.buf.length - lengthVal) + require(bitStream.validate_offset_bytes(lengthVal)) // 8.5.7.2 Base val expFactor: Int = header.unsignedToInt match @@ -606,11 +605,13 @@ trait Codec { def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal + require(bitStream.validate_offset_bits(bit_terminated_pattern_size_in_bits)) + val tmp_currentByte: Int = bitStream.currentByte val tmp_currentBit: Int = bitStream.currentBit var tmp_byte: UByte = 0 - if bitStream.currentByte.toLong * 8 + bitStream.currentBit + bit_terminated_pattern_size_in_bits.toInt > bitStream.buf.length.toLong * 8 then + if !bitStream.validate_offset_bits(bit_terminated_pattern_size_in_bitsVal) then return 0 var i: Int = 0 @@ -672,39 +673,16 @@ trait Codec { } def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { - val cb = bitStream.currentBit - var ret: Boolean = false - - if cb == 0 then - ret = bitStream.currentByte + nCount <= bitStream.buf.length - if(ret) { - copyToArray(arr, bitStream.buf, bitStream.currentByte, nCount) - bitStream.currentByte += nCount - } - - else - ret = appendByteArray(arr, nCount) - - ret + appendByteArray(arr, nCount) } def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { - val cb: Int = bitStream.currentBit - val arr: Array[UByte] = Array.fill(nCount + 1)(0) - - if cb == 0 then - if bitStream.currentByte + nCount > bitStream.buf.length then - return NoneMut() - - arrayCopyOffset(bitStream.buf, arr, bitStream.currentByte, bitStream.currentByte + nCount, 0) - bitStream.currentByte += nCount - - else - readByteArray(nCount) match - case NoneMut() => return NoneMut() - case SomeMut(a) => arrayCopyOffsetLen(a, arr, 0, 0, a.length) - - SomeMut(arr) + readByteArray(nCount) match + case NoneMut() => NoneMut() + case SomeMut(a) => + val arr: Array[UByte] = Array.fill(nCount + 1)(0) // TODO: why is +1 needed? + arrayCopyOffsetLen(a, arr, 0, 0, a.length) + SomeMut(arr) } def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index f3d9b38fe..e545be4f5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -11,12 +11,6 @@ val CHAR_ZERO: ASCIIChar = 48 val CHAR_NINE: ASCIIChar = 57 val CHAR_0000: ASCIIChar = 0 - -// TODO remove / replace by invariant -def CHECK_BIT_STREAM(pBitStrm: BitStream): Unit = { - assert(pBitStrm.currentByte.toLong * 8 + pBitStrm.currentBit <= pBitStrm.buf.length.toLong * 8) -} - /** * Get an instance of a ACN coded bitstream * @param count of elements in underlaying buffer @@ -28,27 +22,6 @@ def initACNCodec(count: Int): ACN = { case class ACN(bitStream: BitStream) extends Codec { - def alignToByte(): Unit = { - if bitStream.currentBit != 0 then - bitStream.currentBit = 0 - bitStream.currentByte += 1 - CHECK_BIT_STREAM(bitStream) - } - - def alignToShort(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT - CHECK_BIT_STREAM(bitStream) - } - - def alignToInt(): Unit = { - alignToByte() - bitStream.currentByte = ((bitStream.currentByte + - (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT - CHECK_BIT_STREAM(bitStream) - } - /*ACN Integer functions*/ def enc_Int_PositiveInteger_ConstSize(intVal: ULong, encodedSizeInBits: Int): Unit = { if encodedSizeInBits == 0 then @@ -61,13 +34,10 @@ case class ACN(bitStream: BitStream) extends Codec { appendNBitZero(encodedSizeInBits - nBits) /*Encode number */ encodeNonNegativeInteger(intVal) - - CHECK_BIT_STREAM(bitStream) } def enc_Int_PositiveInteger_ConstSize_8(intVal: ULong): Unit = { appendByte(intVal.toByte) - CHECK_BIT_STREAM(bitStream) } def enc_Int_PositiveInteger_ConstSize_big_endian_B(intVal: ULong, size: Int): Unit = { @@ -81,8 +51,6 @@ case class ACN(bitStream: BitStream) extends Codec { appendByte(byteToEncode) mask >>>= 8 i += 1 - - CHECK_BIT_STREAM(bitStream) } def enc_Int_PositiveInteger_ConstSize_big_endian_16(intVal: ULong): Unit = { @@ -106,8 +74,6 @@ case class ACN(bitStream: BitStream) extends Codec { appendByte(byteToEncode) tmp >>>= 8 i += 1 - - CHECK_BIT_STREAM(bitStream) } def enc_Int_PositiveInteger_ConstSize_little_endian_16(intVal: ULong): Unit = { @@ -190,9 +156,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { - val ret = dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) - bitStream.currentByte += (8 - NO_OF_BYTES_IN_JVM_LONG) - ret + dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) } @@ -218,8 +182,6 @@ case class ACN(bitStream: BitStream) extends Codec { appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(intVal, nBytes) - - CHECK_BIT_STREAM(bitStream) } def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { @@ -248,8 +210,6 @@ case class ACN(bitStream: BitStream) extends Codec { else appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) encodeNonNegativeIntegerNeg(-intVal - 1, true) - - CHECK_BIT_STREAM(bitStream) } @@ -356,8 +316,6 @@ case class ACN(bitStream: BitStream) extends Codec { appendByte(nBytes) /* Encode integer data*/ encode_UnsignedInteger(int2uint(intVal), nBytes) - - CHECK_BIT_STREAM(bitStream) } @@ -417,8 +375,6 @@ case class ACN(bitStream: BitStream) extends Codec { while i >= 0 do appendPartialByte(tmp(i).toByte, 4) i -= 1 - - CHECK_BIT_STREAM(bitStream) } @@ -445,8 +401,6 @@ case class ACN(bitStream: BitStream) extends Codec { /* Encode Number */ enc_Int_BCD_ConstSize(intVal, nNibbles) - - CHECK_BIT_STREAM(bitStream) } @@ -466,8 +420,6 @@ case class ACN(bitStream: BitStream) extends Codec { enc_Int_BCD_ConstSize(intVal, nNibbles) appendPartialByte(0xF, 4) - - CHECK_BIT_STREAM(bitStream) } def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { @@ -505,8 +457,6 @@ case class ACN(bitStream: BitStream) extends Codec { while i >= 0 do appendByte((tmp(i) + CHAR_ZERO).toByte) i -= 1 - - CHECK_BIT_STREAM(bitStream) } @@ -596,8 +546,6 @@ case class ACN(bitStream: BitStream) extends Codec { while i < 100 && digitsArray100(i) != 0x0 do appendByte(digitsArray100(i)) i += 1 - - CHECK_BIT_STREAM(bitStream) } def enc_UInt_ASCII_VarSize_LengthEmbedded(intVal: ULong): Unit = { @@ -610,8 +558,6 @@ case class ACN(bitStream: BitStream) extends Codec { while i < 100 && digitsArray100(i) != 0x0 do appendByte(digitsArray100(i)) i += 1 - - CHECK_BIT_STREAM(bitStream) } @@ -640,8 +586,6 @@ case class ACN(bitStream: BitStream) extends Codec { while i < null_characters_size do appendByte(null_characters(i)) i += 1 - - CHECK_BIT_STREAM(bitStream) } def enc_SInt_ASCII_VarSize_NullTerminated(intVal: Long, null_characters: Array[Byte], null_characters_size: Int): Unit = { From 59e2f9e52178c9b5e036692298c56ef2bc842445 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 9 Nov 2023 14:29:09 +0100 Subject: [PATCH 085/174] ujujuj --- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 51657eb64..770fb61c2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -621,7 +621,7 @@ trait Codec { case None() => return 0 case Some(ub) => tmp_byte = ub - bit_terminated_pattern_size_in_bits = 8 + bit_terminated_pattern_size_in_bits -= 8 if bit_terminated_pattern(i) != tmp_byte then bitStream.currentByte = tmp_currentByte bitStream.currentBit = tmp_currentBit From 9aa3341f46df59db902bce78a2942f71ff27f8d9 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 9 Nov 2023 14:53:58 +0100 Subject: [PATCH 086/174] docs to readbits & minor changes --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 20 ++++++++++++++++++- .../scala/asn1scala/asn1jvm_Codec_PER.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 7 ++++--- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index e1d78253a..77933952d 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -256,7 +256,7 @@ case class BitStream( * @param bitNr 0 to 7 - number of the bit * * Remarks: - * bit 0 is the MSB, bit 7 is the LSB, ASN.1? / ESA? declares bit 1 as MSB, + * bit 0 is the MSB, bit 7 is the LSB, ESA declares bit 1 as MSB, * bit 8 as LSB - but we start from 0 in CS * */ @@ -421,6 +421,24 @@ case class BitStream( * Remarks: * First bit is written into the MSB of Byte 0 * + * Example: + * nBits = 10 + * curBits on bitstream = 3 + * + * bits on stream x x b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 x + * currentBit 0 1 2 3 4 5 6 7 0 1 2 3 4 ... + * | | + * start of byte n start of byte n+1 + * + * arr = ByteArray with size 2 (10bits need 2 bytes) get + * returned with this structure + * LSB byte 0 LSB byte 1 + * | | 0 padding | + * b0 b1 b2 b3 | b4 b5 b6 b7 || b8 b9 0 0 | 0 0 0 0 + * i: 1 2 3 4 5 6 7 8 9 10 + * | | + * MSB byte 0 MSB byte 1 + * */ def readBits(nBits: Int): Array[UByte] = { require(nBits >= 0 && validate_offset_bits(nBits)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala index be4b77a1e..30745debd 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala @@ -7,7 +7,7 @@ package asn1scala * @return PER coded bitstream */ def initPERCodec(count: Int): PER = { - PER(BitStream(Array.fill(count)(0), count.toLong * 8)) + PER(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) } case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index c762ae5d2..3267eaa94 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -9,12 +9,12 @@ import stainless.lang.{None => None, Option => Option, Some => Some, _} * @return UPER coded bitstream */ def initUPERCodec(count: Int): UPER = { - UPER(BitStream(Array.fill(count)(0), count.toLong * 8)) + UPER(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) } case class UPER(bitStream: BitStream) extends Codec { - def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { + private def objectIdentifier_subIdentifiers_encode(encodingBuf: Array[UByte], pSizeVal: Int, siValueVal: ULong): Int = { var lastOctet: Boolean = false val tmp: Array[UByte] = Array.fill(16)(0) var nSize: Int = 0 @@ -37,7 +37,8 @@ case class UPER(bitStream: BitStream) extends Codec { encodingBuf(pSize) = curByte pSize += 1 i += 1 - return pSize + + pSize } def ObjectIdentifier_encode(pVal: Asn1ObjectIdentifier): Unit = { From 6eb691c172ca7f9006558ba8e6636df21a5392ee Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 9 Nov 2023 15:34:32 +0100 Subject: [PATCH 087/174] refactor checkBitPatternPresent and readBits_nullterminated --- StgScala/acn_scala.stg | 36 +++--- StgScala/test_cases_scala.stg | 8 +- .../scala/asn1scala/asn1jvm_Bitstream.scala | 55 +++++++-- .../main/scala/asn1scala/asn1jvm_Codec.scala | 115 +++++++----------- 4 files changed, 113 insertions(+), 101 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 999b688bd..db07bfa96 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -570,26 +570,28 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -codec.appendBits((byte[]){}, ) +codec.appendBits(Array({}), ) >> oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +// TODO: check if it works as intended = 0 ret = Right(0) -while ret.isRight && \< && ((checkBitPatternPresentResult = codec.checkBitPatternPresent((byte[]){}, )) == 1)) do + +var checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) +while ret.isRight && \< && !checkBitPatternPresentResult.getOrElse(true) do += 1 + checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) -if ret.isRight && ( == ) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = codec.checkBitPatternPresent((byte[]){}, ) +if ret.isRight && ( == ) && !checkBitPatternPresentResult.getOrElse(true) then + checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) -if (ret && (checkBitPatternPresentResult == 0)) { - ret = FALSE; /*COVERAGE_IGNORE*/ - *pErrCode = ; /*COVERAGE_IGNORE*/ -} else if (ret && (checkBitPatternPresentResult == 2)) { -

nCount = ; - ret = true; - *pErrCode = 0; +if (ret && checkBitPatternPresentResult.isEmpty) { + ret = Left() /*COVERAGE_IGNORE*/ +} else if (ret && checkBitPatternPresentResult.get) { +

nCount = + ret = Right(0) } >> @@ -622,15 +624,15 @@ if (\<=) && (\<=) t bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << codec.appendBits(

arr,

nCount) -codec.appendBits((byte[]){}, ) +codec.appendBits(Array({}), ) >> bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -// TODO acn:620 - wrong ret value? reads bits untill 0 termination, but only length is returned, not the datanullterminated.rReadBits_BitStrm, (byte[]){}, ,

arr, ) match - case None() => - return Left() - case Some(x) => -

nCount = x + codec.readBits_nullterminated(Array({}), , ) match + case NoneMut() => + return Left() + case SomeMut(x) => +

arr = x >> RefTypeParam_tmpVar(sName, sTypeDecl) ::= " " diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 792c223e7..87eb017a7 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -339,13 +339,13 @@ def (output: TestOutput): Int = output.report_failure_begin() errorCode match case 1 => - output.report_failure_message("Test case failed in encoding.") + output.report_failure_message("Test case '/' failed in encoding.") case 2 => - output.report_failure_message("Test case '' failed in decoding.") + output.report_failure_message("Test case '/' failed in decoding.") case 3 => - output.report_failure_message("Test case '' failed in the validation of the decoded message.") + output.report_failure_message("Test case '/' failed in the validation of the decoded message.") case 4 => - output.report_failure_message("Test case '' failed. Encoded and decoded messages are different.") + output.report_failure_message("Test case '/' failed. Encoded and decoded messages are different.") case _ => output.report_failure_message("Unexpected error code in test case ''.") output.report_failure_message("========================================") diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index e6c4b6990..951b60041 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -89,7 +89,7 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) @ghost - def validate_offset_bits(bits: Int = 0): Boolean = { + def validate_offset_bits(bits: Long = 0): Boolean = { require(bits >= 0) remainingBits >= bits }.ensuring(_ => BitStream.invariant(this)) @@ -205,7 +205,7 @@ case class BitStream( * @param nBits number of bits * */ - def appendNBitOne(nBits: Int): Unit = { + def appendNBitOne(nBits: Long): Unit = { require(nBits >= 0) require(validate_offset_bits(nBits)) @@ -234,7 +234,7 @@ case class BitStream( * @param nBits number of bits * */ - def appendNBitZero(nBits: Int): Unit = { + def appendNBitZero(nBits: Long): Unit = { require(nBits >= 0) require(validate_offset_bits(nBits)) @@ -279,7 +279,7 @@ case class BitStream( * bit 0 is the MSB of the first byte of srcBuffer * */ - def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { + def appendBits(srcBuffer: Array[UByte], nBits: Long): Unit = { require(nBits >= 0 && nBits / 8 < srcBuffer.length) require(validate_offset_bits(nBits)) @@ -440,10 +440,10 @@ case class BitStream( * MSB byte 0 MSB byte 1 * */ - def readBits(nBits: Int): Array[UByte] = { + def readBits(nBits: Long): Array[UByte] = { require(nBits >= 0 && validate_offset_bits(nBits)) - val arr: Array[UByte] = Array.fill(((nBits.toLong + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt)(0) + val arr: Array[UByte] = Array.fill(((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt)(0) var i = 0 (while i < nBits do @@ -453,7 +453,7 @@ case class BitStream( i += 1 ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i) && - arr.length == ((nBits.toLong + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) // TODO stainless counter examples with wrong array sizes otherwise + arr.length == ((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) // TODO stainless counter examples with wrong array sizes otherwise arr }.ensuring(_ => BitStream.invariant(this)) @@ -541,6 +541,47 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) + + def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { + require(validate_offset_bits(nBits)) + val tmp_currentBit = currentBit + val tmp_currentByte = currentByte + val tmp_remainingBits = remainingBits + + val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) + + if !ret then + currentBit = tmp_currentBit + currentByte = tmp_currentByte + remainingBits = tmp_remainingBits + + ret + } + + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): (Array[UByte], Int) = { + require(validate_offset_bits(nMaxReadBits)) + var bitsRead: Int = 0 + + val tmpBitStreamLength = if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1 + val tmpStrm: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0), tmpBitStreamLength.toLong * 8, 0, 0) + + var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do + decreases(nMaxReadBits - bitsRead) + + tmpStrm.appendBit(readBit()) + bitsRead += 1 + + if bitsRead < nMaxReadBits then + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + if (bitsRead == nMaxReadBits) && !checkBitPatternPresentResult then + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + + (tmpStrm.buf, bitsRead) + } + + // ************** Aligning functions ********* def alignToByte(): Unit = { if currentBit != 0 then diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 7ebff4584..9d05a2a59 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -603,75 +603,6 @@ trait Codec { Some(v) } - def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bitsVal: UByte): Int = { - var bit_terminated_pattern_size_in_bits = bit_terminated_pattern_size_in_bitsVal - require(bitStream.validate_offset_bits(bit_terminated_pattern_size_in_bits)) - - val tmp_currentByte: Int = bitStream.currentByte - val tmp_currentBit: Int = bitStream.currentBit - var tmp_byte: UByte = 0 - - if !bitStream.validate_offset_bits(bit_terminated_pattern_size_in_bitsVal) then - return 0 - - var i: Int = 0 - while bit_terminated_pattern_size_in_bits >= 8 do - decreases(bit_terminated_pattern_size_in_bits) - - readByte() match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - bit_terminated_pattern_size_in_bits -= 8 - if bit_terminated_pattern(i) != tmp_byte then - bitStream.currentByte = tmp_currentByte - bitStream.currentBit = tmp_currentBit - return 1 - i += 1 - - if bit_terminated_pattern_size_in_bits > 0 then - readPartialByte(bit_terminated_pattern_size_in_bits) match - case None() => return 0 - case Some(ub) => tmp_byte = ub - - tmp_byte = (tmp_byte << (8 - bit_terminated_pattern_size_in_bits)).toByte - - if bit_terminated_pattern(i) != tmp_byte then - bitStream.currentByte = tmp_currentByte - bitStream.currentBit = tmp_currentBit - return 1 - - return 2 - } - - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { - var checkBitPatternPresentResult: Int = 0 - - var bitsRead: Int = 0 - - val tmpStrm: BitStream = BitStream_Init(if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1) - - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - while (bitsRead < nMaxReadBits) && (checkBitPatternPresentResult == 1) do - decreases(nMaxReadBits - bitsRead) - readBit() match - case None() => return NoneMut() - case Some(bitVal) => - tmpStrm.appendBit(bitVal) - bitsRead += 1 - - if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if (bitsRead == nMaxReadBits) && (checkBitPatternPresentResult == 1) then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - - if checkBitPatternPresentResult != 2 then - return NoneMut() - - SomeMut((tmpStrm.buf, bitsRead)) - } - def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { appendByteArray(arr, nCount) } @@ -994,7 +925,7 @@ trait Codec { case false => () } - def appendNBitZero(nBits: Int): Unit = { + def appendNBitZero(nBits: Long): Unit = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) isValidPrecondition match @@ -1002,7 +933,7 @@ trait Codec { case false => () } - def appendNBitOne(nBits: Int): Unit = { + def appendNBitOne(nBits: Long): Unit = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) isValidPrecondition match @@ -1010,7 +941,7 @@ trait Codec { case false => () } - def appendBits(srcBuffer: Array[UByte], nBits: Int): Unit = { + def appendBits(srcBuffer: Array[UByte], nBits: Long): Unit = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) isValidPrecondition match @@ -1073,7 +1004,7 @@ trait Codec { case false => NoneMut() } - def readBits(nbits: Int): OptionMut[Array[UByte]] = { + def readBits(nbits: Long): OptionMut[Array[UByte]] = { val isValidPrecondition = bitStream.validate_offset_bits(nbits) assert(isValidPrecondition) isValidPrecondition match @@ -1096,4 +1027,42 @@ trait Codec { case true => Some(bitStream.readPartialByte(nbits)) case false => None() } + + def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Option[Boolean] = { + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + assert(isValidPrecondition) + isValidPrecondition match + case true => Some(bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits)) + case false => None() + } + + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { + val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) + assert(isValidPrecondition) + isValidPrecondition match + case true => SomeMut(bitStream.readBits_nullterminated(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) + case false => NoneMut() + } + + def alignToByte(): Unit = { + // TODO: precondition + bitStream.alignToByte() +// if currentBit != 0 then +// currentBit = 0 +// currentByte += 1 + } + + def alignToShort(): Unit = { + // TODO: precondition + bitStream.alignToShort() +// alignToByte() +// currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + } + + def alignToInt(): Unit = { + // TODO: precondition + bitStream.alignToInt() +// alignToByte() +// currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + } } From 78f3132256bd2c2eb9c65b7f08892a66be73dd6a Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 9 Nov 2023 16:07:22 +0100 Subject: [PATCH 088/174] verified readBits_nullterminated --- .../main/scala/asn1scala/asn1jvm_Bitstream.scala | 16 ++++++++++++---- .../src/main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 951b60041..3e9744dbf 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -543,6 +543,7 @@ case class BitStream( def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { + require(nBits >= 0) require(validate_offset_bits(nBits)) val tmp_currentBit = currentBit val tmp_currentByte = currentByte @@ -558,15 +559,18 @@ case class BitStream( ret } - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): (Array[UByte], Int) = { - require(validate_offset_bits(nMaxReadBits)) + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): (Array[UByte], Int) = { + require(nMaxReadBits >= 0) + require(bit_terminated_pattern_size_in_bits >= 0 && bit_terminated_pattern_size_in_bits <= bit_terminated_pattern.length.toLong*8) + require(nMaxReadBits <= Long.MaxValue - bit_terminated_pattern_size_in_bits) + require(validate_offset_bits(nMaxReadBits + bit_terminated_pattern_size_in_bits)) var bitsRead: Int = 0 - val tmpBitStreamLength = if nMaxReadBits % 8 == 0 then nMaxReadBits / 8 else nMaxReadBits / 8 + 1 + val tmpBitStreamLength = if nMaxReadBits % 8 == 0 then (nMaxReadBits / 8).toInt else (nMaxReadBits / 8).toInt + 1 val tmpStrm: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0), tmpBitStreamLength.toLong * 8, 0, 0) var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do + (while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do decreases(nMaxReadBits - bitsRead) tmpStrm.appendBit(readBit()) @@ -574,6 +578,7 @@ case class BitStream( if bitsRead < nMaxReadBits then checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + ).invariant(bitsRead <= nMaxReadBits &&& validate_offset_bits(bit_terminated_pattern_size_in_bits)) if (bitsRead == nMaxReadBits) && !checkBitPatternPresentResult then checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) @@ -584,17 +589,20 @@ case class BitStream( // ************** Aligning functions ********* def alignToByte(): Unit = { + // TODO: set remainingBits if currentBit != 0 then currentBit = 0 currentByte += 1 } def alignToShort(): Unit = { + // TODO: set remainingBits alignToByte() currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT } def alignToInt(): Unit = { + // TODO: set remainingBits alignToByte() currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 9d05a2a59..684b21756 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1036,7 +1036,7 @@ trait Codec { case false => None() } - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: UByte, nMaxReadBits: Int): OptionMut[(Array[UByte], Int)] = { + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): OptionMut[(Array[UByte], Int)] = { val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) assert(isValidPrecondition) isValidPrecondition match From 005d7911eaa6643e59adaacf83e6beb33175cafe Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 9 Nov 2023 16:21:34 +0100 Subject: [PATCH 089/174] make currentBit, currentByte, buf of BitStream private --- StgScala/test_cases_scala.stg | 4 +-- .../scala/asn1scala/asn1jvm_Bitstream.scala | 31 +++++++++---------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 10 +++++- 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 87eb017a7..c46bacc86 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -60,7 +60,7 @@ Codec_Encode(sModName, sFuncName, sVal) ::= << Codec_Decode(sModName, sFuncName, sTasName, sEnc, sAmber) ::= << // test_cases_scala.stg:62 -codec.bitStream.attachBuffer(codec.bitStream.buf) // TODO: reset curBit, curByte instead? +codec.resetBitIndex() // Decode value (codec) match case Left(_) => return Left(2) @@ -99,7 +99,7 @@ Codec_write_bitstreamToFile() ::= << // test_cases_scala.stg:99 val file = new File(filename+".dat") val bw = new FileOutputStream(file) -bw.write(codec.bitStream.buf) +bw.write(codec.getBuffer) bw.close() >> diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 3e9744dbf..97ddfcc1a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -76,10 +76,10 @@ val masksb: Array[UByte] = Array( ) case class BitStream( - var buf: Array[Byte], + private var buf: Array[Byte], private var remainingBits: Long, - var currentByte: Int = 0, // marks the currentByte that gets accessed - var currentBit: Int = 0, // marks the next bit that gets accessed + private var currentByte: Int = 0, // marks the currentByte that gets accessed + private var currentBit: Int = 0, // marks the next bit that gets accessed ) { // all BisStream instances satisfy the following: require(BitStream.invariant(remainingBits, currentBit, currentByte, buf.length)) @@ -109,9 +109,17 @@ case class BitStream( currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) + def resetBitIndex(): Unit = { + // TODO: make sure invariant is satisfied, or only checked before and after block + currentBit = 0 + currentByte = 0 + remainingBits = buf.length.toLong * 8 + } + private def increaseBitIndex(): Unit = { require(remainingBits > 0) + // TODO: make sure invariant is satisfied, or only checked before and after block if currentBit < 7 then currentBit += 1 else @@ -127,19 +135,9 @@ case class BitStream( BitStream.invariant(this) } - /** - * Set new internal buffer - * - * @param buf Byte array that should be attached to this BitStream - * - */ - @extern - def attachBuffer(buf: Array[UByte]): Unit = { - this.buf = buf // Illegal aliasing, therefore we need to workaround this with @extern... - currentByte = 0 - currentBit = 0 - remainingBits = buf.length.toLong * 8 - }.ensuring(_ => this.buf == buf && currentByte == 0 && currentBit == 0) + def getBuffer: Array[UByte] = { + buf + } /** * Return count of bytes that got already fully or partially written @@ -552,6 +550,7 @@ case class BitStream( val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) if !ret then + // TODO: make sure invariant is satisfied, or only checked before and after block currentBit = tmp_currentBit currentByte = tmp_currentByte remainingBits = tmp_remainingBits diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 684b21756..1631fcc97 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -127,7 +127,7 @@ trait Codec { readByte() match case None() => return None() case Some(ub) => - // mask the Byte-Bits, becuase negative values eg. -1 (1111 1111) + // mask the Byte-Bits, because negative values eg. -1 (1111 1111) // will be casted to an Int -1 (1111 ... 1111) v = v | (ub & 0xFF) @@ -1065,4 +1065,12 @@ trait Codec { // alignToByte() // currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT } + + def resetBitIndex(): Unit = { + bitStream.resetBitIndex() + } + + def getBuffer: Array[UByte] = { + bitStream.getBuffer + } } From dd49cbc6b5a45b043afad7ab4cc61d43bb6d178b Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Thu, 9 Nov 2023 16:36:42 +0100 Subject: [PATCH 090/174] remove getBuffer, and use readByteArray instead in ATCs --- StgScala/test_cases_scala.stg | 5 ++++- asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 4 +--- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index c46bacc86..3140c4c74 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -99,7 +99,10 @@ Codec_write_bitstreamToFile() ::= << // test_cases_scala.stg:99 val file = new File(filename+".dat") val bw = new FileOutputStream(file) -bw.write(codec.getBuffer) +codec.resetBitIndex() +codec.readByteArray(codec.getBufferLength) match + case SomeMut(arr) => bw.write(arr) + case NoneMut() => return Left(5) bw.close() >> diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 97ddfcc1a..253b74378 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -135,9 +135,7 @@ case class BitStream( BitStream.invariant(this) } - def getBuffer: Array[UByte] = { - buf - } + def getBufferLength: Int = buf.length /** * Return count of bytes that got already fully or partially written diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 1631fcc97..476b06032 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1070,7 +1070,7 @@ trait Codec { bitStream.resetBitIndex() } - def getBuffer: Array[UByte] = { - bitStream.getBuffer + def getBufferLength: Int = { + bitStream.getBufferLength } } From ae25ada42300092686a749cd1cec06adfe97b214 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 9 Nov 2023 18:23:15 +0100 Subject: [PATCH 091/174] magic number --- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index e545be4f5..6c3663c82 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -17,7 +17,7 @@ val CHAR_0000: ASCIIChar = 0 * @return ACN coded bitstream */ def initACNCodec(count: Int): ACN = { - ACN(BitStream(Array.fill(count)(0), count.toLong * 8)) + ACN(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) } case class ACN(bitStream: BitStream) extends Codec { From 6f791c00d70ee65e20c99840e66d37783c52b2b0 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 10 Nov 2023 11:10:16 +0100 Subject: [PATCH 092/174] verify function which update the bitIndex --- asn1scala/build.sbt | 2 +- asn1scala/project/build.properties | 2 +- .../scala/asn1scala/asn1jvm_Bitstream.scala | 77 ++++++++++++------- 3 files changed, 53 insertions(+), 28 deletions(-) diff --git a/asn1scala/build.sbt b/asn1scala/build.sbt index 0f8751df1..e52f7c830 100644 --- a/asn1scala/build.sbt +++ b/asn1scala/build.sbt @@ -1,6 +1,6 @@ ThisBuild / version := "0.1.0-SNAPSHOT" -ThisBuild / scalaVersion := "3.2.2" +ThisBuild / scalaVersion := "3.3.1" lazy val root = (project in file(".")) .settings( diff --git a/asn1scala/project/build.properties b/asn1scala/project/build.properties index 46e43a97e..72413de15 100644 --- a/asn1scala/project/build.properties +++ b/asn1scala/project/build.properties @@ -1 +1 @@ -sbt.version=1.8.2 +sbt.version=1.8.3 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 253b74378..b56b4266a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -37,15 +37,15 @@ import StaticChecks.* object BitStream { - @pure @inline + @pure @inline @ghost def invariant(bs: BitStream): Boolean = { - invariant(bs.remainingBits, bs.currentBit, bs.currentByte, bs.buf.length) + invariant(bs.remainingBits, bs.currentBit, bs.currentByte, bs.buf.length, bs.isBitIndexManipulationState) } - @pure @inline - def invariant(remainingBits: Long, currentBit: Int, currentByte: Int, buffLength: Int): Boolean = { - remainingBits == ((buffLength.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit)) && + @pure @inline @ghost + def invariant(remainingBits: Long, currentBit: Int, currentByte: Int, buffLength: Int, isBitIndexManipulationState: Boolean): Boolean = { + (remainingBits == ((buffLength.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit)) || isBitIndexManipulationState) && currentBit >= 0 && currentBit < NO_OF_BITS_IN_BYTE && currentByte >= 0 && ((currentByte < buffLength) | (currentBit == 0 && currentByte == buffLength)) } @@ -80,8 +80,9 @@ case class BitStream( private var remainingBits: Long, private var currentByte: Int = 0, // marks the currentByte that gets accessed private var currentBit: Int = 0, // marks the next bit that gets accessed + @ghost var isBitIndexManipulationState: Boolean = false ) { // all BisStream instances satisfy the following: - require(BitStream.invariant(remainingBits, currentBit, currentByte, buf.length)) + require(BitStream.invariant(remainingBits, currentBit, currentByte, buf.length, isBitIndexManipulationState)) @ghost def validate_offset_bit(): Boolean = { @@ -105,28 +106,34 @@ case class BitStream( bytes <= remainingBits / NO_OF_BITS_IN_BYTE }.ensuring(_ => BitStream.invariant(this)) + private inline def updateBitIndex(inline body: => Unit): Unit = + require(!isBitIndexManipulationState) + isBitIndexManipulationState = true + body + isBitIndexManipulationState = false + def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) def resetBitIndex(): Unit = { - // TODO: make sure invariant is satisfied, or only checked before and after block - currentBit = 0 - currentByte = 0 - remainingBits = buf.length.toLong * 8 + require(!isBitIndexManipulationState) + updateBitIndex: + currentBit = 0 + currentByte = 0 + remainingBits = buf.length.toLong * 8 } private def increaseBitIndex(): Unit = { + require(!isBitIndexManipulationState) require(remainingBits > 0) - - // TODO: make sure invariant is satisfied, or only checked before and after block - if currentBit < 7 then - currentBit += 1 - else - currentBit = 0 - currentByte += 1 - - remainingBits -= 1 + updateBitIndex: + if currentBit < 7 then + currentBit += 1 + else + currentBit = 0 + currentByte += 1 + remainingBits -= 1 }.ensuring {_ => val oldBitStrm = old(this) @@ -586,21 +593,39 @@ case class BitStream( // ************** Aligning functions ********* def alignToByte(): Unit = { - // TODO: set remainingBits + require(!isBitIndexManipulationState) if currentBit != 0 then - currentBit = 0 - currentByte += 1 + updateBitIndex: + val bitIndexIncrease = 8 - currentBit % 8 + currentBit = 0 + currentByte += 1 + remainingBits -= bitIndexIncrease } + def alignToShort(): Unit = { - // TODO: set remainingBits + require(!isBitIndexManipulationState) + require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT) + (currentBit+7)/8)) + alignToByte() - currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT + + if (currentByte % NO_OF_BYTES_IN_JVM_SHORT) != 0 then + updateBitIndex: + val byteIndexIncrease = NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT + currentByte += byteIndexIncrease + remainingBits -= byteIndexIncrease * 8 } def alignToInt(): Unit = { - // TODO: set remainingBits + require(!isBitIndexManipulationState) + require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT) + (currentBit+7)/8)) + alignToByte() - currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT + + if (currentByte % NO_OF_BYTES_IN_JVM_INT) != 0 then + updateBitIndex: + val byteIndexIncrease = NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT + currentByte += byteIndexIncrease + remainingBits -= byteIndexIncrease*8 } } // BitStream class From 14cd794b45b7b0472d079a7fce14197bc4a26e0e Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 10 Nov 2023 13:45:09 +0100 Subject: [PATCH 093/174] replaced remainingBits with func, invariant holds now --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 94 ++++++++----------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_PER.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 2 +- 5 files changed, 43 insertions(+), 59 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index b56b4266a..6320654bb 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -39,13 +39,11 @@ object BitStream { @pure @inline @ghost def invariant(bs: BitStream): Boolean = { - invariant(bs.remainingBits, bs.currentBit, bs.currentByte, bs.buf.length, bs.isBitIndexManipulationState) + invariant(bs.currentBit, bs.currentByte, bs.buf.length) } - @pure @inline @ghost - def invariant(remainingBits: Long, currentBit: Int, currentByte: Int, buffLength: Int, isBitIndexManipulationState: Boolean): Boolean = { - (remainingBits == ((buffLength.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit)) || isBitIndexManipulationState) && + def invariant(currentBit: Int, currentByte: Int, buffLength: Int): Boolean = { currentBit >= 0 && currentBit < NO_OF_BITS_IN_BYTE && currentByte >= 0 && ((currentByte < buffLength) | (currentBit == 0 && currentByte == buffLength)) } @@ -77,12 +75,14 @@ val masksb: Array[UByte] = Array( case class BitStream( private var buf: Array[Byte], - private var remainingBits: Long, private var currentByte: Int = 0, // marks the currentByte that gets accessed private var currentBit: Int = 0, // marks the next bit that gets accessed - @ghost var isBitIndexManipulationState: Boolean = false ) { // all BisStream instances satisfy the following: - require(BitStream.invariant(remainingBits, currentBit, currentByte, buf.length, isBitIndexManipulationState)) + require(BitStream.invariant(currentBit, currentByte, buf.length)) + + private def remainingBits: Long = { + (buf.length.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit) + } @ghost def validate_offset_bit(): Boolean = { @@ -106,34 +106,29 @@ case class BitStream( bytes <= remainingBits / NO_OF_BITS_IN_BYTE }.ensuring(_ => BitStream.invariant(this)) - private inline def updateBitIndex(inline body: => Unit): Unit = - require(!isBitIndexManipulationState) - isBitIndexManipulationState = true - body - isBitIndexManipulationState = false +// private inline def updateBitIndex(inline body: => Unit): Unit = +// require(!isBitIndexManipulationState) +// isBitIndexManipulationState = true +// body +// isBitIndexManipulationState = false def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) def resetBitIndex(): Unit = { - require(!isBitIndexManipulationState) - updateBitIndex: +// updateBitIndex: currentBit = 0 currentByte = 0 - remainingBits = buf.length.toLong * 8 } private def increaseBitIndex(): Unit = { - require(!isBitIndexManipulationState) require(remainingBits > 0) - updateBitIndex: - if currentBit < 7 then - currentBit += 1 - else - currentBit = 0 - currentByte += 1 - remainingBits -= 1 + if currentBit < 7 then + currentBit += 1 + else + currentBit = 0 + currentByte += 1 }.ensuring {_ => val oldBitStrm = old(this) @@ -212,7 +207,7 @@ case class BitStream( require(nBits >= 0) require(validate_offset_bits(nBits)) - var i = 0 + var i = 0L (while i < nBits do decreases(nBits - i) @@ -241,7 +236,7 @@ case class BitStream( require(nBits >= 0) require(validate_offset_bits(nBits)) - var i = 0 + var i = 0L (while i < nBits do decreases(nBits - i) @@ -283,17 +278,17 @@ case class BitStream( * */ def appendBits(srcBuffer: Array[UByte], nBits: Long): Unit = { - require(nBits >= 0 && nBits / 8 < srcBuffer.length) + require(nBits >= 0 && (nBits / 8) < srcBuffer.length) require(validate_offset_bits(nBits)) - var i = 0 - (while(i < nBits) do + var i = 0L + (while i < nBits do decreases(nBits - i) - appendBitFromByte(srcBuffer(i / NO_OF_BITS_IN_BYTE), i % NO_OF_BITS_IN_BYTE) + appendBitFromByte(srcBuffer((i / NO_OF_BITS_IN_BYTE).toInt), (i % NO_OF_BITS_IN_BYTE).toInt) - i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) + i += 1L + ).invariant(i >= 0 &&& i <= nBits &&& i / NO_OF_BITS_IN_BYTE <= Int.MaxValue &&& validate_offset_bits(nBits - i)) }.ensuring(_ => BitStream.invariant(this)) // ****************** Append Byte Functions ********************** @@ -448,15 +443,16 @@ case class BitStream( val arr: Array[UByte] = Array.fill(((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt)(0) - var i = 0 + var i = 0L (while i < nBits do decreases(nBits - i) - arr(i / NO_OF_BITS_IN_BYTE) |||= (if readBit() then BitAccessMasks(i % NO_OF_BITS_IN_BYTE) else 0) + arr((i / NO_OF_BITS_IN_BYTE).toInt) |||= (if readBit() then BitAccessMasks((i % NO_OF_BITS_IN_BYTE).toInt) else 0) i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i) && - arr.length == ((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) // TODO stainless counter examples with wrong array sizes otherwise + ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i) &&& + (i / NO_OF_BITS_IN_BYTE) <= Int.MaxValue &&& + arr.length == ((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) arr }.ensuring(_ => BitStream.invariant(this)) @@ -550,7 +546,6 @@ case class BitStream( require(validate_offset_bits(nBits)) val tmp_currentBit = currentBit val tmp_currentByte = currentByte - val tmp_remainingBits = remainingBits val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) @@ -558,7 +553,6 @@ case class BitStream( // TODO: make sure invariant is satisfied, or only checked before and after block currentBit = tmp_currentBit currentByte = tmp_currentByte - remainingBits = tmp_remainingBits ret } @@ -571,7 +565,7 @@ case class BitStream( var bitsRead: Int = 0 val tmpBitStreamLength = if nMaxReadBits % 8 == 0 then (nMaxReadBits / 8).toInt else (nMaxReadBits / 8).toInt + 1 - val tmpStrm: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0), tmpBitStreamLength.toLong * 8, 0, 0) + val tmpStrm: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) (while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do @@ -593,39 +587,29 @@ case class BitStream( // ************** Aligning functions ********* def alignToByte(): Unit = { - require(!isBitIndexManipulationState) if currentBit != 0 then - updateBitIndex: - val bitIndexIncrease = 8 - currentBit % 8 - currentBit = 0 - currentByte += 1 - remainingBits -= bitIndexIncrease + val bitIndexIncrease = 8 - currentBit % 8 + currentBit = 0 + currentByte += 1 } - def alignToShort(): Unit = { - require(!isBitIndexManipulationState) require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT) + (currentBit+7)/8)) alignToByte() if (currentByte % NO_OF_BYTES_IN_JVM_SHORT) != 0 then - updateBitIndex: - val byteIndexIncrease = NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT - currentByte += byteIndexIncrease - remainingBits -= byteIndexIncrease * 8 + val byteIndexIncrease = NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT + currentByte += byteIndexIncrease } def alignToInt(): Unit = { - require(!isBitIndexManipulationState) require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT) + (currentBit+7)/8)) alignToByte() if (currentByte % NO_OF_BYTES_IN_JVM_INT) != 0 then - updateBitIndex: - val byteIndexIncrease = NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT - currentByte += byteIndexIncrease - remainingBits -= byteIndexIncrease*8 + val byteIndexIncrease = NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT + currentByte += byteIndexIncrease } } // BitStream class diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 476b06032..b660d63e6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -48,7 +48,7 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { // TODO remove def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0), count.toLong * 8, 0, 0) + BitStream(Array.fill(count)(0)) } /** diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 6c3663c82..5a1c13f66 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -17,7 +17,7 @@ val CHAR_0000: ASCIIChar = 0 * @return ACN coded bitstream */ def initACNCodec(count: Int): ACN = { - ACN(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) + ACN(BitStream(Array.fill(count)(0))) } case class ACN(bitStream: BitStream) extends Codec { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala index 30745debd..8a497030c 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_PER.scala @@ -7,7 +7,7 @@ package asn1scala * @return PER coded bitstream */ def initPERCodec(count: Int): PER = { - PER(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) + PER(BitStream(Array.fill(count)(0))) } case class PER(bitStream: BitStream) extends Codec { } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 3267eaa94..27158413a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -9,7 +9,7 @@ import stainless.lang.{None => None, Option => Option, Some => Some, _} * @return UPER coded bitstream */ def initUPERCodec(count: Int): UPER = { - UPER(BitStream(Array.fill(count)(0), count.toLong * NO_OF_BITS_IN_BYTE)) + UPER(BitStream(Array.fill(count)(0))) } case class UPER(bitStream: BitStream) extends Codec { From 333feace8e504962f5d216d12917a1f29fa4aa46 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 10 Nov 2023 14:03:01 +0100 Subject: [PATCH 094/174] some VC's, bit naming --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 29 +++++++++---------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 6320654bb..3c922907b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -540,7 +540,6 @@ case class BitStream( }.ensuring(_ => BitStream.invariant(this)) - def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { require(nBits >= 0) require(validate_offset_bits(nBits)) @@ -550,38 +549,38 @@ case class BitStream( val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) if !ret then - // TODO: make sure invariant is satisfied, or only checked before and after block currentBit = tmp_currentBit currentByte = tmp_currentByte ret } - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): (Array[UByte], Int) = { - require(nMaxReadBits >= 0) - require(bit_terminated_pattern_size_in_bits >= 0 && bit_terminated_pattern_size_in_bits <= bit_terminated_pattern.length.toLong*8) - require(nMaxReadBits <= Long.MaxValue - bit_terminated_pattern_size_in_bits) - require(validate_offset_bits(nMaxReadBits + bit_terminated_pattern_size_in_bits)) + def readBitsNullTerminated(bit_terminated_pattern: Array[UByte], nBits: Long, nMaxReadBits: Long): (Array[UByte], Int) = { + require(nBits >= 0 && nBits <= bit_terminated_pattern.length.toLong * NO_OF_BITS_IN_BYTE) + require(nMaxReadBits >= 0 &&& (nMaxReadBits / NO_OF_BITS_IN_BYTE) <= Int.MaxValue) + require(validate_offset_bits(nMaxReadBits + nBits)) + var bitsRead: Int = 0 - val tmpBitStreamLength = if nMaxReadBits % 8 == 0 then (nMaxReadBits / 8).toInt else (nMaxReadBits / 8).toInt + 1 - val tmpStrm: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) + // round to next full byte + val tmpBitStreamLength = ((nMaxReadBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt + val tmpStr: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) - var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) (while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do decreases(nMaxReadBits - bitsRead) - tmpStrm.appendBit(readBit()) + tmpStr.appendBit(readBit()) bitsRead += 1 if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) - ).invariant(bitsRead <= nMaxReadBits &&& validate_offset_bits(bit_terminated_pattern_size_in_bits)) + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) + ).invariant(bitsRead <= nMaxReadBits &&& validate_offset_bits(nBits)) if (bitsRead == nMaxReadBits) && !checkBitPatternPresentResult then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, bit_terminated_pattern_size_in_bits) + checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) - (tmpStrm.buf, bitsRead) + (tmpStr.buf, bitsRead) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index b660d63e6..811a3ddc1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1040,7 +1040,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) assert(isValidPrecondition) isValidPrecondition match - case true => SomeMut(bitStream.readBits_nullterminated(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) + case true => SomeMut(bitStream.readBitsNullTerminated(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) case false => NoneMut() } From 024fc3f4679dd6aa8db1e5a9195e6b81765edab2 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 10 Nov 2023 14:43:08 +0100 Subject: [PATCH 095/174] checkBitPatternPresent done --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 25 +++++++------------ 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 3c922907b..cbf842cb1 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -106,20 +106,13 @@ case class BitStream( bytes <= remainingBits / NO_OF_BITS_IN_BYTE }.ensuring(_ => BitStream.invariant(this)) -// private inline def updateBitIndex(inline body: => Unit): Unit = -// require(!isBitIndexManipulationState) -// isBitIndexManipulationState = true -// body -// isBitIndexManipulationState = false - def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) def resetBitIndex(): Unit = { -// updateBitIndex: - currentBit = 0 - currentByte = 0 + currentBit = 0 + currentByte = 0 } private def increaseBitIndex(): Unit = { @@ -131,9 +124,9 @@ case class BitStream( currentByte += 1 }.ensuring {_ => - val oldBitStrm = old(this) - oldBitStrm.bitIndex() + 1 == this.bitIndex() &&& - oldBitStrm.remainingBits - remainingBits == 1 &&& + val oldBitStr = old(this) + oldBitStr.bitIndex() + 1 == this.bitIndex() &&& + oldBitStr.remainingBits - remainingBits == 1 &&& BitStream.invariant(this) } @@ -543,14 +536,14 @@ case class BitStream( def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { require(nBits >= 0) require(validate_offset_bits(nBits)) - val tmp_currentBit = currentBit - val tmp_currentByte = currentByte + val tmpByte = currentByte + val tmpBit = currentBit val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) if !ret then - currentBit = tmp_currentBit - currentByte = tmp_currentByte + currentByte = tmpByte + currentBit = tmpBit ret } From 19571e5af575eb0d45feade45ce1ea72eaf17026 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 10 Nov 2023 15:30:31 +0100 Subject: [PATCH 096/174] some changes in readBitsUntilTerminator --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 27 +++++++++---------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 5 ++-- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index cbf842cb1..d6c1a3ac8 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -548,35 +548,32 @@ case class BitStream( ret } - def readBitsNullTerminated(bit_terminated_pattern: Array[UByte], nBits: Long, nMaxReadBits: Long): (Array[UByte], Int) = { - require(nBits >= 0 && nBits <= bit_terminated_pattern.length.toLong * NO_OF_BITS_IN_BYTE) + def readBitsUntilTerminator(terminatorPattern: Array[UByte], nBitsTerminator: Long, nMaxReadBits: Long): (Array[UByte], Long) = { + require(nBitsTerminator >= 0 && nBitsTerminator <= terminatorPattern.length.toLong * NO_OF_BITS_IN_BYTE) require(nMaxReadBits >= 0 &&& (nMaxReadBits / NO_OF_BITS_IN_BYTE) <= Int.MaxValue) - require(validate_offset_bits(nMaxReadBits + nBits)) + require(validate_offset_bits(nMaxReadBits + nBitsTerminator)) - var bitsRead: Int = 0 + var checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) // round to next full byte val tmpBitStreamLength = ((nMaxReadBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt val tmpStr: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) - var checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) - (while (bitsRead < nMaxReadBits) && !checkBitPatternPresentResult do - decreases(nMaxReadBits - bitsRead) + (while (tmpStr.bitIndex() < nMaxReadBits) && !checkBitPatternPresentResult do + decreases(nMaxReadBits - tmpStr.bitIndex()) tmpStr.appendBit(readBit()) - bitsRead += 1 - if bitsRead < nMaxReadBits then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) - ).invariant(bitsRead <= nMaxReadBits &&& validate_offset_bits(nBits)) + if tmpStr.bitIndex() < nMaxReadBits then + checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) + ).invariant(tmpStr.bitIndex() <= nMaxReadBits &&& validate_offset_bits(nMaxReadBits - tmpStr.bitIndex())) - if (bitsRead == nMaxReadBits) && !checkBitPatternPresentResult then - checkBitPatternPresentResult = checkBitPatternPresent(bit_terminated_pattern, nBits) + if (tmpStr.bitIndex() == nMaxReadBits) && !checkBitPatternPresentResult then + checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) - (tmpStr.buf, bitsRead) + (tmpStr.buf, tmpStr.bitIndex()) } - // ************** Aligning functions ********* def alignToByte(): Unit = { if currentBit != 0 then diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 811a3ddc1..170e18b28 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1036,11 +1036,12 @@ trait Codec { case false => None() } - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): OptionMut[(Array[UByte], Int)] = { + // TODO rename to bitstream call + def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): OptionMut[(Array[UByte], Long)] = { val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) assert(isValidPrecondition) isValidPrecondition match - case true => SomeMut(bitStream.readBitsNullTerminated(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) + case true => SomeMut(bitStream.readBitsUntilTerminator(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) case false => NoneMut() } From 386bc16583f7d8d4c3ef6031d24a68f12939a8b4 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 10 Nov 2023 16:42:30 +0100 Subject: [PATCH 097/174] translated missing code for BitString and IA5String --- StgScala/acn_scala.stg | 16 ++++++++-------- StgScala/init_scala.stg | 2 +- StgScala/isvalid_scala.stg | 17 ++++++++--------- StgScala/uper_scala.stg | 2 +- 4 files changed, 18 insertions(+), 19 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index db07bfa96..e25bc55bc 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -455,13 +455,13 @@ codec.dec_String_Ascii_FixSize() match >> Acn_String_Ascii_Null_Teminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -codec.enc_String_Ascii_Null_Teminated_mult(, (byte[]){}, ,

) +codec.enc_String_Ascii_Null_Teminated_mult(, Array({}), ,

) >> Acn_String_Ascii_Null_Teminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -codec.dec_String_Ascii_Null_Teminated_mult(, (byte[]){}, ) match - case None() => return Left() - case Some(x) =>

= x +codec.dec_String_Ascii_Null_Teminated_mult(, Array({}), ) match + case NoneMut() => return Left() + case SomeMut(x) =>

= x >> Acn_String_Ascii_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld) ::= "codec.enc_String_Ascii_External_Field_Determinant(,

)" @@ -482,7 +482,7 @@ codec.dec_String_Ascii_Internal_Field_Determinant(, ) match >> PrintAlphabet2(arrnCharSet) /*nogen*/ ::= << -static byte allowedCharSet[] = {}; wrap, anchor, separator=",">} +val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">) >> Acn_String_CharIndex_FixSize_encode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << @@ -623,7 +623,7 @@ if (\<=) && (\<=) t >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -codec.appendBits(

arr,

nCount) +codec.appendBits(

arr,

arr.length*8) // TODO: re-introduce nCount? -> codec.appendBits(

arr,

nCount) codec.appendBits(Array({}), ) >> @@ -631,8 +631,8 @@ bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arr codec.readBits_nullterminated(Array({}), , ) match case NoneMut() => return Left() - case SomeMut(x) => -

arr = x + case SomeMut(arr, i) => +

arr = arr >> RefTypeParam_tmpVar(sName, sTypeDecl) ::= " " diff --git a/StgScala/init_scala.stg b/StgScala/init_scala.stg index d8a9d47c9..a3f22b77d 100644 --- a/StgScala/init_scala.stg +++ b/StgScala/init_scala.stg @@ -91,7 +91,7 @@ initTestCaseIA5String(p, sAcc, nSize, nMaxSizePlusOne, i, td/*:FE_StringTypeDefi

= Array.fill(){0} while ( \< ) { - static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; + val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">)

() = allowedCharSet( % ) diff --git a/StgScala/isvalid_scala.stg b/StgScala/isvalid_scala.stg index ce75530e1..d264428c7 100644 --- a/StgScala/isvalid_scala.stg +++ b/StgScala/isvalid_scala.stg @@ -188,16 +188,15 @@ while(ret.isRight && \<

nCount Print_AlphabetCheckFunc(sFuncName, arrsAlphaConBody) ::= << -def (const char* str): flag = +def (str: Array[Byte]): Boolean = { - flag ret=TRUE; - int i=0; - - while ((str[i] != '\0') && ret) { - ret = ret && (); - i = i + 1; + var valid: Boolean = true + var i: Int = 0 + while ((str(i) != CHAR_0000) && valid) { + valid = valid && (); + i = i + 1 } - return ret; + valid } >> @@ -209,7 +208,7 @@ SingleValContraint(p, v) ::= "(

== )" -stringContainsChar(sStrVal, p) ::= "strchr(,

)" +stringContainsChar(sStrVal, p) ::= ".contains(

)" RangeContraint(p, v1, v2, bMin, bMax) ::= "( \<=

&&

\<= )" diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index c5d8b254a..5e1b42fd5 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -84,7 +84,7 @@ if !codec.readByte(

arr()) then >> PrintAlphabet2(arrnCharSet) /*nogen*/::= << -static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; +val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">) >> InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< From da5ca2ea7b60fddc2cea0c3715deb0848e5190fe Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 10 Nov 2023 16:42:36 +0100 Subject: [PATCH 098/174] fix in dec_String_Ascii_Null_Teminated_mult --- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 5a1c13f66..465cfa23b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -954,8 +954,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): OptionMut[Array[ASCIIChar]] = { - val sz: Int = if null_character_size < 10 then null_character_size else 10 - val tmp: Array[Byte] = Array.fill(10)(0) + val tmp: Array[Byte] = Array.fill(null_character_size)(0) val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) //read null_character_size characters into the tmp buffer var j: Int = 0 From 35b8726b3c6f7f69b7720e0064703ad2939de96b Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 10 Nov 2023 16:43:11 +0100 Subject: [PATCH 099/174] additional test cases --- PUSCScalaTest/AcnInterop.cs | 37 ++++++++++--------- PUSCScalaTest/Testframework.cs | 8 +++- PUSCScalaTest/UperInterop.cs | 3 ++ .../additional-test-cases/NULLTERMINATED.acn | 7 ++++ .../additional-test-cases/NULLTERMINATED.asn1 | 7 ++++ 5 files changed, 44 insertions(+), 18 deletions(-) create mode 100644 PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.acn create mode 100644 PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.asn1 diff --git a/PUSCScalaTest/AcnInterop.cs b/PUSCScalaTest/AcnInterop.cs index cc5f99851..4cd5ad09a 100644 --- a/PUSCScalaTest/AcnInterop.cs +++ b/PUSCScalaTest/AcnInterop.cs @@ -3,56 +3,59 @@ [TestClass] public class AcnInterop { - private void UPERInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => + private void ACNInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => new TestBasics().Run_TestService(s, folderSuffix, ServiceVariation.CREATE_SCALA | ServiceVariation.CREATE_C | ServiceVariation.ACN | ServiceVariation.CREATE_TESTS | ServiceVariation.COMPARE_ENCODINGS); [TestMethod] - public void TestService_01() => UPERInteropEncScalaDecC(PUS_C_Service.S1, "S1"); + public void TestService_01() => ACNInteropEncScalaDecC(PUS_C_Service.S1, "S1"); [TestMethod] - public void TestService_02() => UPERInteropEncScalaDecC(PUS_C_Service.S2, "S2"); + public void TestService_02() => ACNInteropEncScalaDecC(PUS_C_Service.S2, "S2"); [TestMethod] - public void TestService_03() => UPERInteropEncScalaDecC(PUS_C_Service.S3, "S3"); + public void TestService_03() => ACNInteropEncScalaDecC(PUS_C_Service.S3, "S3"); [TestMethod] - public void TestService_04() => UPERInteropEncScalaDecC(PUS_C_Service.S4, "S4"); + public void TestService_04() => ACNInteropEncScalaDecC(PUS_C_Service.S4, "S4"); [TestMethod] - public void TestService_05() => UPERInteropEncScalaDecC(PUS_C_Service.S5, "S5"); + public void TestService_05() => ACNInteropEncScalaDecC(PUS_C_Service.S5, "S5"); [TestMethod] - public void TestService_06() => UPERInteropEncScalaDecC(PUS_C_Service.S6, "S6"); + public void TestService_06() => ACNInteropEncScalaDecC(PUS_C_Service.S6, "S6"); [TestMethod] - public void TestService_08() => UPERInteropEncScalaDecC(PUS_C_Service.S8, "S8"); + public void TestService_08() => ACNInteropEncScalaDecC(PUS_C_Service.S8, "S8"); [TestMethod] - public void TestService_09() => UPERInteropEncScalaDecC(PUS_C_Service.S9, "S9"); + public void TestService_09() => ACNInteropEncScalaDecC(PUS_C_Service.S9, "S9"); [TestMethod] - public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); + public void TestService_11() => ACNInteropEncScalaDecC(PUS_C_Service.S11, "S11"); //[TestMethod] - //public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); + //public void TestService_12() => ACNInteropEncScalaDecC(PUS_C_Service.S12, "S12"); [TestMethod] - public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); + public void TestService_13() => ACNInteropEncScalaDecC(PUS_C_Service.S13, "S13"); //[TestMethod] - //public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); + //public void TestService_14() => ACNInteropEncScalaDecC(PUS_C_Service.S14, "S14"); [TestMethod] - public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); + public void TestService_15() => ACNInteropEncScalaDecC(PUS_C_Service.S15, "S15"); [TestMethod] - public void TestService_17() => UPERInteropEncScalaDecC(PUS_C_Service.S17, "S17"); + public void TestService_17() => ACNInteropEncScalaDecC(PUS_C_Service.S17, "S17"); [TestMethod] - public void TestService_18() => UPERInteropEncScalaDecC(PUS_C_Service.S18, "S18"); + public void TestService_18() => ACNInteropEncScalaDecC(PUS_C_Service.S18, "S18"); [TestMethod] - public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); + public void TestService_19() => ACNInteropEncScalaDecC(PUS_C_Service.S19, "S19"); + + [TestMethod] + public void AdditionalTestCases() => ACNInteropEncScalaDecC(PUS_C_Service.ADDITIONAL_TEST_CASES, "AdditionalTestCases"); } } diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index 212a81277..4c9aec0a8 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -18,7 +18,7 @@ public enum PUS_C_Service S5, S6, S8, S9, S11, S12, S13, S14, S15, S17, - S18, S19 + S18, S19, ADDITIONAL_TEST_CASES } [Flags] @@ -234,6 +234,7 @@ Func GetServiceFiles(PUS_C_Service service) => PUS_C_Service.S17 => GetService17FileNames, PUS_C_Service.S18 => GetService18FileNames, PUS_C_Service.S19 => GetService19FileNames, + PUS_C_Service.ADDITIONAL_TEST_CASES => GetAdditionalTestCasesFileNames, _ => throw new InvalidOperationException("what?") }; @@ -822,5 +823,10 @@ private string[] GetService19FileNames() => "service-19/PUS-19-8", "service-19/PUS-19-9" }; + + private string[] GetAdditionalTestCasesFileNames() => + new string[]{ + "additional-test-cases/NULLTERMINATED", + }; } } diff --git a/PUSCScalaTest/UperInterop.cs b/PUSCScalaTest/UperInterop.cs index 702bd3ac7..603c40b8b 100644 --- a/PUSCScalaTest/UperInterop.cs +++ b/PUSCScalaTest/UperInterop.cs @@ -56,5 +56,8 @@ private void UPERInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => [TestMethod] public void TestService_19() => UPERInteropEncScalaDecC(PUS_C_Service.S19, "S19"); + + [TestMethod] + public void AdditionalTestCases() => UPERInteropEncScalaDecC(PUS_C_Service.ADDITIONAL_TEST_CASES, "AdditionalTestCases"); } } diff --git a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.acn b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.acn new file mode 100644 index 000000000..2d09014a6 --- /dev/null +++ b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.acn @@ -0,0 +1,7 @@ + +NULLTERMINATED DEFINITIONS ::= BEGIN + +MyPDU [encoding ASCII, size null-terminated, termination-pattern '01'H] -- ASCII encoding with termination pattern +MyPDU2 [encoding ASCII, size null-terminated, termination-pattern '0'H] -- ASCII encoding with termination pattern + +END diff --git a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.asn1 b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.asn1 new file mode 100644 index 000000000..f31463b1c --- /dev/null +++ b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/additional-test-cases/NULLTERMINATED.asn1 @@ -0,0 +1,7 @@ + +NULLTERMINATED DEFINITIONS AUTOMATIC TAGS ::= BEGIN + +MyPDU ::= IA5String (SIZE (20)) (FROM("A".."Z" | "a".."z" | " ")) +MyPDU2 ::= BIT STRING (SIZE (20)) + +END From 3e9ed018d0f822ff7c923d7c87809af70ce26da8 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 10 Nov 2023 17:00:06 +0100 Subject: [PATCH 100/174] translated missing code for BitString and IA5String for UPER --- StgScala/uper_scala.stg | 14 ++++++++------ .../src/main/scala/asn1scala/asn1jvm_Codec.scala | 6 ++++++ .../main/scala/asn1scala/asn1jvm_Codec_ACN.scala | 6 ------ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 5e1b42fd5..a448f0ce7 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -89,16 +89,18 @@ val allowedCharSet: Array[Byte] = Array(}; wr InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< -int charIndex = GetCharIndex(

[], allowedCharSet, ); +val charIndex: Int = GetCharIndex(

(), allowedCharSet) codec.encodeConstraintWholeNumber(charIndex, 0, ) >> InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< -asn1SccSint charIndex = 0; -val worked = codec.decodeConstraintWholeNumber(&charIndex, 0, ) -if !worked then - ret = -

[] = if (worked) then allowedCharSet[charIndex] else '\0' + +codec.decodeConstraintWholeNumber(0, ) match + case Some(charIndex) => +

() = allowedCharSet(charIndex.toInt) + case None() => +

() = CHAR_0000 + return Left() >> InternalItem_string_no_alpha_encode(p, sErrCode, i) ::=<< diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 170e18b28..14cdf2409 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -16,6 +16,12 @@ val masks2: Array[UInt] = Array( 0xFF000000, // -16777216 / 1111 1111 0000 0000 0000 0000 0000 0000 / 0xFF00 0000 ) +val CHAR_MINUS: ASCIIChar = 45 +val CHAR_PLUS: ASCIIChar = 43 +val CHAR_ZERO: ASCIIChar = 48 +val CHAR_NINE: ASCIIChar = 57 +val CHAR_0000: ASCIIChar = 0 + /***********************************************************************************************/ /** Byte Stream Functions **/ diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 465cfa23b..f6c58cd86 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -5,12 +5,6 @@ import stainless.lang.{None, Option, Some} val FAILED_READ_ERR_CODE = 5400 -val CHAR_MINUS: ASCIIChar = 45 -val CHAR_PLUS: ASCIIChar = 43 -val CHAR_ZERO: ASCIIChar = 48 -val CHAR_NINE: ASCIIChar = 57 -val CHAR_0000: ASCIIChar = 0 - /** * Get an instance of a ACN coded bitstream * @param count of elements in underlaying buffer From 21052edb2a6752ef38e9281e207785ade88f9a01 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 13 Nov 2023 08:44:01 +0100 Subject: [PATCH 101/174] enabled Tests for ACN/UPER Service 14 and UPER Service 12 (work for C now) --- PUSCScalaTest/AcnAtcCTests.cs | 5 +++-- PUSCScalaTest/AcnInterop.cs | 5 +++-- PUSCScalaTest/UperAtcCTests.cs | 10 ++++------ PUSCScalaTest/UperInterop.cs | 10 ++++------ 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/PUSCScalaTest/AcnAtcCTests.cs b/PUSCScalaTest/AcnAtcCTests.cs index 45c8d932a..ddabd59e3 100644 --- a/PUSCScalaTest/AcnAtcCTests.cs +++ b/PUSCScalaTest/AcnAtcCTests.cs @@ -34,14 +34,15 @@ private void ACNWithTestGenCall(PUS_C_Service s, string folderSuffix) => [TestMethod] public void TestService_11() => ACNWithTestGenCall(PUS_C_Service.S11, "S11"); + // TODO: not working //[TestMethod] //public void TestService_12() => ACNWithTestGenCall(PUS_C_Service.S12, "S12"); [TestMethod] public void TestService_13() => ACNWithTestGenCall(PUS_C_Service.S13, "S13"); - //[TestMethod] - //public void TestService_14() => ACNWithTestGenCall(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_14() => ACNWithTestGenCall(PUS_C_Service.S14, "S14"); [TestMethod] public void TestService_15() => ACNWithTestGenCall(PUS_C_Service.S15, "S15"); diff --git a/PUSCScalaTest/AcnInterop.cs b/PUSCScalaTest/AcnInterop.cs index 4cd5ad09a..2f1876981 100644 --- a/PUSCScalaTest/AcnInterop.cs +++ b/PUSCScalaTest/AcnInterop.cs @@ -34,14 +34,15 @@ private void ACNInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => [TestMethod] public void TestService_11() => ACNInteropEncScalaDecC(PUS_C_Service.S11, "S11"); + // TODO: not working for C and Scala //[TestMethod] //public void TestService_12() => ACNInteropEncScalaDecC(PUS_C_Service.S12, "S12"); [TestMethod] public void TestService_13() => ACNInteropEncScalaDecC(PUS_C_Service.S13, "S13"); - //[TestMethod] - //public void TestService_14() => ACNInteropEncScalaDecC(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_14() => ACNInteropEncScalaDecC(PUS_C_Service.S14, "S14"); [TestMethod] public void TestService_15() => ACNInteropEncScalaDecC(PUS_C_Service.S15, "S15"); diff --git a/PUSCScalaTest/UperAtcCTests.cs b/PUSCScalaTest/UperAtcCTests.cs index 1b8217d2f..ae0a309e9 100644 --- a/PUSCScalaTest/UperAtcCTests.cs +++ b/PUSCScalaTest/UperAtcCTests.cs @@ -34,16 +34,14 @@ private void UPERWithTestGenTestCall(PUS_C_Service s, string folderSuffix) => [TestMethod] public void TestService_11() => UPERWithTestGenTestCall(PUS_C_Service.S11, "S11"); - // C part needs fixing - //[TestMethod] - //public void TestService_12() => UPERWithTestGenTestCall(PUS_C_Service.S12, "S12"); + [TestMethod] + public void TestService_12() => UPERWithTestGenTestCall(PUS_C_Service.S12, "S12"); [TestMethod] public void TestService_13() => UPERWithTestGenTestCall(PUS_C_Service.S13, "S13"); - // C part needs fixing - //[TestMethod] - //public void TestService_14() => UPERWithTestGenTestCall(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_14() => UPERWithTestGenTestCall(PUS_C_Service.S14, "S14"); [TestMethod] public void TestService_15() => UPERWithTestGenTestCall(PUS_C_Service.S15, "S15"); diff --git a/PUSCScalaTest/UperInterop.cs b/PUSCScalaTest/UperInterop.cs index 603c40b8b..e90ceaf83 100644 --- a/PUSCScalaTest/UperInterop.cs +++ b/PUSCScalaTest/UperInterop.cs @@ -34,16 +34,14 @@ private void UPERInteropEncScalaDecC(PUS_C_Service s, string folderSuffix) => [TestMethod] public void TestService_11() => UPERInteropEncScalaDecC(PUS_C_Service.S11, "S11"); - // does not work in C - interop makes no sense - //[TestMethod] - //public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); + [TestMethod] + public void TestService_12() => UPERInteropEncScalaDecC(PUS_C_Service.S12, "S12"); [TestMethod] public void TestService_13() => UPERInteropEncScalaDecC(PUS_C_Service.S13, "S13"); - // does not work in C - interop makes no sense - //[TestMethod] - //public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); + [TestMethod] + public void TestService_14() => UPERInteropEncScalaDecC(PUS_C_Service.S14, "S14"); [TestMethod] public void TestService_15() => UPERInteropEncScalaDecC(PUS_C_Service.S15, "S15"); From 8877f712145434c1a657d82a0ee77ffab58d6d12 Mon Sep 17 00:00:00 2001 From: Mario Bucev Date: Fri, 10 Nov 2023 11:49:44 +0100 Subject: [PATCH 102/174] Address some invalid VCs --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 148 +++++++++++++----- 1 file changed, 105 insertions(+), 43 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index d6c1a3ac8..cee53167d 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -42,7 +42,7 @@ object BitStream { invariant(bs.currentBit, bs.currentByte, bs.buf.length) } - @pure @inline @ghost + @pure @ghost def invariant(currentBit: Int, currentByte: Int, buffLength: Int): Boolean = { currentBit >= 0 && currentBit < NO_OF_BITS_IN_BYTE && currentByte >= 0 && ((currentByte < buffLength) | (currentBit == 0 && currentByte == buffLength)) @@ -127,7 +127,7 @@ case class BitStream( val oldBitStr = old(this) oldBitStr.bitIndex() + 1 == this.bitIndex() &&& oldBitStr.remainingBits - remainingBits == 1 &&& - BitStream.invariant(this) + oldBitStr.buf.length == buf.length } def getBufferLength: Int = buf.length @@ -179,7 +179,7 @@ case class BitStream( buf(currentByte) = (buf(currentByte) & (~BitAccessMasks(currentBit))).toByte increaseBitIndex() - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - 1) // NOTE: needs cvc5 for solving /** * Append a set bit @@ -188,7 +188,7 @@ case class BitStream( require(validate_offset_bit()) appendBit(true) - } + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - 1) /** * Append n set bits to bitstream @@ -200,15 +200,20 @@ case class BitStream( require(nBits >= 0) require(validate_offset_bits(nBits)) + @ghost val oldThis = snapshot(this) var i = 0L (while i < nBits do decreases(nBits - i) - appendBitOne() - i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) - }.ensuring(_ => BitStream.invariant(this)) + ).invariant( + 0 <= i && i <= nBits && + nBits <= Int.MaxValue.toLong * NO_OF_BITS_IN_BYTE.toLong && + buf.length == oldThis.buf.length && + remainingBits == oldThis.remainingBits - i && + validate_offset_bits(nBits - i)) + + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - nBits) /** * Append cleared bit to bitstream @@ -217,7 +222,7 @@ case class BitStream( require(validate_offset_bit()) appendBit(false) - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - 1) /** * Append n cleared bit to bitstream @@ -229,16 +234,20 @@ case class BitStream( require(nBits >= 0) require(validate_offset_bits(nBits)) + @ghost val oldThis = snapshot(this) var i = 0L (while i < nBits do decreases(nBits - i) - appendBitZero() - i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) + ).invariant( + 0 <= i && i <= nBits && + nBits <= Int.MaxValue.toLong * NO_OF_BITS_IN_BYTE.toLong && + buf.length == oldThis.buf.length && + remainingBits == oldThis.remainingBits - i && + validate_offset_bits(nBits - i)) - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - nBits) /** * Append bit with bitNr from b to bitstream @@ -258,7 +267,7 @@ case class BitStream( val bitPosInByte = 1 << ((NO_OF_BITS_IN_BYTE - 1) - bitNr) appendBit((b.unsignedToInt & bitPosInByte) != 0) - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - 1) /** * Append nBits from srcBuffer to bitstream @@ -274,6 +283,7 @@ case class BitStream( require(nBits >= 0 && (nBits / 8) < srcBuffer.length) require(validate_offset_bits(nBits)) + @ghost val oldThis = snapshot(this) var i = 0L (while i < nBits do decreases(nBits - i) @@ -281,8 +291,12 @@ case class BitStream( appendBitFromByte(srcBuffer((i / NO_OF_BITS_IN_BYTE).toInt), (i % NO_OF_BITS_IN_BYTE).toInt) i += 1L - ).invariant(i >= 0 &&& i <= nBits &&& i / NO_OF_BITS_IN_BYTE <= Int.MaxValue &&& validate_offset_bits(nBits - i)) - }.ensuring(_ => BitStream.invariant(this)) + ).invariant(i >= 0 &&& i <= nBits &&& i / NO_OF_BITS_IN_BYTE <= Int.MaxValue &&& + buf.length == oldThis.buf.length &&& + remainingBits == oldThis.remainingBits - i &&& + validate_offset_bits(nBits - i)) + + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - nBits) // ****************** Append Byte Functions ********************** @@ -309,15 +323,21 @@ case class BitStream( require(nBits >= 0 &&& nBits <= NO_OF_BITS_IN_BYTE) require(validate_offset_bits(nBits)) - var i = 0 + @ghost val oldThis = snapshot(this) + var i = 0L (while i < nBits do decreases(nBits - i) - appendBitFromByte(v, NO_OF_BITS_IN_BYTE - nBits + i) + appendBitFromByte(v, NO_OF_BITS_IN_BYTE - nBits + i.toInt) i += 1 - ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i)) - }.ensuring(_ => BitStream.invariant(this)) + ).invariant( + 0 <= i && i <= nBits && + nBits <= Int.MaxValue.toLong * NO_OF_BITS_IN_BYTE.toLong && + buf.length == oldThis.buf.length && + remainingBits == oldThis.remainingBits - i && + validate_offset_bits(nBits - i)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - nBits) /** * Append whole byte to bitstream @@ -344,7 +364,7 @@ case class BitStream( appendPartialByte(v, NO_OF_BITS_IN_BYTE) - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - NO_OF_BITS_IN_BYTE) /** * NBytes of the given array is added to the bitstream @@ -360,6 +380,7 @@ case class BitStream( require(0 <= noOfBytes && noOfBytes <= arr.length) require(validate_offset_bytes(noOfBytes)) + @ghost val oldThis = snapshot(this) var i: Int = 0 (while i < noOfBytes do decreases(noOfBytes - i) @@ -367,9 +388,13 @@ case class BitStream( appendByte(arr(i)) i += 1 - ).invariant(0 <= i &&& i <= noOfBytes &&& validate_offset_bytes(noOfBytes - i)) + ).invariant( + 0 <= i && i <= noOfBytes && + buf.length == oldThis.buf.length && + remainingBits == oldThis.remainingBits - i.toLong * NO_OF_BITS_IN_BYTE && + validate_offset_bytes(noOfBytes - i)) - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - noOfBytes.toLong * NO_OF_BITS_IN_BYTE) // ****************** Peak Functions ********************** @@ -383,7 +408,7 @@ case class BitStream( def peekBit(): Boolean = { require(validate_offset_bit()) ((buf(currentByte) & 0xFF) & (BitAccessMasks(currentBit) & 0xFF)) > 0 - }.ensuring(_ => BitStream.invariant(this)) + } // ****************** Read Bit Functions ********************** @@ -401,7 +426,7 @@ case class BitStream( increaseBitIndex() ret - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - 1) /** * Read multiple bits from the bitstream @@ -433,9 +458,11 @@ case class BitStream( */ def readBits(nBits: Long): Array[UByte] = { require(nBits >= 0 && validate_offset_bits(nBits)) + assert(nBits <= Int.MaxValue.toLong * NO_OF_BITS_IN_BYTE.toLong) + val arrLen = ((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt + val arr: Array[UByte] = Array.fill(arrLen)(0) - val arr: Array[UByte] = Array.fill(((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt)(0) - + @ghost val oldThis = snapshot(this) var i = 0L (while i < nBits do decreases(nBits - i) @@ -445,10 +472,12 @@ case class BitStream( i += 1 ).invariant(i >= 0 &&& i <= nBits &&& validate_offset_bits(nBits - i) &&& (i / NO_OF_BITS_IN_BYTE) <= Int.MaxValue &&& - arr.length == ((nBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt) + buf == oldThis.buf &&& + remainingBits == oldThis.remainingBits - i &&& + arr.length == arrLen) arr - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - nBits) // ****************** Read Byte Functions ********************** @@ -464,6 +493,7 @@ case class BitStream( def readByte(): UByte = { require(validate_offset_bits(8)) + @ghost val oldThis = snapshot(this) var ret = 0 var i = 0 (while i < NO_OF_BITS_IN_BYTE do @@ -471,18 +501,26 @@ case class BitStream( ret |= (if readBit() then BitAccessMasks(i) else 0) i += 1 - ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& validate_offset_bits(NO_OF_BITS_IN_BYTE - i)) + ).invariant(i >= 0 &&& i <= NO_OF_BITS_IN_BYTE &&& + buf == oldThis.buf &&& + remainingBits == oldThis.remainingBits - i &&& + validate_offset_bits(NO_OF_BITS_IN_BYTE - i)) ret.toUnsignedByte - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - NO_OF_BITS_IN_BYTE) def readByteArray(nBytes: Int): Array[UByte] = { require(nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) require(nBytes >= 0 && nBytes <= remainingBits / NO_OF_BITS_IN_BYTE) require(validate_offset_bytes(nBytes)) - readBits(nBytes * NO_OF_BITS_IN_BYTE) - }.ensuring(_ => BitStream.invariant(this)) + // @ghost val oldThis = snapshot(this) + // val nBits = (nBytes * NO_OF_BITS_IN_BYTE).toLong + val res = readBits(nBytes * NO_OF_BITS_IN_BYTE) + // assert(remainingBits == oldThis.remainingBits - nBits) + // assert(nBits == nBytes.toLong * NO_OF_BITS_IN_BYTE) + res + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - nBytes.toLong * NO_OF_BITS_IN_BYTE) /** @@ -519,6 +557,7 @@ case class BitStream( require(nBits >= 0 && nBits < NO_OF_BITS_IN_BYTE) require(validate_offset_bits(nBits)) + @ghost val oldThis = snapshot(this) var v = 0.toByte var i = 0 (while i < nBits do @@ -527,10 +566,13 @@ case class BitStream( v |||= (if readBit() then BitAccessMasks(NO_OF_BITS_IN_BYTE - nBits + i) else 0) i += 1 - ).invariant(i >= 0 && i <= nBits && validate_offset_bits(nBits - i)) + ).invariant(i >= 0 && i <= nBits && + buf == oldThis.buf && + remainingBits == oldThis.remainingBits - i && + validate_offset_bits(nBits - i)) v - }.ensuring(_ => BitStream.invariant(this)) + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - nBits) def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { @@ -540,19 +582,22 @@ case class BitStream( val tmpBit = currentBit val ret = arraySameElements(bit_terminated_pattern, readBits(nBits)) - - if !ret then - currentByte = tmpByte - currentBit = tmpBit + // TODO: The C code does indeed not reset the stream to the original position + // in case we return 0 or 1, but doesn't it make sense to do so? + // if !ret then + currentByte = tmpByte + currentBit = tmpBit ret - } + }.ensuring(_ => old(this) == this) + // NOTE: needs smt-cvc5 and a timeout of at least 50s def readBitsUntilTerminator(terminatorPattern: Array[UByte], nBitsTerminator: Long, nMaxReadBits: Long): (Array[UByte], Long) = { require(nBitsTerminator >= 0 && nBitsTerminator <= terminatorPattern.length.toLong * NO_OF_BITS_IN_BYTE) - require(nMaxReadBits >= 0 &&& (nMaxReadBits / NO_OF_BITS_IN_BYTE) <= Int.MaxValue) + require(nMaxReadBits >= 0 &&& nMaxReadBits <= Int.MaxValue.toLong * NO_OF_BITS_IN_BYTE) require(validate_offset_bits(nMaxReadBits + nBitsTerminator)) + @ghost val oldThis = snapshot(this) var checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) // round to next full byte @@ -561,16 +606,33 @@ case class BitStream( (while (tmpStr.bitIndex() < nMaxReadBits) && !checkBitPatternPresentResult do decreases(nMaxReadBits - tmpStr.bitIndex()) - + @ghost val oldTmpStr = snapshot(tmpStr) + @ghost val oldThis2 = snapshot(this) + assert(remainingBits == oldThis.remainingBits - tmpStr.bitIndex()) + assert(validate_offset_bits(nMaxReadBits + nBitsTerminator - tmpStr.bitIndex())) tmpStr.appendBit(readBit()) + assert(tmpStr.remainingBits == oldTmpStr.remainingBits - 1) + assert(remainingBits == oldThis2.remainingBits - 1) + assert(remainingBits == oldThis.remainingBits - tmpStr.bitIndex()) if tmpStr.bitIndex() < nMaxReadBits then checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) - ).invariant(tmpStr.bitIndex() <= nMaxReadBits &&& validate_offset_bits(nMaxReadBits - tmpStr.bitIndex())) + assert(buf == oldThis.buf) + assert(tmpStr.buf.length == tmpBitStreamLength) + assert(tmpStr.bitIndex() <= nMaxReadBits) + assert(tmpStr.remainingBits == tmpBitStreamLength.toLong * NO_OF_BITS_IN_BYTE - tmpStr.bitIndex()) + assert(validate_offset_bits(nMaxReadBits + nBitsTerminator - tmpStr.bitIndex())) + ).invariant(tmpStr.buf.length == tmpBitStreamLength &&& + buf == oldThis.buf &&& + tmpStr.bitIndex() <= nMaxReadBits &&& + remainingBits == oldThis.remainingBits - tmpStr.bitIndex() &&& + tmpStr.remainingBits == tmpBitStreamLength.toLong * NO_OF_BITS_IN_BYTE - tmpStr.bitIndex() &&& + validate_offset_bits(nMaxReadBits + nBitsTerminator - tmpStr.bitIndex())) if (tmpStr.bitIndex() == nMaxReadBits) && !checkBitPatternPresentResult then checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) + // TODO: Shouldn't we do something about checkBitPatternPresentResult? (tmpStr.buf, tmpStr.bitIndex()) } From 94fadc1fdf553543a25914acc1429ccda4de21d7 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 13 Nov 2023 17:17:13 +0100 Subject: [PATCH 103/174] remove readBitsUntilTerminator --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 47 +++++++++---------- .../main/scala/asn1scala/asn1jvm_Codec.scala | 16 +++---- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index d6c1a3ac8..9733bae40 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -548,31 +548,28 @@ case class BitStream( ret } - def readBitsUntilTerminator(terminatorPattern: Array[UByte], nBitsTerminator: Long, nMaxReadBits: Long): (Array[UByte], Long) = { - require(nBitsTerminator >= 0 && nBitsTerminator <= terminatorPattern.length.toLong * NO_OF_BITS_IN_BYTE) - require(nMaxReadBits >= 0 &&& (nMaxReadBits / NO_OF_BITS_IN_BYTE) <= Int.MaxValue) - require(validate_offset_bits(nMaxReadBits + nBitsTerminator)) - - var checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) - - // round to next full byte - val tmpBitStreamLength = ((nMaxReadBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt - val tmpStr: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) - - (while (tmpStr.bitIndex() < nMaxReadBits) && !checkBitPatternPresentResult do - decreases(nMaxReadBits - tmpStr.bitIndex()) - - tmpStr.appendBit(readBit()) - - if tmpStr.bitIndex() < nMaxReadBits then - checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) - ).invariant(tmpStr.bitIndex() <= nMaxReadBits &&& validate_offset_bits(nMaxReadBits - tmpStr.bitIndex())) - - if (tmpStr.bitIndex() == nMaxReadBits) && !checkBitPatternPresentResult then - checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) - - (tmpStr.buf, tmpStr.bitIndex()) - } + // is broken in C - do not translate +// def readBitsUntilTerminator(terminatorPattern: Array[UByte], nBitsTerminator: Long, nMaxReadBits: Long): (Array[UByte], Long) = { +// require(nBitsTerminator >= 0 && nBitsTerminator <= terminatorPattern.length.toLong * NO_OF_BITS_IN_BYTE) +// require(nMaxReadBits >= 0 &&& (nMaxReadBits / NO_OF_BITS_IN_BYTE) <= Int.MaxValue) +// require(validate_offset_bits(nMaxReadBits + nBitsTerminator)) +// +// var checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) +// +// // round to next full byte +// val tmpBitStreamLength = ((nMaxReadBits + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE).toInt +// val tmpStr: BitStream = BitStream(Array.fill(tmpBitStreamLength)(0)) +// +// (while (tmpStr.bitIndex() < nMaxReadBits) && !checkBitPatternPresentResult do +// decreases(nMaxReadBits - tmpStr.bitIndex()) +// +// tmpStr.appendBit(readBit()) +// checkBitPatternPresentResult = checkBitPatternPresent(terminatorPattern, nBitsTerminator) +// +// ).invariant(tmpStr.bitIndex() <= nMaxReadBits &&& validate_offset_bits(nMaxReadBits - tmpStr.bitIndex())) +// +// (tmpStr.buf, tmpStr.bitIndex()) +// } // ************** Aligning functions ********* def alignToByte(): Unit = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 14cdf2409..d26b1f6f2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1042,14 +1042,14 @@ trait Codec { case false => None() } - // TODO rename to bitstream call - def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): OptionMut[(Array[UByte], Long)] = { - val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) - assert(isValidPrecondition) - isValidPrecondition match - case true => SomeMut(bitStream.readBitsUntilTerminator(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) - case false => NoneMut() - } + // broken in C - do not translate +// def readBits_nullterminated(bit_terminated_pattern: Array[UByte], bit_terminated_pattern_size_in_bits: Long, nMaxReadBits: Long): OptionMut[(Array[UByte], Long)] = { +// val isValidPrecondition = bitStream.validate_offset_bits(nMaxReadBits) +// assert(isValidPrecondition) +// isValidPrecondition match +// case true => SomeMut(bitStream.readBitsUntilTerminator(bit_terminated_pattern, bit_terminated_pattern_size_in_bits, nMaxReadBits)) +// case false => NoneMut() +// } def alignToByte(): Unit = { // TODO: precondition From fa0754cc6865485c9c97797aac0d37ce4a4ecde6 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 13 Nov 2023 17:48:35 +0100 Subject: [PATCH 104/174] added some return values that make more sense --- .../main/scala/asn1scala/asn1jvm_Codec.scala | 128 +++++++++++------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 6 +- 2 files changed, 83 insertions(+), 51 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index d26b1f6f2..6cec18f5a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -396,7 +396,10 @@ trait Codec { case None() => return None() case Some(l) => nBytes = l - val valIsNegative: Boolean = peekBit() + val valIsNegative = false + peekBit() match + case Some(b) => b + case None() => assert(false) var v: Long = if valIsNegative then Long.MaxValue else 0 @@ -572,7 +575,11 @@ trait Codec { return None() // decode exponent - val expIsNegative = peekBit() + var expIsNegative = false + peekBit() match + case Some(b) => expIsNegative = b + case None() => assert(false) + var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 var i: Int = 0 @@ -912,55 +919,64 @@ trait Codec { } - - - - def appendBitOne(): Unit = { + def appendBitOne(): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendBitOne() - case false => () + + if isValidPrecondition then + bitStream.appendBitOne() + + isValidPrecondition } - def appendBitZero(): Unit = { + def appendBitZero(): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendBitZero() - case false => () + + if isValidPrecondition then + bitStream.appendBitZero() + + isValidPrecondition } - def appendNBitZero(nBits: Long): Unit = { + def appendNBitZero(nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendNBitZero(nBits) - case false => () + + if isValidPrecondition then + bitStream.appendNBitZero(nBits) + + isValidPrecondition } - def appendNBitOne(nBits: Long): Unit = { + def appendNBitOne(nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendNBitOne(nBits) - case false => () + + if isValidPrecondition then + bitStream.appendNBitOne(nBits) + + isValidPrecondition } - def appendBits(srcBuffer: Array[UByte], nBits: Long): Unit = { + def appendBits(srcBuffer: Array[UByte], nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendBits(srcBuffer, nBits) - case false => () + + if isValidPrecondition then + bitStream.appendBits(srcBuffer, nBits) + + isValidPrecondition } - def appendBit(v: Boolean): Unit = { + def appendBit(v: Boolean): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() assert(isValidPrecondition) - isValidPrecondition match - case true => - bitStream.appendBit(v) + + if isValidPrecondition then + bitStream.appendBit(v) + + isValidPrecondition } def readBit(): Option[Boolean] = { @@ -971,16 +987,22 @@ trait Codec { case false => None() } - def peekBit(): Boolean = { - bitStream.peekBit() + def peekBit(): Option[Boolean] = { + val isValidPrecondition = bitStream.validate_offset_bits(1) + assert(isValidPrecondition) + isValidPrecondition match + case true => Some(bitStream.peekBit()) + case false => None() } - def appendByte(value: Byte): Unit = { + def appendByte(value: Byte): Boolean = { val isValidPrecondition = bitStream.validate_offset_byte() assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendByte(value) - case false => () + + if isValidPrecondition then + bitStream.appendByte(value) + + isValidPrecondition } def readByte(): Option[UByte] = { @@ -994,11 +1016,11 @@ trait Codec { def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) assert(isValidPrecondition) - isValidPrecondition match - case true => - bitStream.appendByteArray(arr, arr_len) - true - case false => false + + if isValidPrecondition then + bitStream.appendByteArray(arr, arr_len) + + isValidPrecondition } @@ -1018,12 +1040,14 @@ trait Codec { case false => NoneMut() } - def appendPartialByte(vVal: UByte, nbits: UByte): Unit = { + def appendPartialByte(vVal: UByte, nbits: UByte): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nbits) assert(isValidPrecondition) - isValidPrecondition match - case true => bitStream.appendPartialByte(vVal, nbits) - case false => () + + if isValidPrecondition then + bitStream.appendPartialByte(vVal, nbits) + + isValidPrecondition } def readPartialByte(nbits: UByte): Option[UByte] = { @@ -1051,12 +1075,16 @@ trait Codec { // case false => NoneMut() // } - def alignToByte(): Unit = { - // TODO: precondition - bitStream.alignToByte() -// if currentBit != 0 then -// currentBit = 0 -// currentByte += 1 + def alignToByte(): Boolean = { + val isValidPrecondition = bitStream.validate_offset_bits( + NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE) + ) + assert(isValidPrecondition) + + if isValidPrecondition then + bitStream.alignToByte() + + isValidPrecondition } def alignToShort(): Unit = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index f6c58cd86..83595de33 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -236,7 +236,11 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { - val valIsNegative: Boolean = peekBit() + var valIsNegative: Boolean = false + peekBit() match + case Some(b) => valIsNegative = b + case None() => assert(false) + val nBytes: Int = encodedSizeInBits / 8 val rstBits: Int = encodedSizeInBits % 8 From 5e0402d7faa66e53c8f252104edda467c7a319dd Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 16 Nov 2023 18:30:44 +0100 Subject: [PATCH 105/174] finished error handling refactoring --- StgScala/acn_scala.stg | 46 ++++++++++---- StgScala/uper_scala.stg | 61 ++++++++++++++----- .../main/scala/asn1scala/asn1jvm_Codec.scala | 37 ++++++++--- 3 files changed, 109 insertions(+), 35 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index e25bc55bc..ece27c31d 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -345,7 +345,9 @@ Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse { var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - codec.appendBits(if

then true_data else false_data, ) + if !codec.appendBits(if

then true_data else false_data, ) then + Console.err.println("appendBits failed: not enough space for bits") + } >> @@ -370,7 +372,9 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - codec.appendBits(tmp, ) + if !codec.appendBits(tmp, ) then + Console.err.println("appendBits failed: not enough space for bits") + } >> @@ -570,7 +574,9 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -codec.appendBits(Array({}), ) +if !codec.appendBits(Array({}), ) then + Console.err.println("appendBits failed: not enough space for bits") + >> oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << @@ -596,7 +602,9 @@ if (ret && checkBitPatternPresentResult.isEmpty) { >> bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -codec.appendBits(

arr,

nCount) +if !codec.appendBits(

arr,

nCount) then + Console.err.println(s"appendBits failed: not enough space for ${

nCount} bits") + >> bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << @@ -610,7 +618,9 @@ if (\<=) && (\<=) t >> bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -codec.appendBits(

arr, ) +if !codec.appendBits(

arr, ) then + Console.err.println("appendBits failed: not enough space for bits") + >> bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << @@ -623,8 +633,13 @@ if (\<=) && (\<=) t >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -codec.appendBits(

arr,

arr.length*8) // TODO: re-introduce nCount? -> codec.appendBits(

arr,

nCount) -codec.appendBits(Array({}), ) +if !codec.appendBits(

arr,

arr.length*8) then // TODO: re-introduce nCount? -> codec.appendBits(

arr,

nCount) + Console.err.println(s"appendBits failed: not enough space for ${

arr.length*8} bits") + + +if !codec.appendBits(Array({}), ) then + Console.err.println(s"appendBits failed: not enough space for bits") + >> bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << @@ -651,7 +666,12 @@ ret = _ACN_Decode(

, codec, pErrCode, exist.) then + Console.err.println("appendBit failed: not enough space for 1 bit") + +>> + sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << codec.readBit() match case Some(bit) => @@ -1049,7 +1069,9 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -codec.appendBits(arr, .asInstanceOf[Int]) +if !codec.appendBits(arr, .asInstanceOf[Int]) + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + >> bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << @@ -1144,11 +1166,13 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit if ret.isRight then val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - codec.appendBits(bitStrm.buf, nCount); + if !codec.appendBits(bitStrm.buf, nCount) then + Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) - codec.appendBits(bitStrm.buf, nCount) + if !codec.appendBits(bitStrm.buf, nCount) then + Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") } diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index a448f0ce7..c85a3d359 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -75,7 +75,9 @@ def (@annotation.unused codec: UPER): E >> InternalItem_oct_str_encode(p, sAcc, i, sErrCode) ::=<< -codec.appendByte0(

arr()) +if !codec.appendByte(

arr()) then + Console.err.println("appendByte failed: not enough space for 1 byte") + >> InternalItem_oct_str_decode(p, sAcc, i, sErrCode) ::=<< @@ -186,7 +188,9 @@ IntNoneRequired_decode(p, nConst, sErrCode) ::= << /*case: A:: = INTEGER (5..40,...) */ IntRootExt_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< -codec.appendBitZero() /* write extension bit*/ +if !codec.appendBitZero() then /* write extension bit*/ + Console.err.println("appendBitZero failed: not enough space for 1 bit") + >> @@ -209,11 +213,15 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< /*case: A:: = INTEGER (5..40,..., 60..70) */ IntRootExt2_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< if then - codec.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ + if !codec.appendBitZero() then /* write extension bit, value within root range, so ext bit is zero */ + Console.err.println("appendBitZero failed: not enough space for 1 bit") + else /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ - codec.appendBitOne() + if !codec.appendBitOne() then + Console.err.println("appendBitOne failed: not enough space for 1 bit") + >> @@ -223,7 +231,9 @@ IntRootExt2_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=") +if !codec.appendBit(

) then + Console.err.println("appendBit failed: not enough space for 1 bit") + >> Boolean_decode(p, sErrCode) ::= << @@ -332,7 +342,11 @@ codec.decodeConstraintWholeNumber(0, ) match // uper:317 /* CHOICE END*/ /* SEQUENCE START */ -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "codec.appendBit(

exist.);" +sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= << +if !codec.appendBit(

exist.) then + Console.err.println("appendBit failed: not enough space for 1 bit") + +>> sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << codec.readBit() match // uper:332 case Some(bit) => @@ -341,7 +355,11 @@ codec.readBit() match // uper:332 return Left() >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "codec.appendBit( )" +sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= << +if !codec.appendBit() then + Console.err.println("appendBit failed: not enough space for 1 bit") + +>> sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << @@ -495,7 +513,9 @@ codec.decodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // up /* BIT STRING*/ bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast -codec.appendBits(

arr, .asInstanceOf[Int]) +if !codec.appendBits(

arr, .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << codec.readBits(.asInstanceOf[Int]) match // uper:496 @@ -529,7 +549,8 @@ while( \< ) { codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) - codec.appendBits(&

arr[/8], (int)) + if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") val =(int) @@ -549,7 +570,8 @@ FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize = ; codec.encodeConstraintWholeNumber(, 0, 0xFF) -codec.appendBits(&

arr[/8], (int)); +if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") for(=(int); \< (int)( + ); ++) @@ -567,12 +589,15 @@ FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingIt codec.encodeConstraintWholeNumber(, 0, 0xFF) -codec.appendBit(true) +if !codec.appendBitOne() then + Console.err.println("appendBitOne failed: not enough space for 1 bit") + codec.encodeConstraintWholeNumber(, 0, 0x7FFF) -codec.appendBits(&

arr[/8], (int)); +if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${asInstanceOf[Int]} bits") for(=(int); \< (int)( + ); ++) @@ -608,7 +633,9 @@ while ( >= 0x4000 && \< (a codec.encodeConstraintWholeNumber(0xC1, 0, 0xFF) - codec.appendBits(&

arr[/8], (int)); + if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + =.asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -625,11 +652,15 @@ while ( >= 0x4000 && \< (a if \<= 0x7F then codec.encodeConstraintWholeNumber(, 0, 0xFF) else - codec.appendBit(true) + if !codec.appendBitOne() then + Console.err.println("appendBitOne failed: not enough space for 1 bit") + codec.encodeConstraintWholeNumber(, 0, 0x7FFF) -codec.appendBits(&

arr[/8], (int)); +if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + = .asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 6cec18f5a..56d5f4139 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -6,7 +6,7 @@ import stainless.collection.* import stainless.annotation.* import stainless.proof.* import stainless.math.* -import StaticChecks.* +import StaticChecks.{assert => stainlessAssert, _} val masks2: Array[UInt] = Array( 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 @@ -45,17 +45,12 @@ def ByteStream_GetLength(pStrm: ByteStream): Int = { /***********************************************************************************************/ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { arraySameElements(arr1, arr2) - //return - // (nBitsLength1 == nBitsLength2) && - // (nBitsLength1 / 8 == 0 || memcmp(arr1, arr2, nBitsLength1 / 8) == 0) && - // (nBitsLength1 % 8 > 0 ? (arr1[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8) == arr2[nBitsLength1 / 8] >>> (8 - nBitsLength1 % 8)): TRUE); } - // TODO remove -def BitStream_Init(count: Int): BitStream = { - BitStream(Array.fill(count)(0)) -} +//def BitStream_Init(count: Int): BitStream = { +// BitStream(Array.fill(count)(0)) +//} /** * Parent class for the PER Codec that is used by ACN and UPER @@ -921,6 +916,7 @@ trait Codec { def appendBitOne(): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -931,6 +927,7 @@ trait Codec { def appendBitZero(): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -941,6 +938,7 @@ trait Codec { def appendNBitZero(nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -951,6 +949,7 @@ trait Codec { def appendNBitOne(nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -961,6 +960,7 @@ trait Codec { def appendBits(srcBuffer: Array[UByte], nBits: Long): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -971,6 +971,7 @@ trait Codec { def appendBit(v: Boolean): Boolean = { val isValidPrecondition = bitStream.validate_offset_bit() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -981,7 +982,9 @@ trait Codec { def readBit(): Option[Boolean] = { val isValidPrecondition = bitStream.validate_offset_bit() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => Some(bitStream.readBit()) case false => None() @@ -989,7 +992,9 @@ trait Codec { def peekBit(): Option[Boolean] = { val isValidPrecondition = bitStream.validate_offset_bits(1) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => Some(bitStream.peekBit()) case false => None() @@ -997,6 +1002,7 @@ trait Codec { def appendByte(value: Byte): Boolean = { val isValidPrecondition = bitStream.validate_offset_byte() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -1007,7 +1013,9 @@ trait Codec { def readByte(): Option[UByte] = { val isValidPrecondition = bitStream.validate_offset_byte() + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => Some(bitStream.readByte()) case false => None() @@ -1015,6 +1023,7 @@ trait Codec { def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -1026,7 +1035,9 @@ trait Codec { def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => SomeMut(bitStream.readByteArray(arr_len)) case false => NoneMut() @@ -1034,7 +1045,9 @@ trait Codec { def readBits(nbits: Long): OptionMut[Array[UByte]] = { val isValidPrecondition = bitStream.validate_offset_bits(nbits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => SomeMut(bitStream.readBits(nbits)) case false => NoneMut() @@ -1042,6 +1055,7 @@ trait Codec { def appendPartialByte(vVal: UByte, nbits: UByte): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nbits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then @@ -1052,7 +1066,9 @@ trait Codec { def readPartialByte(nbits: UByte): Option[UByte] = { val isValidPrecondition = bitStream.validate_offset_bits(nbits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => Some(bitStream.readPartialByte(nbits)) case false => None() @@ -1060,7 +1076,9 @@ trait Codec { def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Option[Boolean] = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) + isValidPrecondition match case true => Some(bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits)) case false => None() @@ -1079,6 +1097,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits( NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE) ) + stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then From 2ee105df69837d3dcea5ae3597292fd0a966e06f Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 16 Nov 2023 18:31:06 +0100 Subject: [PATCH 106/174] commented unused verification --- .../asn1scala/asn1jvm_Verification.scala | 307 +++++++++--------- 1 file changed, 155 insertions(+), 152 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala index d9a1c3ba4..ec79ca5a8 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Verification.scala @@ -8,16 +8,8 @@ import stainless.proof.* import stainless.math.* import StaticChecks.* -val masksc: Array[Byte] = Array( - 0x00, // / 0000 0000 / - -0x80, // / 1000 0000 / - -0x40, // / 1100 0000 / - -0x20, // / 1110 0000 / - -0x10, // / 1111 0000 / - -0x08, // / 1111 1000 / - -0x04, // / 1111 1100 / - -0x02, // / 1111 1110 / -) +def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = + a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) def arrayRangesEqOffset[T](a1: Array[T], a2: Array[T], fromA1: Int, toA1: Int, fromA2: Int): Boolean = { require(0 <= fromA1 && fromA1 <= toA1) @@ -47,147 +39,158 @@ def arrayCopyOffsetLen[T](src: Array[T], dst: Array[T], fromSrc: Int, fromDst: I arrayCopyOffset(src, dst, fromSrc, fromSrc + len, fromDst) } -def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { - require(0 <= len && len <= src.length) - require(0 <= startInDst && startInDst <= src.length - len) - require(src.length <= dst.length) - arrayCopyOffset(src, dst, 0, len, startInDst) -} - -def arraySameElements[T](a1: Array[T], a2: Array[T]): Boolean = - a1.length == a2.length && arrayRangesEqOffset(a1, a2, 0, a1.length, 0) +// TODO all below is not used anymore - remove if not needed for verification work + +//val masksc: Array[Byte] = Array( +// 0x00, // / 0000 0000 / +// -0x80, // / 1000 0000 / +// -0x40, // / 1100 0000 / +// -0x20, // / 1110 0000 / +// -0x10, // / 1111 0000 / +// -0x08, // / 1111 1000 / +// -0x04, // / 1111 1100 / +// -0x02, // / 1111 1110 / +//) + +//def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { +// require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) +// val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt +// val arrPrefixEnd = (toBit / 8).toInt +// val fromBitIx = (fromBit / 8).toInt +// val toBitIx = (toBit / 8).toInt +// (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) +//} + +//def copyToArray[T](src: Array[T], dst: Array[T], startInDst: Int, len: Int): Unit = { +// require(0 <= len && len <= src.length) +// require(0 <= startInDst && startInDst <= src.length - len) +// require(src.length <= dst.length) +// arrayCopyOffset(src, dst, 0, len, startInDst) +//} // TODO: Reimplement in terms of arrayRangesEqOffset -def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - decreases(to - from) - if (from == to) true - else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) -} -@opaque @inlineOnce -def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { - require(0 <= at && at < a.length) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(0 <= i && i <= at) - require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) - decreases(i) - if (i == 0) () - else rec(i - 1) - }.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) - } - - rec(at) -}.ensuring { _ => - arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) -} - -def arrayBitIndices(fromBit: Long, toBit: Long): (Int, Int, Int, Int) = { - require(0 <= fromBit && fromBit <= toBit && toBit <= 8 * Int.MaxValue.toLong) - val arrPrefixStart = (fromBit / 8 + (if (fromBit % 8 == 0) 0 else 1)).toInt - val arrPrefixEnd = (toBit / 8).toInt - val fromBitIx = (fromBit / 8).toInt - val toBitIx = (toBit / 8).toInt - (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) -} - -def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { - require(0 <= from && from <= to && to <= 7) - ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) -} - -def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { - require(a1.length <= a2.length) - require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) - require(fromBit < a1.length.toLong * 8) - (fromBit < toBit) ==> { - val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) - val restFrom = (fromBit % 8).toInt - val restTo = (toBit % 8).toInt - ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { - if (fromBitIx == toBitIx) { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) - } else { - bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && - ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) - } - } - } -} - -@opaque @inlineOnce -def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to <= a1.length) - require(from <= at && at < to) - require(arrayPrefix(a1, a2, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= at) - require(arrayPrefix(a1, a2, i, to)) - decreases(to - i) - if (i == at) () - else rec(i + 1) - }.ensuring { _ => - a1(at) == a2(at) - } - - rec(from) -}.ensuring(_ => a1(at) == a2(at)) - -@opaque @inlineOnce -def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { - require(0 <= from && from <= to) - require(a1.length <= a2.length) - require(to < a1.length) - require(arrayPrefix(a1, a2, from, to)) - require(a1(to) == a2(to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= to) - require(arrayPrefix(a1, a2, i, to + 1)) - decreases(i) - if (i == from) () - else { - arrayPrefixImpliesEq(a1, a2, from, i - 1, to) - rec(i - 1) - } - }.ensuring { _ => - arrayPrefix(a1, a2, from, to + 1) - } - - rec(to) -}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) - -@opaque @inlineOnce -def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { - require(0 <= from && from <= mid && mid <= to) - require(a1.length <= a2.length && a2.length <= a3.length) - require(mid <= a1.length && to <= a2.length) - require(arrayPrefix(a1, a2, from, mid)) - require(arrayPrefix(a2, a3, from, to)) - - @opaque @inlineOnce - def rec(i: Int): Unit = { - require(from <= i && i <= mid) - require(arrayPrefix(a1, a2, i, mid)) - require(arrayPrefix(a2, a3, i, to)) - require(arrayPrefix(a1, a3, from, i)) - decreases(to - i) - if (i == mid) () - else { - arrayPrefixAppend(a1, a3, from, i) - rec(i + 1) - } - }.ensuring { _ => - arrayPrefix(a1, a3, from, mid) - } - rec(from) -}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) +//def arrayPrefix[T](a1: Array[T], a2: Array[T], from: Int, to: Int): Boolean = { +// require(0 <= from && from <= to) +// require(a1.length <= a2.length) +// require(to <= a1.length) +// decreases(to - from) +// if (from == to) true +// else a1(from) == a2(from) && arrayPrefix(a1, a2, from + 1, to) +//} + +//@opaque @inlineOnce +//def arrayUpdatedAtPrefixLemma[T](a: Array[T], at: Int, v: T): Unit = { +// require(0 <= at && at < a.length) +// +// @opaque @inlineOnce +// def rec(i: Int): Unit = { +// require(0 <= i && i <= at) +// require(arrayPrefix(a, freshCopy(a).updated(at, v), i, at)) +// decreases(i) +// if (i == 0) () +// else rec(i - 1) +// }.ensuring { _ => +// arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) +// } +// +// rec(at) +//}.ensuring { _ => +// arrayPrefix(a, freshCopy(a).updated(at, v), 0, at) +//} + +//def bytePrefix(b1: Byte, b2: Byte, from: Int, to: Int): Boolean = { +// require(0 <= from && from <= to && to <= 7) +// ((b1 & masksc(to) & masksb(8 - from)) & 0xFF) == ((b2 & masksc(to) & masksb(8 - from)) & 0xFF) +//} + +//def arrayBitPrefix(a1: Array[Byte], a2: Array[Byte], fromBit: Long, toBit: Long): Boolean = { +// require(a1.length <= a2.length) +// require(0 <= fromBit && fromBit <= toBit && toBit <= a1.length.toLong * 8) +// require(fromBit < a1.length.toLong * 8) +// (fromBit < toBit) ==> { +// val (arrPrefixStart, arrPrefixEnd, fromBitIx, toBitIx) = arrayBitIndices(fromBit, toBit) +// val restFrom = (fromBit % 8).toInt +// val restTo = (toBit % 8).toInt +// ((arrPrefixStart < arrPrefixEnd) ==> arrayPrefix(a1, a2, arrPrefixStart, arrPrefixEnd)) && { +// if (fromBitIx == toBitIx) { +// bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, restTo) +// } else { +// bytePrefix(a1(fromBitIx), a2(fromBitIx), restFrom, 7) && +// ((restTo != 0) ==> bytePrefix(a1(toBitIx), a2(toBitIx), 0, restTo)) +// } +// } +// } +//} + +//@opaque @inlineOnce +//def arrayPrefixImpliesEq[T](a1: Array[T], a2: Array[T], from: Int, at: Int, to: Int): Unit = { +// require(0 <= from && from <= to) +// require(a1.length <= a2.length) +// require(to <= a1.length) +// require(from <= at && at < to) +// require(arrayPrefix(a1, a2, from, to)) +// +// @opaque @inlineOnce +// def rec(i: Int): Unit = { +// require(from <= i && i <= at) +// require(arrayPrefix(a1, a2, i, to)) +// decreases(to - i) +// if (i == at) () +// else rec(i + 1) +// }.ensuring { _ => +// a1(at) == a2(at) +// } +// +// rec(from) +//}.ensuring(_ => a1(at) == a2(at)) + +//@opaque @inlineOnce +//def arrayPrefixAppend[T](a1: Array[T], a2: Array[T], from: Int, to: Int) = { +// require(0 <= from && from <= to) +// require(a1.length <= a2.length) +// require(to < a1.length) +// require(arrayPrefix(a1, a2, from, to)) +// require(a1(to) == a2(to)) +// +// @opaque @inlineOnce +// def rec(i: Int): Unit = { +// require(from <= i && i <= to) +// require(arrayPrefix(a1, a2, i, to + 1)) +// decreases(i) +// if (i == from) () +// else { +// arrayPrefixImpliesEq(a1, a2, from, i - 1, to) +// rec(i - 1) +// } +// }.ensuring { _ => +// arrayPrefix(a1, a2, from, to + 1) +// } +// +// rec(to) +//}.ensuring(_ => arrayPrefix(a1, a2, from, to + 1)) + +//@opaque @inlineOnce +//def arrayPrefixTransitive[T](a1: Array[T], a2: Array[T], a3: Array[T], from: Int, mid: Int, to: Int): Unit = { +// require(0 <= from && from <= mid && mid <= to) +// require(a1.length <= a2.length && a2.length <= a3.length) +// require(mid <= a1.length && to <= a2.length) +// require(arrayPrefix(a1, a2, from, mid)) +// require(arrayPrefix(a2, a3, from, to)) +// +// @opaque @inlineOnce +// def rec(i: Int): Unit = { +// require(from <= i && i <= mid) +// require(arrayPrefix(a1, a2, i, mid)) +// require(arrayPrefix(a2, a3, i, to)) +// require(arrayPrefix(a1, a3, from, i)) +// decreases(to - i) +// if (i == mid) () +// else { +// arrayPrefixAppend(a1, a3, from, i) +// rec(i + 1) +// } +// }.ensuring { _ => +// arrayPrefix(a1, a3, from, mid) +// } +// rec(from) +//}.ensuring(_ => arrayPrefix(a1, a3, from, mid)) From 2d4c0b175b36d9ebd18f4f0eb063b7273c65c797 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 27 Nov 2023 18:59:10 +0100 Subject: [PATCH 107/174] fix early return --- StgScala/uper_scala.stg | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index c85a3d359..ce06613bd 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -476,7 +476,9 @@ codec.decodeConstraintWholeNumber(, ) match // uper:444 octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << if !codec.encodeOctetString_no_length(

arr, .asInstanceOf[Int]) then - ret = Left(446) + Console.err.println(s"encodeOctetString_no_length failed: not enough space for ${.asInstanceOf[Int]} bytes") + return Left(479) + >> octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << From dbbddb429e577e3823e02f8aa1e6a1bc55578ae4 Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Mon, 13 Nov 2023 10:14:59 +0100 Subject: [PATCH 108/174] fix some String init/access stuff --- BackendAst/DAstUtilFunctions.fs | 1 + StgScala/LangGeneric_scala.fs | 2 +- StgScala/init_scala.stg | 8 ++++---- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/BackendAst/DAstUtilFunctions.fs b/BackendAst/DAstUtilFunctions.fs index 1090ccd5b..43f6ad761 100644 --- a/BackendAst/DAstUtilFunctions.fs +++ b/BackendAst/DAstUtilFunctions.fs @@ -86,6 +86,7 @@ let scalaInitMethSuffix (k: Asn1TypeKind) = | false -> match k with | BitString bitString -> "" + | IA5String ia5string -> "" | _ -> "()" | true -> "" | _ -> "" diff --git a/StgScala/LangGeneric_scala.fs b/StgScala/LangGeneric_scala.fs index 9114bce68..4725d9e6f 100644 --- a/StgScala/LangGeneric_scala.fs +++ b/StgScala/LangGeneric_scala.fs @@ -54,7 +54,7 @@ type LangGeneric_scala() = override _.doubleValueToString (v:double) = v.ToString(FsUtils.doubleParseString, System.Globalization.NumberFormatInfo.InvariantInfo) - override _.initializeString stringSize = sprintf "{ [0 ... %d] = 0x0 }" stringSize + override _.initializeString stringSize = sprintf "Array.fill(%d+1)(0x0)" stringSize override _.supportsInitExpressions = false diff --git a/StgScala/init_scala.stg b/StgScala/init_scala.stg index a3f22b77d..11643e811 100644 --- a/StgScala/init_scala.stg +++ b/StgScala/init_scala.stg @@ -21,7 +21,7 @@ initInteger(sVal, nValue) ::= " = " initReal(sVal, dValue) ::= " = " initBoolean(sVal, bValue) ::= " = truefalse" -initObjectIdentifier_vali(p, sAcc, sI, nIntVal) ::= "

values[] = " +initObjectIdentifier_vali(p, sAcc, sI, nIntVal) ::= "

values() = " initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= <<

nCount = @@ -107,15 +107,15 @@ while ( \< ) { /* BIT AND OCTET STRINGS */ -initBitOrOctStringFromCompoundLiteral(p, sCompLiteral) ::= "

= ;" +initBitOrOctStringFromCompoundLiteral(p, sCompLiteral) ::= "

= " -initFixSizeBitOrOctString_bytei(p, sAcc, sI, sByteHexVal) ::= "

arr[] = 0x;" +initFixSizeBitOrOctString_bytei(p, sAcc, sI, sByteHexVal) ::= "

arr() = 0x;" initFixSizeBitOrOctString(p, sAcc,arrsBytes) ::= << >> initFixVarSizeBitOrOctString(p, sAcc, nSize, arrsBytes) ::= << -

nCount = ; +

nCount = >> From e79972592153411b6c6038e602b5b5504a05a2bf Mon Sep 17 00:00:00 2001 From: Ivo Nussbaumer Date: Fri, 1 Dec 2023 17:12:03 +0100 Subject: [PATCH 109/174] translated some left over C code --- StgScala/acn_scala.stg | 4 ++-- StgScala/equal_scala.stg | 8 ++++---- StgScala/isvalid_scala.stg | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index ece27c31d..5fbe77edf 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -844,7 +844,7 @@ case => ChoiceChild_encode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case () => - codec.BitStream_EncodeConstraintWholeNumber(, 0, ) + codec.encodeConstraintWholeNumber(, 0, ) >> @@ -1170,7 +1170,7 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") - codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) + codec.encodeConstraintWholeNumber(nCount, , ) if !codec.appendBits(bitStrm.buf, nCount) then Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") diff --git a/StgScala/equal_scala.stg b/StgScala/equal_scala.stg index e4e86f8aa..f5e3ced16 100644 --- a/StgScala/equal_scala.stg +++ b/StgScala/equal_scala.stg @@ -95,7 +95,7 @@ isEqual_Boolean(p1, p2) /*nogen*/::= "ret = ( ( && ) || (! && !) isEqual_Real(p1, p2) ::= "Asn1Real_Equal(, )" -isEqual_IA5String(p1, p2) /*nogen*/::= "ret = (strcmp(, ) ==0)" +isEqual_IA5String(p1, p2) /*nogen*/::= "ret = .sameElements()" isEqual_NumericString(p1, p2) /*nogen*/::= "" isEqual_NullType()/*nogen*/ ::= "ret = true" @@ -171,10 +171,10 @@ while ret && \< nCount do >> isEqual_SequenceOf_fix_size(p1,p2, sAcc, i, nFixedSize, sInnerStatement) ::= << -for( = 0; ret && \< ; ++) -{ + = 0 +while ret && \< do -} + += 1 >> diff --git a/StgScala/isvalid_scala.stg b/StgScala/isvalid_scala.stg index d264428c7..341aad5e5 100644 --- a/StgScala/isvalid_scala.stg +++ b/StgScala/isvalid_scala.stg @@ -84,7 +84,7 @@ def (@annotation.unused : > ExpEqual(sExp1, sExp2) ::= "( == )" -ExpStringEqual(sExp1, sExp2) ::= "( == )" +ExpStringEqual(sExp1, sExp2) ::= "(.sameElements(.getBytes))" ExpGt(sExp1, sExp2) ::= "( \> )" ExpGte(sExp1, sExp2) ::= "( \>= )" ExpLt(sExp1, sExp2) ::= "( \< )" From 5a608b56c70a06ce94eab7b38ee8fd200e3c27a8 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 1 Dec 2023 17:31:34 +0100 Subject: [PATCH 110/174] fixed #281 --- BackendAst/DAstInitialize.fs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/BackendAst/DAstInitialize.fs b/BackendAst/DAstInitialize.fs index 08fcb6b23..9c78a9ae9 100644 --- a/BackendAst/DAstInitialize.fs +++ b/BackendAst/DAstInitialize.fs @@ -869,11 +869,16 @@ let createSequenceOfInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A initTasFunction, nonEmbeddedChildrenFuncs + let initParams = + match o.isFixedSize with + | true -> $"(Array.fill({o.maxSize}){{{extractDefaultInitValue childType.Kind}}})" + | false -> $"({o.minSize}, Array.fill({o.maxSize}){{{extractDefaultInitValue childType.Kind}}})" + let initVal = match typeDefinition with | TypeDefinition t -> t.typedefName | ReferenceToExistingDefinition r -> r.typedefName - + $"(0, Array.fill({o.maxSize}){{{extractDefaultInitValue childType.Kind}}})" + + initParams let childInitExpr = getChildExpression lm childType let childInitGlobal = getChildExpressionGlobal lm childType From 4b61d9d29d347790f93f7e14bb140a380ba1e21b Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 1 Dec 2023 19:48:46 +0100 Subject: [PATCH 111/174] reworked alignment --- .../src/main/scala/asn1scala/asn1jvm.scala | 2 ++ .../scala/asn1scala/asn1jvm_Bitstream.scala | 25 +++++++++++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index a0dea3587..fda595ede 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -27,6 +27,8 @@ type ULongNoRTL = ULong type asn1Real = Double val NO_OF_BITS_IN_BYTE = 8 +val NO_OF_BITS_IN_SHORT = 16 +val NO_OF_BITS_IN_INT = 32 val NO_OF_BITS_IN_LONG = 64 val NO_OF_BYTES_IN_JVM_SHORT = 2 val NO_OF_BYTES_IN_JVM_INT = 4 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 81cd8079a..5f3f4ca18 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -641,29 +641,32 @@ case class BitStream( // ************** Aligning functions ********* def alignToByte(): Unit = { + require(validate_offset_bits((currentBit + (NO_OF_BITS_IN_BYTE - 1)) / NO_OF_BITS_IN_BYTE)) + if currentBit != 0 then - val bitIndexIncrease = 8 - currentBit % 8 currentBit = 0 currentByte += 1 } def alignToShort(): Unit = { - require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT) + (currentBit+7)/8)) + require(validate_offset_bits( + (NO_OF_BITS_IN_SHORT - // max alignment (16) - + (NO_OF_BITS_IN_BYTE * (currentByte % NO_OF_BYTES_IN_JVM_SHORT) + currentBit) // current pos + ) % NO_OF_BITS_IN_SHORT) // edge case (0,0) -> 0 + ) alignToByte() - - if (currentByte % NO_OF_BYTES_IN_JVM_SHORT) != 0 then - val byteIndexIncrease = NO_OF_BYTES_IN_JVM_SHORT - currentByte % NO_OF_BYTES_IN_JVM_SHORT - currentByte += byteIndexIncrease + currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT } def alignToInt(): Unit = { - require(validate_offset_bytes((NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT) + (currentBit+7)/8)) + require(validate_offset_bits( + (NO_OF_BITS_IN_INT - // max alignment (32) - + (NO_OF_BITS_IN_BYTE * (currentByte % NO_OF_BYTES_IN_JVM_INT) + currentBit) // current pos + ) % NO_OF_BITS_IN_INT) // edge case (0,0) -> 0 + ) alignToByte() - - if (currentByte % NO_OF_BYTES_IN_JVM_INT) != 0 then - val byteIndexIncrease = NO_OF_BYTES_IN_JVM_INT - currentByte % NO_OF_BYTES_IN_JVM_INT - currentByte += byteIndexIncrease + currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT } } // BitStream class From 8dbc730d1d6fa13761b090fffdefc2f50aec80f1 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 4 Dec 2023 15:34:06 +0100 Subject: [PATCH 112/174] use cheaper OP --- .../src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 5f3f4ca18..aac4e26fa 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -650,9 +650,9 @@ case class BitStream( def alignToShort(): Unit = { require(validate_offset_bits( - (NO_OF_BITS_IN_SHORT - // max alignment (16) - - (NO_OF_BITS_IN_BYTE * (currentByte % NO_OF_BYTES_IN_JVM_SHORT) + currentBit) // current pos - ) % NO_OF_BITS_IN_SHORT) // edge case (0,0) -> 0 + (NO_OF_BITS_IN_SHORT - // max alignment (16) - + (NO_OF_BITS_IN_BYTE * (currentByte & (NO_OF_BYTES_IN_JVM_SHORT - 1)) + currentBit) // current pos + ) & (NO_OF_BITS_IN_SHORT - 1)) // edge case (0,0) -> 0 ) alignToByte() @@ -661,9 +661,9 @@ case class BitStream( def alignToInt(): Unit = { require(validate_offset_bits( - (NO_OF_BITS_IN_INT - // max alignment (32) - - (NO_OF_BITS_IN_BYTE * (currentByte % NO_OF_BYTES_IN_JVM_INT) + currentBit) // current pos - ) % NO_OF_BITS_IN_INT) // edge case (0,0) -> 0 + (NO_OF_BITS_IN_INT - // max alignment (32) - + (NO_OF_BITS_IN_BYTE * (currentByte & (NO_OF_BYTES_IN_JVM_INT - 1)) + currentBit) // current pos + ) & (NO_OF_BITS_IN_INT - 1)) // edge case (0,0) -> 0 ) alignToByte() From 1493b8302a75dc59885ec24d357c2ef864dd09e8 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 4 Dec 2023 18:09:32 +0100 Subject: [PATCH 113/174] added proposed C implementation for comparability --- asn1crt/asn1crt.h | 45 +++++++++++++++++++++++++++------- asn1crt/asn1crt_encoding_acn.c | 39 ++++++++++++++--------------- 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/asn1crt/asn1crt.h b/asn1crt/asn1crt.h index e4d41ca41..5bb2e8bfa 100644 --- a/asn1crt/asn1crt.h +++ b/asn1crt/asn1crt.h @@ -8,7 +8,7 @@ extern "C" { # include # include - /* C99 check */ + /* C99 check */ #elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || _MSC_VER >= 1900 # include # include @@ -50,6 +50,26 @@ typedef unsigned long long uint64_t; #define FP_WORD_SIZE 8 #endif +#ifndef NO_OF_BITS_IN_BYTE +#define NO_OF_BITS_IN_BYTE 8 +#endif + +#ifndef NO_OF_BYTES_IN_INT16 +#define NO_OF_BYTES_IN_INT16 (sizeof(int16_t)) // 2 +#endif + +#ifndef NO_OF_BYTES_IN_INT32 +#define NO_OF_BYTES_IN_INT32 (sizeof(int32_t)) // 4 +#endif + +#ifndef NO_OF_BITS_IN_INT16 +#define NO_OF_BITS_IN_INT16 (NO_OF_BYTES_IN_INT16 * NO_OF_BITS_IN_BYTE) // 16 +#endif + +#ifndef NO_OF_BITS_IN_INT32 +#define NO_OF_BITS_IN_INT32 (NO_OF_BYTES_IN_INT32 * NO_OF_BITS_IN_BYTE) // 32 +#endif + #ifndef PRId32 #define PRId32 "d" #endif @@ -129,10 +149,10 @@ typedef struct BitStream_t { byte* buf; long count; long currentByte; - /* Next available bit for writting. - Possible vallues 0..7, 0 is most significant + /* Next available bit for writting. + Possible vallues 0..7, 0 is most significant bit of current byte*/ - int currentBit; + int currentBit; //PushDataFnc pushData; void* pushDataPrm; //FetchDataFnc fetchData; @@ -182,10 +202,10 @@ int GetCharIndex(char ch, byte allowedCharSet[], int setLen); flag Asn1Real_Equal(asn1Real Left, asn1Real Right); -void ObjectIdentifier_Init(Asn1ObjectIdentifier *pVal); -flag ObjectIdentifier_equal(const Asn1ObjectIdentifier *pVal1, const Asn1ObjectIdentifier *pVal2); -flag ObjectIdentifier_isValid(const Asn1ObjectIdentifier *pVal); -flag RelativeOID_isValid(const Asn1ObjectIdentifier *pVal); +void ObjectIdentifier_Init(Asn1ObjectIdentifier* pVal); +flag ObjectIdentifier_equal(const Asn1ObjectIdentifier* pVal1, const Asn1ObjectIdentifier* pVal2); +flag ObjectIdentifier_isValid(const Asn1ObjectIdentifier* pVal); +flag RelativeOID_isValid(const Asn1ObjectIdentifier* pVal); /* Time Classes Asn1LocalTime, // TIME-OF-DAY ::= TIME(SETTINGS "Basic=Time Time=HMS Local-or-UTC=L") @@ -259,7 +279,14 @@ extern const asn1SccUint64 ber_aux[]; extern const asn1SccUint32 ber_aux[]; #endif -#define CHECK_BIT_STREAM(pBitStrm) assert((pBitStrm)->currentByte*8+(pBitStrm)->currentBit<=(pBitStrm)->count*8) +#define CHECK_BIT_STREAM(pBitStrm) assert((pBitStrm)->currentByte*8+(pBitStrm)->currentBit<=(pBitStrm)->count*8) + +// check if nBits still have space in pBitStrm (only for non streaming mode) +#ifndef ASN1SCC_STREAMING +#define CHECK_BIT_STREAM_PRE(pBitStrm, nBits) assert(((pBitStrm)->currentByte * 8 + (pBitStrm)->currentBit + nBits) <= ((pBitStrm)->count * 8)) +#else +#define CHECK_BIT_STREAM_PRE(pBitStrm, nBits) ((void)pBitStrm) +#endif #ifdef _MSC_VER #pragma warning( disable : 4127) diff --git a/asn1crt/asn1crt_encoding_acn.c b/asn1crt/asn1crt_encoding_acn.c index 64c41d7af..6d43bf17a 100644 --- a/asn1crt/asn1crt_encoding_acn.c +++ b/asn1crt/asn1crt_encoding_acn.c @@ -10,10 +10,11 @@ static flag RequiresReverse(void) return b[0] == 1; } - - void Acn_AlignToNextByte(BitStream* pBitStrm, flag bEncode) { + CHECK_BIT_STREAM_PRE(pBitStrm, (NO_OF_BITS_IN_BYTE - + pBitStrm->currentBit) & (NO_OF_BITS_IN_BYTE - 1)); + if (pBitStrm->currentBit != 0) { pBitStrm->currentBit = 0; @@ -21,43 +22,41 @@ void Acn_AlignToNextByte(BitStream* pBitStrm, flag bEncode) if (bEncode) bitstream_push_data_if_required(pBitStrm); else - bitstream_fetch_data_if_required(pBitStrm); + bitstream_fetch_data_if_required(pBitStrm); CHECK_BIT_STREAM(pBitStrm); } } void Acn_AlignToNextWord(BitStream* pBitStrm, flag bEncode) { + CHECK_BIT_STREAM_PRE(pBitStrm, (NO_OF_BITS_IN_INT16 - + (NO_OF_BITS_IN_BYTE * (pBitStrm->currentByte & (NO_OF_BYTES_IN_INT16 - 1)) + pBitStrm->currentBit)) + & (NO_OF_BITS_IN_INT16 - 1)); + Acn_AlignToNextByte(pBitStrm, bEncode); + pBitStrm->currentByte = ((pBitStrm->currentByte + (NO_OF_BYTES_IN_INT16 - 1)) / NO_OF_BYTES_IN_INT16) * NO_OF_BYTES_IN_INT16; - pBitStrm->currentByte += pBitStrm->currentByte % 2; if (bEncode) bitstream_push_data_if_required(pBitStrm); else - bitstream_fetch_data_if_required(pBitStrm); + bitstream_fetch_data_if_required(pBitStrm); CHECK_BIT_STREAM(pBitStrm); } void Acn_AlignToNextDWord(BitStream* pBitStrm, flag bEncode) { - Acn_AlignToNextByte(pBitStrm, bEncode); + CHECK_BIT_STREAM_PRE(pBitStrm, (NO_OF_BITS_IN_INT32 - + (NO_OF_BITS_IN_BYTE * (pBitStrm->currentByte & (NO_OF_BYTES_IN_INT32 - 1)) + pBitStrm->currentBit)) + & (NO_OF_BITS_IN_INT32 - 1)); - //pBitStrm->currentByte += pBitStrm->currentByte % 4; - int totalBytes = pBitStrm->currentByte % 4; - if (pBitStrm->currentByte + totalBytes < pBitStrm->count) { - pBitStrm->currentByte += totalBytes; - } - else { - int extraBytes = pBitStrm->currentByte + totalBytes - pBitStrm->count; - pBitStrm->currentByte = pBitStrm->count; - if (bEncode) - bitstream_push_data_if_required(pBitStrm); - else - bitstream_fetch_data_if_required(pBitStrm); - pBitStrm->currentByte = extraBytes; - } + Acn_AlignToNextByte(pBitStrm, bEncode); + pBitStrm->currentByte = ((pBitStrm->currentByte + (NO_OF_BYTES_IN_INT32 - 1)) / NO_OF_BYTES_IN_INT32) * NO_OF_BYTES_IN_INT32; + if (bEncode) + bitstream_push_data_if_required(pBitStrm); + else + bitstream_fetch_data_if_required(pBitStrm); CHECK_BIT_STREAM(pBitStrm); } From 24977989cba746d6a59ba190bcaf77c082b13e72 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 4 Dec 2023 18:09:50 +0100 Subject: [PATCH 114/174] fixed broken precondition --- asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index aac4e26fa..670340b1e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -641,7 +641,9 @@ case class BitStream( // ************** Aligning functions ********* def alignToByte(): Unit = { - require(validate_offset_bits((currentBit + (NO_OF_BITS_IN_BYTE - 1)) / NO_OF_BITS_IN_BYTE)) + require(validate_offset_bits( + (NO_OF_BITS_IN_BYTE - currentBit) & (NO_OF_BITS_IN_BYTE - 1) + )) if currentBit != 0 then currentBit = 0 From 975b79d0307161b41e21b7b0e79fbd46cd2bd50d Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 4 Dec 2023 18:56:38 +0100 Subject: [PATCH 115/174] changed from ghost to pure - meth gets accessed from non ghost context in codec --- .../src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 670340b1e..8a240f6aa 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -80,32 +80,34 @@ case class BitStream( ) { // all BisStream instances satisfy the following: require(BitStream.invariant(currentBit, currentByte, buf.length)) + @pure private def remainingBits: Long = { (buf.length.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit) } - @ghost + @pure def validate_offset_bit(): Boolean = { remainingBits >= 1 }.ensuring(_ => BitStream.invariant(this)) - @ghost + @pure def validate_offset_bits(bits: Long = 0): Boolean = { require(bits >= 0) remainingBits >= bits }.ensuring(_ => BitStream.invariant(this)) - @ghost + @pure def validate_offset_byte(): Boolean = { remainingBits >= NO_OF_BITS_IN_BYTE }.ensuring(_ => BitStream.invariant(this)) - @ghost + @pure def validate_offset_bytes(bytes: Int): Boolean = { require(bytes >= 0) bytes <= remainingBits / NO_OF_BITS_IN_BYTE }.ensuring(_ => BitStream.invariant(this)) + @pure def bitIndex(): Long = { currentByte.toLong * 8 + currentBit.toLong }.ensuring(res => 0 <= res && res <= 8 * buf.length.toLong &&& res == buf.length.toLong * 8 - remainingBits) From 31feeaf675f1cdafc6fec770683ac76e3358bb49 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 8 Dec 2023 18:08:00 +0100 Subject: [PATCH 116/174] removed unused real enc / dec fixed F# errors (only with latest VS - were warning before) verfied some stuff --- BackendAst/DAstACN.fs | 9 +- .../src/main/scala/asn1scala/asn1jvm.scala | 2 + .../scala/asn1scala/asn1jvm_Bitstream.scala | 2 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 19 +-- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 136 ++++++++---------- .../main/scala/asn1scala/asn1jvm_Helper.scala | 2 +- 6 files changed, 83 insertions(+), 87 deletions(-) diff --git a/BackendAst/DAstACN.fs b/BackendAst/DAstACN.fs index 98558ab70..6c32be769 100644 --- a/BackendAst/DAstACN.fs +++ b/BackendAst/DAstACN.fs @@ -149,13 +149,16 @@ let handleAlignemntForAsn1Types (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (code | Some al -> let alStr, nAligmVal = match al with - | AcnGenericTypes.NextByte -> match ST.lang with + | AcnGenericTypes.NextByte -> + match ST.lang with | Scala -> "Byte", 8I | _ -> "NextByte", 8I - | AcnGenericTypes.NextWord -> match ST.lang with + | AcnGenericTypes.NextWord -> + match ST.lang with | Scala -> "Short", 16I | _ -> "NextWord", 16I - | AcnGenericTypes.NextDWord -> match ST.lang with + | AcnGenericTypes.NextDWord -> + match ST.lang with | Scala -> "Int", 32I | _ -> "NextDWord", 32I let newFuncBody st errCode prms p = diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala index fda595ede..2bf326acd 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm.scala @@ -33,6 +33,8 @@ val NO_OF_BITS_IN_LONG = 64 val NO_OF_BYTES_IN_JVM_SHORT = 2 val NO_OF_BYTES_IN_JVM_INT = 4 val NO_OF_BYTES_IN_JVM_LONG = 8 +val NO_OF_BYTES_IN_JVM_FLOAT = 4 +val NO_OF_BYTES_IN_JVM_DOUBLE = 8 val OBJECT_IDENTIFIER_MAX_LENGTH = 20 val NOT_INITIALIZED_ERR_CODE = 1337 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 8a240f6aa..d050d1b4b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -556,7 +556,7 @@ case class BitStream( * */ def readPartialByte(nBits: Int): UByte = { - require(nBits >= 0 && nBits < NO_OF_BITS_IN_BYTE) + require(nBits >= 0 && nBits <= NO_OF_BITS_IN_BYTE) require(validate_offset_bits(nBits)) @ghost val oldThis = snapshot(this) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 56d5f4139..ccf313ed4 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -57,7 +57,6 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { * * @param count represents the number of bytes in the internal buffer */ -@mutable trait Codec { def bitStream: BitStream @@ -177,17 +176,17 @@ trait Codec { // return decodeNonNegativeInteger32Neg(v, nBits) } - def encodeNonNegativeIntegerNeg(v: ULong, negate: Boolean): Unit = { + def encodeNonNegativeIntegerNeg(v: ULong): Unit = { if v >>> 32 == 0 then - encodeNonNegativeInteger32Neg(v.toInt, negate) + encodeNonNegativeInteger32Neg(v.toInt, true) else // TODO: Check Int/Long val hi = (v >>> 32).toInt var lo = v.toInt - encodeNonNegativeInteger32Neg(hi, negate) + encodeNonNegativeInteger32Neg(hi, true) /*bug !!!!*/ - if negate then + if true then // TODO, the negate flag was always true lo = ~lo val nBits = GetNumberOfBitsForNonNegativeInteger(lo.toLong) appendNBitZero(32 - nBits) @@ -379,7 +378,7 @@ trait Codec { encodeNonNegativeInteger(v) else appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) - encodeNonNegativeIntegerNeg((-v - 1), true) + encodeNonNegativeIntegerNeg((-v - 1)) } @@ -1064,13 +1063,15 @@ trait Codec { isValidPrecondition } - def readPartialByte(nbits: UByte): Option[UByte] = { - val isValidPrecondition = bitStream.validate_offset_bits(nbits) + def readPartialByte(nBits: Int): Option[UByte] = { + require(nBits >= 0 && nBits <= NO_OF_BITS_IN_BYTE) + + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) isValidPrecondition match - case true => Some(bitStream.readPartialByte(nbits)) + case true => Some(bitStream.readPartialByte(nBits)) case false => None() } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 83595de33..31f0aff9a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -1,7 +1,7 @@ package asn1scala import stainless.lang.StaticChecks.assert -import stainless.lang.{None, Option, Some} +import stainless.lang.{None => None, ghost => ghostExpr, Option => Option, _} val FAILED_READ_ERR_CODE = 5400 @@ -203,7 +203,7 @@ case class ACN(bitStream: BitStream) extends Codec { else appendNBitOne(encodedSizeInBits - GetNumberOfBitsForNonNegativeInteger(-intVal - 1)) - encodeNonNegativeIntegerNeg(-intVal - 1, true) + encodeNonNegativeIntegerNeg(-intVal - 1) } @@ -691,118 +691,108 @@ case class ACN(bitStream: BitStream) extends Codec { Right(0) } - - /*Real encoding functions*/ + /* Real encoding functions */ def enc_Real_IEEE754_32_big_endian(realValue: Float): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue).array + val b: Array[Byte] = java.nio.ByteBuffer.allocate(NO_OF_BYTES_IN_JVM_FLOAT).putFloat(realValue).array var i: Int = 0 - while i < 4 do + while i < NO_OF_BYTES_IN_JVM_FLOAT do appendByte(b(i)) i += 1 } - def dec_Real_IEEE754_32_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 0 - while i < 4 do - readByte() match - case None() => return None() - case Some(ub) => b(i) = ub - i += 1 + def enc_Real_IEEE754_32_little_endian(realValue: Float): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(NO_OF_BYTES_IN_JVM_FLOAT).putFloat(realValue).array - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1).toDouble) + var i: Int = NO_OF_BYTES_IN_JVM_FLOAT - 1 + while i >= 0 do + appendByte(b(i)) + i -= 1 } - def dec_Real_IEEE754_32_big_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) + def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(NO_OF_BYTES_IN_JVM_DOUBLE).putDouble(realValue).array + var i: Int = 0 - while i < 4 do - readByte() match - case None() => return None() - case Some(ub) => b(i) = ub + while i < NO_OF_BYTES_IN_JVM_DOUBLE do + appendByte(b(i)) i += 1 - - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) } + def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { + val b: Array[Byte] = java.nio.ByteBuffer.allocate(NO_OF_BYTES_IN_JVM_DOUBLE).putDouble(realValue).array - def enc_Real_IEEE754_64_big_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array - - var i: Int = 0 - while i < 8 do + var i: Int = NO_OF_BYTES_IN_JVM_DOUBLE - 1 + while i >= 0 do appendByte(b(i)) - i += 1 + i -= 1 } - def dec_Real_IEEE754_64_big_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 0 - while i < 8 do + /* Real decoding functions */ + def dec_Real_IEEE754_32_big_endian(): Option[Float] = { + var ret: Int = 0 + var i: Int = 1 + + assert(NO_OF_BYTES_IN_JVM_INT == NO_OF_BYTES_IN_JVM_FLOAT) + + while i <= NO_OF_BYTES_IN_JVM_INT do readByte() match case None() => return None() - case Some(ub) => b(i) = ub + case Some(b) => + ret |= b.unsignedToInt << (NO_OF_BYTES_IN_JVM_INT - i) * NO_OF_BITS_IN_BYTE i += 1 - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) + Some(java.lang.Float.intBitsToFloat(ret)) } + def dec_Real_IEEE754_32_little_endian(): Option[Float] = { + var ret: Int = 0 + var i: Int = 0 - def enc_Real_IEEE754_32_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(4).putFloat(realValue.toFloat).array + assert(NO_OF_BYTES_IN_JVM_INT == NO_OF_BYTES_IN_JVM_FLOAT) - var i: Int = 3 - while i >= 0 do - appendByte(b(i)) - i -= 1 - } + while i < NO_OF_BYTES_IN_JVM_INT do + readByte() match + case None() => return None() + case Some(b) => + ret |= b.unsignedToInt << i * NO_OF_BITS_IN_BYTE + i += 1 - def dec_Real_IEEE754_32_little_endian(): Option[Double] = { - dec_Real_IEEE754_32_little_endian_fp32() match - case None() => None() - case Some(f) => Some(f.toDouble) + Some(java.lang.Float.intBitsToFloat(ret)) } - def dec_Real_IEEE754_32_little_endian_fp32(): Option[Float] = { - val b: Array[Byte] = Array.fill(4)(0) - var i: Int = 3 - while i >= 0 do + def dec_Real_IEEE754_64_big_endian(): Option[Double] = { + var ret: Long = 0 + var i: Int = 1 + + assert(NO_OF_BYTES_IN_JVM_LONG == NO_OF_BYTES_IN_JVM_DOUBLE) + + while i <= NO_OF_BYTES_IN_JVM_LONG do readByte() match case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 + case Some(b) => + ret |= b.unsignedToLong << (NO_OF_BYTES_IN_JVM_LONG - i) * NO_OF_BITS_IN_BYTE + i += 1 - val dat1 = BigInt(b).toInt - Some(java.lang.Float.intBitsToFloat(dat1)) + Some(java.lang.Double.longBitsToDouble(ret)) } - def enc_Real_IEEE754_64_little_endian(realValue: Double): Unit = { - val b: Array[Byte] = java.nio.ByteBuffer.allocate(8).putDouble(realValue).array + def dec_Real_IEEE754_64_little_endian(): Option[Double] = { + var ret: Long = 0 + var i: Int = 0 - var i: Int = 7 - while i >= 0 do - appendByte(b(i)) - i -= 1 - } + assert(NO_OF_BYTES_IN_JVM_LONG == NO_OF_BYTES_IN_JVM_DOUBLE) - def dec_Real_IEEE754_64_little_endian(): Option[Double] = { - val b: Array[Byte] = Array.fill(8)(0) - var i: Int = 7 - while i >= 0 do + while i < NO_OF_BYTES_IN_JVM_LONG do readByte() match case None() => return None() - case Some(ub) => b(i) = ub - i -= 1 + case Some(b) => + ret |= b.unsignedToLong << i * NO_OF_BITS_IN_BYTE + i += 1 - val dat1 = BigInt(b).toLong - Some(java.lang.Double.longBitsToDouble(dat1)) + Some(java.lang.Double.longBitsToDouble(ret)) } - /* String functions*/ def enc_String_Ascii_FixSize(max: Long, strVal: Array[ASCIIChar]): Unit = { var i: Long = 0 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index b2a3defe5..ce8206be5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -27,7 +27,7 @@ val MASK_POS_INT = 0x7F_FF_FF_FFL * Meths to upcast unsigned integer data types on the JVM */ extension (ubL: UByte) { - def unsignedToLong: Long = ubL & MASK_BYTE_L + def unsignedToLong: Long = ubL.toLong & MASK_BYTE_L def unsignedToInt: Int = ubL.toInt & MASK_BYTE @targetName("unsigned right shift on Bytes") From d02c9a967fedbac046d18efc7f0b5b4ad5369b61 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Thu, 14 Dec 2023 17:10:13 +0100 Subject: [PATCH 117/174] post enc func & post dec val --- BackendAst/DAstACN.fs | 3 ++- StgScala/acn_scala.stg | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/BackendAst/DAstACN.fs b/BackendAst/DAstACN.fs index 6c32be769..4fe24efa1 100644 --- a/BackendAst/DAstACN.fs +++ b/BackendAst/DAstACN.fs @@ -1629,7 +1629,8 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi | None -> (ToC (r.args.mappingFunctionsModule.orElse "")) + "." + (ToC fncName.Value) | Some modFncName -> (ToC modFncName.Value) + "." + (ToC fncName.Value) - let fncCall = sequence_call_post_encoding_function (lm.lg.getPointer p.arg) (actualFncName) bsPosStart bitStreamPositionsLocalVar + let fncCall = sequence_call_post_encoding_function (lm.lg.getPointer p.arg) (actualFncName) bsPosStart bitStreamPositionsLocalVar + let initialBitStrmStatement = sequence_save_bitStream_start bsPosStart codec [AcnInsertedChild(bitStreamPositionsLocalVar, td.extention_function_potisions, ""); AcnInsertedChild(bsPosStart, bitStreamName, "")]@localVariables, Some fncCall, Some bitStreamPositionsLocalVar, Some initialBitStrmStatement | _ -> diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 5fbe77edf..dd5576309 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -821,11 +821,11 @@ else >> sequence_call_post_encoding_function(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << -(

, &, &, codec) +(

, , , codec) >> sequence_call_post_decoding_validator(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << -ret = (

, &, &, codec, pErrCode) +ret = (

, , , codec) >> /* SEQUENCE END */ From 8b482fb4b39a336a055e118d87b0d1d6ecfc74c5 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 15 Dec 2023 20:46:24 +0100 Subject: [PATCH 118/174] typo & some VCs --- StgScala/acn_scala.stg | 6 +- StgScala/uper_scala.stg | 42 +++---- .../main/scala/asn1scala/asn1jvm_Codec.scala | 114 +++++++++++------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 10 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 8 +- 5 files changed, 102 insertions(+), 78 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index dd5576309..f7b3ee462 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -844,7 +844,7 @@ case => ChoiceChild_encode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case () => - codec.encodeConstraintWholeNumber(, 0, ) + codec.encodeConstrainedWholeNumber(, 0, ) >> @@ -1111,7 +1111,7 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, nBits ret = Right(0) - codec.encodeConstraintWholeNumber(nCount, , ) + codec.encodeConstrainedWholeNumber(nCount, , ) codec.encodeOctetString_no_length(bitStrm.buf, nCount) match case false => return Left(pErrCode) @@ -1170,7 +1170,7 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") - codec.encodeConstraintWholeNumber(nCount, , ) + codec.encodeConstrainedWholeNumber(nCount, , ) if !codec.appendBits(bitStrm.buf, nCount) then Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index ce06613bd..a251dbee9 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -92,7 +92,7 @@ val allowedCharSet: Array[Byte] = Array(}; wr InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< val charIndex: Int = GetCharIndex(

(), allowedCharSet) -codec.encodeConstraintWholeNumber(charIndex, 0, ) +codec.encodeConstrainedWholeNumber(charIndex, 0, ) >> InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< @@ -106,7 +106,7 @@ codec.decodeConstraintWholeNumber(0, ) match >> InternalItem_string_no_alpha_encode(p, sErrCode, i) ::=<< -codec.encodeConstraintWholeNumber(

(), 0, 127) +codec.encodeConstrainedWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< @@ -122,7 +122,7 @@ codec.decodeConstraintWholeNumberByte(0, 127) match // uper:109 /*case: A:: = INTEGER (-5..20) */ IntFullyConstraint_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -codec.encodeConstraintWholeNumber(

, , ) +codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << @@ -147,7 +147,7 @@ codec.decodeConstraintPosWholeNumber(, ) match // uper:135 >> /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnConstraintWholeNumber(

)" +IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << codec.decodeUnConstraintWholeNumber() match // uper:145 case Some(x) => @@ -157,7 +157,7 @@ codec.decodeUnConstraintWholeNumber() match // uper:145 >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnConstraintWholeNumber(

)" +IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << if !codec.decodeUnConstraintWholeNumber() then ret = if then 0 else @@ -273,7 +273,7 @@ if !codec._decode() then Enumerated_item_encode(p, sName, nIndex, nLastItemIndex) ::= << case => - codec.encodeConstraintWholeNumber(, 0, ) + codec.encodeConstrainedWholeNumber(, 0, ) >> Enumerated_item_decode(p, sName, nIndex, nLastItemIndex) ::= << @@ -303,7 +303,7 @@ codec.decodeConstraintWholeNumber(0, ) match // uper:277 choice_child_encode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr, bIsSequence, bIsEnum) ::= << case () => - codec.encodeConstraintWholeNumber(, 0, ) + codec.encodeConstrainedWholeNumber(, 0, ) >> choice_child_decode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr, bIsSequence, bIsEnum) ::= << @@ -431,7 +431,7 @@ str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength =

.indexOf(0x00) /*ret = nStringLength >= && nStringLength \<= ;*/ -codec.encodeConstraintWholeNumber(nStringLength, , ) +codec.encodeConstrainedWholeNumber(nStringLength, , ) >> @@ -459,7 +459,7 @@ seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSiz >> seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -codec.encodeConstraintWholeNumber(

nCount, , ) +codec.encodeConstrainedWholeNumber(

nCount, , ) >> @@ -490,7 +490,7 @@ codec.decodeOctetString_no_length() match // uper:460 >> octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << -codec.encodeConstraintWholeNumber(

nCount, , ) +codec.encodeConstrainedWholeNumber(

nCount, , ) if !codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) then ret = Left() >> @@ -528,7 +528,7 @@ codec.readBits(.asInstanceOf[Int]) match // uper:496 >> bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -codec.encodeConstraintWholeNumber(

nCount, , ) +codec.encodeConstrainedWholeNumber(

nCount, , ) >> @@ -549,7 +549,7 @@ FixedSize_Fragmentation_sqf_64K_encode(p, sAcc,sCurOffset, sCurBlockSize, sBlock var = 0 while( \< ) { - codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) + codec.encodeConstrainedWholeNumber(0xC4, 0, 0xFF) if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") @@ -570,7 +570,7 @@ while( \< ) FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize, sBlockId, sCurOffset, sCurBlockSize, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::=<< //encode Block = ; -codec.encodeConstraintWholeNumber(, 0, 0xFF) +codec.encodeConstrainedWholeNumber(, 0, 0xFF) if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") @@ -588,13 +588,13 @@ for(=(int); \< (int)( + ); < FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingItemsWithinByte, nRemainingItemsVar, sCurOffset, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::= << //encode remaining items -codec.encodeConstraintWholeNumber(, 0, 0xFF) +codec.encodeConstrainedWholeNumber(, 0, 0xFF) if !codec.appendBitOne() then Console.err.println("appendBitOne failed: not enough space for 1 bit") -codec.encodeConstraintWholeNumber(, 0, 0x7FFF) +codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) @@ -623,16 +623,16 @@ while ( >= 0x4000 && \< (a { if >= 0x10000 then = 0x10000 - codec.encodeConstraintWholeNumber(0xC4, 0, 0xFF) + codec.encodeConstrainedWholeNumber(0xC4, 0, 0xFF) else if >= 0xC000 then = 0xC000 - codec.encodeConstraintWholeNumber(0xC3, 0, 0xFF) + codec.encodeConstrainedWholeNumber(0xC3, 0, 0xFF) else if >= 0x8000 then = 0x8000 - codec.encodeConstraintWholeNumber(0xC2, 0, 0xFF) + codec.encodeConstrainedWholeNumber(0xC2, 0, 0xFF) else = 0x4000 - codec.encodeConstraintWholeNumber(0xC1, 0, 0xFF) + codec.encodeConstrainedWholeNumber(0xC1, 0, 0xFF) if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then @@ -652,12 +652,12 @@ while ( >= 0x4000 && \< (a } if \<= 0x7F then - codec.encodeConstraintWholeNumber(, 0, 0xFF) + codec.encodeConstrainedWholeNumber(, 0, 0xFF) else if !codec.appendBitOne() then Console.err.println("appendBitOne failed: not enough space for 1 bit") - codec.encodeConstraintWholeNumber(, 0, 0x7FFF) + codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index ccf313ed4..d00482580 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -193,7 +193,7 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } - def encodeConstraintWholeNumber(v: Long, min: Long, max: Long): Unit = { + def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) require(min <= v && v <= max) @@ -300,7 +300,7 @@ trait Codec { val nBytes: Int = GetLengthInBytesOfUInt((v - min)) /* encode length */ - encodeConstraintWholeNumber(nBytes.toLong, 0, 255) + encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) @@ -313,7 +313,7 @@ trait Codec { val nBytes: Int = GetLengthInBytesOfUInt(v - min) /* encode length */ - encodeConstraintWholeNumber(nBytes.toLong, 0, 255) + encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) @@ -366,12 +366,11 @@ trait Codec { return Some(v) } - def encodeUnConstraintWholeNumber(v: Long): Unit = { + def encodeUnconstrainedWholeNumber(v: Long): Unit = { val nBytes: Int = GetLengthInBytesOfSInt(v) /* encode length */ - encodeConstraintWholeNumber(nBytes.toLong, 0, 255) - /*8 bits, first bit is always 0*/ + encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) if v >= 0 then appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) @@ -422,34 +421,34 @@ trait Codec { // 8.5.2 Plus Zero if v == DoublePosZeroBitString then - encodeConstraintWholeNumber(0, 0, 0xFF) + encodeConstrainedWholeNumber(0, 0, 0xFF) return; // 8.5.3 Minus Zero if v == DoubleNegZeroBitString then - encodeConstraintWholeNumber(1, 0, 0xFF) - encodeConstraintWholeNumber(0x43, 0, 0xFF) + encodeConstrainedWholeNumber(1, 0, 0xFF) + encodeConstrainedWholeNumber(0x43, 0, 0xFF) return; - // 8.5.9 SpecialRealValues (2021 standard) + // 8.5.9 SpecialRealValues if (v & ExpoBitMask) == ExpoBitMask then // 8.5.9 PLUS-INFINITY if v == DoublePosInfBitString then - encodeConstraintWholeNumber(1, 0, 0xFF) - encodeConstraintWholeNumber(0x40, 0, 0xFF) + encodeConstrainedWholeNumber(1, 0, 0xFF) + encodeConstrainedWholeNumber(0x40, 0, 0xFF) return; // 8.5.9 MINUS-INFINITY else if v == DoubleNegInfBitString then - encodeConstraintWholeNumber(1, 0, 0xFF) - encodeConstraintWholeNumber(0x41, 0, 0xFF) + encodeConstrainedWholeNumber(1, 0, 0xFF) + encodeConstrainedWholeNumber(0x41, 0, 0xFF) return; // 8.5.9 NOT-A-NUMBER else - encodeConstraintWholeNumber(1, 0, 0xFF) - encodeConstraintWholeNumber(0x42, 0, 0xFF) + encodeConstrainedWholeNumber(1, 0, 0xFF) + encodeConstrainedWholeNumber(0x42, 0, 0xFF) return; // 8.5.6 a) @@ -480,10 +479,10 @@ trait Codec { header |= 0x02 /* encode length */ - encodeConstraintWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) + encodeConstrainedWholeNumber(1 + nExpLen + nManLen, 0, 0xFF) /* encode header */ - encodeConstraintWholeNumber(header & 0xFF, 0, 0xFF) + encodeConstrainedWholeNumber(header & 0xFF, 0, 0xFF) /* encode exponent */ if exponent >= 0 then @@ -633,16 +632,16 @@ trait Codec { decreases(nRemainingItemsVar1) if nRemainingItemsVar1 >= 0x10000 then nCurBlockSize1 = 0x10000 - encodeConstraintWholeNumber(0xC4, 0, 0xFF) + encodeConstrainedWholeNumber(0xC4, 0, 0xFF) else if nRemainingItemsVar1 >= 0xC000 then nCurBlockSize1 = 0xC000 - encodeConstraintWholeNumber(0xC3, 0, 0xFF) + encodeConstrainedWholeNumber(0xC3, 0, 0xFF) else if nRemainingItemsVar1 >= 0x8000 then nCurBlockSize1 = 0x8000 - encodeConstraintWholeNumber(0xC2, 0, 0xFF) + encodeConstrainedWholeNumber(0xC2, 0, 0xFF) else nCurBlockSize1 = 0x4000 - encodeConstraintWholeNumber(0xC1, 0, 0xFF) + encodeConstrainedWholeNumber(0xC1, 0, 0xFF) var i1: Int = nCurOffset1 while i1 < nCurBlockSize1 + nCurOffset1 do @@ -655,10 +654,10 @@ trait Codec { if ret then if nRemainingItemsVar1 <= 0x7F then - encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) + encodeConstrainedWholeNumber(nRemainingItemsVar1.toLong, 0, 0xFF) else appendBit(true) - encodeConstraintWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) + encodeConstrainedWholeNumber(nRemainingItemsVar1.toLong, 0, 0x7FFF) var i1: Int = nCurOffset1 @@ -763,7 +762,7 @@ trait Codec { if ret then if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then - encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) ret = encodeOctetString_no_length(arr, nCount) else @@ -796,7 +795,7 @@ trait Codec { def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then - encodeConstraintWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) + encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) appendBits(arr, nCount) @@ -809,17 +808,17 @@ trait Codec { if nRemainingItemsVar1 >= 0x10000 then nCurBlockSize1 = 0x10000 - encodeConstraintWholeNumber(0xC4, 0, 0xFF) + encodeConstrainedWholeNumber(0xC4, 0, 0xFF) else if nRemainingItemsVar1 >= 0xC000 then nCurBlockSize1 = 0xC000 - encodeConstraintWholeNumber(0xC3, 0, 0xFF) + encodeConstrainedWholeNumber(0xC3, 0, 0xFF) else if nRemainingItemsVar1 >= 0x8000 then nCurBlockSize1 = 0x8000 - encodeConstraintWholeNumber(0xC2, 0, 0xFF) + encodeConstrainedWholeNumber(0xC2, 0, 0xFF) else nCurBlockSize1 = 0x4000 - encodeConstraintWholeNumber(0xC1, 0, 0xFF) + encodeConstrainedWholeNumber(0xC1, 0, 0xFF) val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) appendBits(t, nCurBlockSize1.toInt) @@ -828,10 +827,10 @@ trait Codec { if nRemainingItemsVar1 <= 0x7F then - encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0xFF) + encodeConstrainedWholeNumber(nRemainingItemsVar1, 0, 0xFF) else appendBit(true) - encodeConstraintWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) + encodeConstrainedWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) appendBits(t, nRemainingItemsVar1.toInt) @@ -912,8 +911,9 @@ trait Codec { return NoneMut() } - def appendBitOne(): Boolean = { + require(bitStream.validate_offset_bit()) + val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -925,6 +925,8 @@ trait Codec { } def appendBitZero(): Boolean = { + require(bitStream.validate_offset_bit()) + val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -936,6 +938,8 @@ trait Codec { } def appendNBitZero(nBits: Long): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -947,6 +951,8 @@ trait Codec { } def appendNBitOne(nBits: Long): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -958,6 +964,8 @@ trait Codec { } def appendBits(srcBuffer: Array[UByte], nBits: Long): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -969,6 +977,8 @@ trait Codec { } def appendBit(v: Boolean): Boolean = { + require(bitStream.validate_offset_bit()) + val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -980,6 +990,8 @@ trait Codec { } def readBit(): Option[Boolean] = { + require(bitStream.validate_offset_bit()) + val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -990,6 +1002,8 @@ trait Codec { } def peekBit(): Option[Boolean] = { + require(bitStream.validate_offset_bit()) + val isValidPrecondition = bitStream.validate_offset_bits(1) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -1000,6 +1014,8 @@ trait Codec { } def appendByte(value: Byte): Boolean = { + require(bitStream.validate_offset_byte()) + val isValidPrecondition = bitStream.validate_offset_byte() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -1011,6 +1027,8 @@ trait Codec { } def readByte(): Option[UByte] = { + require(bitStream.validate_offset_byte()) + val isValidPrecondition = bitStream.validate_offset_byte() stainlessAssert(isValidPrecondition) assert(isValidPrecondition) @@ -1020,51 +1038,57 @@ trait Codec { case false => None() } - def appendByteArray(arr: Array[UByte], arr_len: Int): Boolean = { - val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { + val isValidPrecondition = bitStream.validate_offset_bytes(noOfBytes) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then - bitStream.appendByteArray(arr, arr_len) + bitStream.appendByteArray(arr, noOfBytes) isValidPrecondition } - def readByteArray(arr_len: Int): OptionMut[Array[UByte]] = { - val isValidPrecondition = bitStream.validate_offset_bytes(arr_len) + def readByteArray(nBytes: Int): OptionMut[Array[UByte]] = { + require(nBytes >= 0 && nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) + require(bitStream.validate_offset_bytes(nBytes)) + + val isValidPrecondition = bitStream.validate_offset_bytes(nBytes) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) isValidPrecondition match - case true => SomeMut(bitStream.readByteArray(arr_len)) + case true => SomeMut(bitStream.readByteArray(nBytes)) case false => NoneMut() } - def readBits(nbits: Long): OptionMut[Array[UByte]] = { - val isValidPrecondition = bitStream.validate_offset_bits(nbits) + def readBits(nBits: Long): OptionMut[Array[UByte]] = { + require(nBits >= 0 && bitStream.validate_offset_bits(nBits)) + + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) isValidPrecondition match - case true => SomeMut(bitStream.readBits(nbits)) + case true => SomeMut(bitStream.readBits(nBits)) case false => NoneMut() } - def appendPartialByte(vVal: UByte, nbits: UByte): Boolean = { - val isValidPrecondition = bitStream.validate_offset_bits(nbits) + def appendPartialByte(vVal: UByte, nBits: UByte): Boolean = { + val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) assert(isValidPrecondition) if isValidPrecondition then - bitStream.appendPartialByte(vVal, nbits) + bitStream.appendPartialByte(vVal, nBits) isValidPrecondition } def readPartialByte(nBits: Int): Option[UByte] = { require(nBits >= 0 && nBits <= NO_OF_BITS_IN_BYTE) + require(bitStream.validate_offset_bits(nBits)) val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 31f0aff9a..cd30b7bba 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -830,7 +830,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_Ascii_Internal_Field_Determinant(max: Long, min: Long, strVal: Array[ASCIIChar]): Unit = { val strLen: Int = strVal.length - encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstrainedWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_Ascii_private(max, strVal) } @@ -838,7 +838,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while i < max do val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - encodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + encodeConstrainedWholeNumber(charIndex, 0, allowedCharSet.length - 1) i += 1 } @@ -846,7 +846,7 @@ case class ACN(bitStream: BitStream) extends Codec { var i: Int = 0 while (i < max) && (strVal(i) != CHAR_0000) do val charIndex: Int = GetCharIndex(strVal(i), allowedCharSet) - encodeConstraintWholeNumber(charIndex, 0, allowedCharSet.length - 1) + encodeConstrainedWholeNumber(charIndex, 0, allowedCharSet.length - 1) i += 1 i @@ -859,7 +859,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[Byte], min: Long, strVal: Array[ASCIIChar]): Unit = { val strLen: Int = strVal.length - encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstrainedWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_CharIndex_private(max, allowedCharSet, strVal) } @@ -901,7 +901,7 @@ case class ACN(bitStream: BitStream) extends Codec { 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) val strLen: Int = strVal.length - encodeConstraintWholeNumber(if strLen <= max then strLen else max, min, max) + encodeConstrainedWholeNumber(if strLen <= max then strLen else max, min, max) enc_String_CharIndex_private(max, allowedCharSet, strVal) } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 27158413a..25177b996 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -55,10 +55,10 @@ case class UPER(bitStream: BitStream) extends Codec { i += 1 if totalSize <= 0x7F then - encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + encodeConstrainedWholeNumber(totalSize.toLong, 0, 0xFF) else appendBit(true) - encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + encodeConstrainedWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do @@ -82,10 +82,10 @@ case class UPER(bitStream: BitStream) extends Codec { if totalSize <= 0x7F then - encodeConstraintWholeNumber(totalSize.toLong, 0, 0xFF) + encodeConstrainedWholeNumber(totalSize.toLong, 0, 0xFF) else appendBit(true) - encodeConstraintWholeNumber(totalSize.toLong, 0, 0x7FFF) + encodeConstrainedWholeNumber(totalSize.toLong, 0, 0x7FFF) i = 0 while i < totalSize do From 545ecc69d0bb8b339e7a029e7ac2d36bd77215f5 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 15 Dec 2023 22:08:09 +0100 Subject: [PATCH 119/174] adapt scala atc to C --- StgScala/test_cases_scala.stg | 3 ++- .../src/main/scala/asn1scala/asn1jvm_Bitstream.scala | 2 +- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 10 ++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 3140c4c74..436755c6a 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -99,8 +99,9 @@ Codec_write_bitstreamToFile() ::= << // test_cases_scala.stg:99 val file = new File(filename+".dat") val bw = new FileOutputStream(file) +val l = codec.getLength codec.resetBitIndex() -codec.readByteArray(codec.getBufferLength) match +codec.readByteArray(l) match case SomeMut(arr) => bw.write(arr) case NoneMut() => return Left(5) bw.close() diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index d050d1b4b..d8e75f9f0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -144,7 +144,7 @@ case class BitStream( * Currentbyte = 14, currentBit = 0 --> 14 * */ - def getLength(): Int = { + def getLength: Int = { var ret: Int = currentByte if currentBit > 0 then ret += 1 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index d00482580..ea068a24e 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -1152,4 +1152,14 @@ trait Codec { def getBufferLength: Int = { bitStream.getBufferLength } + + /** + * + * @return the number of used bytes in the underlying buffer + * if the currentBit is not 0, currentByte is added by 1 + * + */ + def getLength: Int = { + bitStream.getLength + } } From 2c56ca307985802d1593455104dbd5f66e020a58 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 18 Dec 2023 18:12:05 +0100 Subject: [PATCH 120/174] fix according to 8.3 --- .../main/scala/asn1scala/asn1jvm_Codec.scala | 67 ++++++++-- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 4 +- .../main/scala/asn1scala/asn1jvm_Helper.scala | 124 ++++++++++++++---- 3 files changed, 150 insertions(+), 45 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index ea068a24e..5ba78c55d 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -297,7 +297,7 @@ trait Codec { def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt((v - min)) + val nBytes: Int = GetLengthForEncodingUnsigned((v - min)) /* encode length */ encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) @@ -310,7 +310,7 @@ trait Codec { def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { assert(v >= min) - val nBytes: Int = GetLengthInBytesOfUInt(v - min) + val nBytes: Int = GetLengthForEncodingUnsigned(v - min) /* encode length */ encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) @@ -366,20 +366,33 @@ trait Codec { return Some(v) } + /** + * 8.3 Encoding of an integer value + * + * The encoding of an integer value shall be primitive. + * The contents octets shall consist of one or more octets. + * + * @param v The value that is always encoded in the smallest possible number of octets. + */ + def encodeUnconstrainedWholeNumber(v: Long): Unit = { - val nBytes: Int = GetLengthInBytesOfSInt(v) + require(bitStream.validate_offset_bytes(1 + GetLengthForEncodingSigned(v))) - /* encode length */ - encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) + // call func that fulfills 8.3.2 + val nBytes: Int = GetLengthForEncodingSigned(v) - if v >= 0 then - appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v)) - encodeNonNegativeInteger(v) - else - appendNBitOne(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((-v - 1))) - encodeNonNegativeIntegerNeg((-v - 1)) - } + // encode length - single octet + appendByte(nBytes.toByte) + var i = nBytes; + (while i > 0 do + decreases(i) + + appendByte((v >>> ((i - 1) * NO_OF_BITS_IN_BYTE)).toUnsignedByte) + + i -= 1 + ).invariant(i >= 0 && i <= nBytes) + } def decodeUnConstraintWholeNumber(): Option[Long] = { @@ -414,6 +427,32 @@ trait Codec { encodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) } + /** + * Binary encoding will be used + * REAL = M*B^E + * where + * M = S*N*2^F + * + * ENCODING is done within three parts + * part 1 is 1 byte header + * part 2 is 1 or more byte for exponent + * part 3 is 3 or more byte for mantissa (N) + * + * First byte + * S :0-->+, S:1-->-1 + * Base will be always be 2 (implied by 6th and 5th bit which are zero) + * ab: F (0..3) + * cd:00 --> 1 byte for exponent as 2's complement + * cd:01 --> 2 byte for exponent as 2's complement + * cd:10 --> 3 byte for exponent as 2's complement + * cd:11 --> 1 byte for encoding the length of the exponent, then the exponent + * + * 8 7 6 5 4 3 2 1 + * +-+-+-+-+-+-+-+-+ + * |1|S|0|0|a|b|c|d| + * +-+-+-+-+-+-+-+-+ + * + */ private def encodeRealBitString(vVal: Long): Unit = { // according to T-REC-X.690 2021 @@ -465,11 +504,11 @@ trait Codec { val (exponent, mantissa) = CalculateMantissaAndExponent(v) - val nManLen: Int = GetLengthInBytesOfUInt(mantissa) + val nManLen: Int = GetLengthForEncodingUnsigned(mantissa) assert(nManLen <= 7) // 52 bit val compactExp = RemoveLeadingFFBytesIfNegative(exponent) - val nExpLen: Int = GetLengthInBytesOfUInt(compactExp) + val nExpLen: Int = GetLengthForEncodingUnsigned(compactExp) assert(nExpLen >= 1 && nExpLen <= 2) // 8.5.7.4 diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index cd30b7bba..71a03bf53 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -170,7 +170,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { - val nBytes: Byte = GetLengthInBytesOfUInt(intVal).toByte + val nBytes: Byte = GetLengthForEncodingUnsigned(intVal).toByte /* encode length */ appendByte(nBytes) @@ -308,7 +308,7 @@ case class ACN(bitStream: BitStream) extends Codec { def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { - val nBytes: Byte = GetLengthInBytesOfSInt(intVal).toByte + val nBytes: Byte = GetLengthForEncodingSigned(intVal).toByte /* encode length */ appendByte(nBytes) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index ce8206be5..b52cc88c4 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -79,6 +79,15 @@ extension (l: Long) { else l.toInt } + + def toUnsignedByte: UByte = { + if ((l & MASK_BYTE) == MASK_MSB_BYTE) + (-MASK_MSB_BYTE).toByte + else if ((l & MASK_MSB_BYTE) == MASK_MSB_BYTE) + ((l & MASK_POS_BYTE) - MASK_MSB_BYTE).toByte + else + (l & MASK_BYTE).toByte + } } def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { @@ -117,39 +126,96 @@ def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { 32 + GetNumberOfBitsForNonNegativeInteger32(h) }.ensuring(n => n >= 0 && n <= 64) -def GetLengthInBytesOfUInt (v: ULong): Int = { - GetLengthInBytesOfSInt(v) // just call signed, is signed anyway -}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) - -def GetLengthInBytesOfSInt (v: Long): Int = { +def GetLengthForEncodingUnsigned(v: ULong): Int = { max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte }.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) /** -Binary encoding will be used -REAL = M*B^E -where -M = S*N*2^F - -ENCODING is done within three parts -part 1 is 1 byte header -part 2 is 1 or more byte for exponent -part 3 is 3 or more byte for mantissa (N) - -First byte -S :0-->+, S:1-->-1 -Base will be always be 2 (implied by 6th and 5th bit which are zero) -ab: F (0..3) -cd:00 --> 1 byte for exponent as 2's complement -cd:01 --> 2 byte for exponent as 2's complement -cd:10 --> 3 byte for exponent as 2's complement -cd:11 --> 1 byte for encoding the length of the exponent, then the exponent - -8 7 6 5 4 3 2 1 -+-+-+-+-+-+-+-+-+ -|1|S|0|0|a|b|c|d| -+-+-+-+-+-+-+-+-+ - **/ + * Get the amount of set bits in the given 64bit number v + * + * @param v input + * @return Amount of set bits in v + */ +@extern +private def popCountL(v: Long): Int = { + Integer.bitCount((v >>> 32).toUnsignedInt) + Integer.bitCount((v & 0xFF_FF_FF_FFL).toUnsignedInt) +} + +/** + * Get number of bytes needed to encode the + * positive number v according to PER rules (8.3) + * + * Example: + * v = 12d = 0b0000'0...0'0000'1100b + * According to 8.3.3 Leading zeros do not have to be + * serialised, hence just send a single octet (0000'1100) + * + * @param v value that should get serialised + * @return number of bytes needed for serialisation + */ +def GetBytesNeededForPositiveNumber(v: Long): Int = { + require(v >= 0) + + v match + case x if x < (1L << 7) => 1 + case x if x < (1L << 15) => 2 + case x if x < (1L << 23) => 3 + case x if x < (1L << 31) => 4 + case x if x < (1L << 39) => 5 + case x if x < (1L << 47) => 6 + case x if x < (1L << 55) => 7 + case _ => 8 + +}.ensuring(n => + n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG &&& + n == NO_OF_BYTES_IN_JVM_LONG || (1L << (NO_OF_BITS_IN_BYTE * n - 1) > v) +) + +/** + * Get number of bytes needed to encode the + * negative number v according to PER rules (8.3) + * + * Example: + * v = -1d = 0b1111'1...1'1111'1111b + * According to 8.3.3 Leading ones do not have to be + * serialised, hence just send a single octet (1111'1111) + * + * @param v value that should get serialised + * @return number of bytes needed for serialisation + */ +def GetBytesNeededForNegativeNumber(v: Long): Int = { + require(v < 0) + + v match + case x if x >= 0xFFFF_FFFF_FFFF_FF80L => 1 + case x if x >= 0xFFFF_FFFF_FFFF_8000L => 2 + case x if x >= 0xFFFF_FFFF_FF80_0000L => 3 + case x if x >= 0xFFFF_FFFF_8000_0000L => 4 + case x if x >= 0xFFFF_FF80_0000_0000L => 5 + case x if x >= 0xFFFF_8000_0000_0000L => 6 + case x if x >= 0xFF80_0000_0000_0000L => 7 + case _ => 8 + +}.ensuring( + n => { + val pre = n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG + val mask = 0xFFFF_FFFF_FFFF_FFFFL << (NO_OF_BITS_IN_BYTE * n) + pre &&& (n == NO_OF_BYTES_IN_JVM_LONG || (NO_OF_BITS_IN_BYTE - n) * NO_OF_BITS_IN_BYTE == popCountL(v & mask)) + }) + +/** + * Get number of bytes needed to encode the + * number v according to the PER rules (8.3) + * + * @param v signed value that should get serialised + * @return number of bytes needed for serialisation + */ +def GetLengthForEncodingSigned(v: Long): Int = { + if v >= 0 then + GetBytesNeededForPositiveNumber(v) + else + GetBytesNeededForNegativeNumber(v) +}.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) def CalculateMantissaAndExponent(doubleAsLong64: Long): (UInt, ULong) = { require({ From 49bda6e20e1298f343ffca1d6de22dad6f94f814 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 18 Dec 2023 18:35:57 +0100 Subject: [PATCH 121/174] decode unconstrained whole number vcs --- .../main/scala/asn1scala/asn1jvm_Codec.scala | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 5ba78c55d..67816c688 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -394,23 +394,31 @@ trait Codec { ).invariant(i >= 0 && i <= nBytes) } - def decodeUnConstraintWholeNumber(): Option[Long] = { - var nBytes: Long = 0 + /** + * 8.3 Encoding of an integer value reverse OP + * + * To call this func at least 2 octets have to be available on the bitstream + * The length n is the first octet, n octets with the value follow + * Values with n > 8 are not supported + * + * @return decoded number + */ + def decodeUnconstrainedWholeNumber(): Option[Long] = { + require(bitStream.validate_offset_bytes(2)) - decodeConstraintWholeNumber(0, 255) match + val nBytes = readByte() match case None() => return None() - case Some(l) => nBytes = l + case Some(b) => b - val valIsNegative = false - peekBit() match + val valIsNegative = peekBit() match case Some(b) => b case None() => assert(false) - var v: Long = if valIsNegative then Long.MaxValue else 0 + var v: Long = if valIsNegative then -1 else 0 - var i: Long = 0 - while i < nBytes do + var i = 0 + (while i < nBytes do decreases(nBytes - i) readByte() match @@ -418,8 +426,9 @@ trait Codec { case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong i += 1 + ).invariant(i >= 0 && i<= nBytes) - return Some(v) + Some(v) } @extern From aa9ae2ac683e6bec6366b1b267fa1e3c5713dcce Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 18 Dec 2023 18:40:02 +0100 Subject: [PATCH 122/174] removed useless assertion --- asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 67816c688..e0bd9515f 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -402,7 +402,7 @@ trait Codec { * The length n is the first octet, n octets with the value follow * Values with n > 8 are not supported * - * @return decoded number + * @return decoded number */ def decodeUnconstrainedWholeNumber(): Option[Long] = { require(bitStream.validate_offset_bytes(2)) @@ -413,7 +413,7 @@ trait Codec { val valIsNegative = peekBit() match case Some(b) => b - case None() => assert(false) + case None() => return None() var v: Long = if valIsNegative then -1 else 0 From e4c1edf1f1281ccfcb9345afc2bf30ea0faaffa3 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 22 Dec 2023 17:34:20 +0100 Subject: [PATCH 123/174] first idea --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 66 ++++++++- .../main/scala/asn1scala/asn1jvm_Codec.scala | 132 +++++++++++++----- .../main/scala/asn1scala/asn1jvm_Helper.scala | 5 + 3 files changed, 167 insertions(+), 36 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index d8e75f9f0..99891a841 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -271,6 +271,70 @@ case class BitStream( }.ensuring(_ => buf.length == old(this).buf.length && remainingBits == old(this).remainingBits - 1) + /** + * Append nBits from the 64bit Integer value v to the bitstream + * + * @param v source of the bits + * @param nBits number of bits to add + * + * Remarks: + * bit 0 is the LSB of v + */ + def appendBitsLSBFirst(v: Long, nBits: Int): Unit = { + require(nBits >= 0 && nBits <= NO_OF_BITS_IN_LONG) + require(validate_offset_bits(nBits)) + +// @ghost val oldThis = snapshot(this) + var i = 0 + (while i < nBits do + decreases(nBits - i) + + val ii = v & (1L << i) + val b = ii != 0 + + appendBit(b) + + i += 1 + ).invariant(i >= 0 && i <= nBits &&& validate_offset_bits(nBits - i)) + } + + /** + * Append nBits from the 64bit Integer value v to the bitstream + * + * @param v source of the bits + * @param nBits number of bits to add + * + * Remarks: + * the first bit added to the bitstream is the highest significant bit + * defined by nBits. + * + * Example: + * nBits = 25 + * + * MSB first added bit LSB + * v v v + * 64----------------24--------------0 + * + * After bit 24, bit 23 and so on get added + * + */ + def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Unit = { + require(nBits >= 0 && nBits <= NO_OF_BITS_IN_LONG) + require(validate_offset_bits(nBits)) + + var i = nBits + (while i >= 0 do + decreases(i) + + val ii = v & (1L << i) + val b = ii != 0 + + appendBit(b) + + i -= 1 + ).invariant(i >= -1 && i <= nBits &&& validate_offset_bits(i)) + } + /** * Append nBits from srcBuffer to bitstream * @@ -281,7 +345,7 @@ case class BitStream( * bit 0 is the MSB of the first byte of srcBuffer * */ - def appendBits(srcBuffer: Array[UByte], nBits: Long): Unit = { + def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Unit = { require(nBits >= 0 && (nBits / 8) < srcBuffer.length) require(validate_offset_bits(nBits)) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index e0bd9515f..9ec917196 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -22,7 +22,6 @@ val CHAR_ZERO: ASCIIChar = 48 val CHAR_NINE: ASCIIChar = 57 val CHAR_0000: ASCIIChar = 0 - /***********************************************************************************************/ /** Byte Stream Functions **/ /***********************************************************************************************/ @@ -30,6 +29,12 @@ def ByteStream_Init(count: Int): ByteStream = { ByteStream(Array.fill(count)(0), 0, false) } +@extern +def runtimeAssert(condition: Boolean, s: String =""): Unit = assert(condition, s) + +@extern +def writeToStdErr(s: String): Unit = Console.err.println(s) + @extern def ByteStream_AttachBuffer(pStrm: ByteStream, buf: Array[UByte]): Unit = { pStrm.buf = buf // Illegal aliasing, therefore we need to workaround with this @extern... @@ -195,16 +200,36 @@ trait Codec { def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) + require( + min >= 0 && max >= 0 || + min < 0 && max < 0 || + min <= (Long.MaxValue >> 1) && max <= min + (Long.MaxValue >> 1) + ) require(min <= v && v <= max) val range = max - min if range == 0 then return + // get number of bits that get written val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger((v - min)) - appendNBitZero(nRangeBits - nBits); - encodeNonNegativeInteger((v - min)) + stainlessAssert(bitStream.validate_offset_bits(nRangeBits)) + + val encVal = v - min + stainlessAssert(encVal >= 0) + +// @ghost + val nEncValBits = GetNumberOfBitsForNonNegativeInteger(encVal) + stainlessAssert(nRangeBits >= nEncValBits) + + val done = bitStream.appendBitsNBitFirstToLSB(encVal, nRangeBits-1) + //if !done then + // writeToStdErr("precondition for appendBitsLSBFirst not met") + +// val nBits: Int = GetNumberOfBitsForNonNegativeInteger(encodeVal) + +// appendNBitZero(nRangeBits - nEncValBits); +// encodeNonNegativeInteger((v - min)) } def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { @@ -215,6 +240,7 @@ trait Codec { val range: ULong = (max - min) if range == 0 then return + val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) appendNBitZero(nRangeBits - nBits) @@ -222,11 +248,14 @@ trait Codec { } def decodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { + require(min <= max) + require( + min >= 0 && max >= 0 || + min < 0 && max < 0 || + min <= (Long.MaxValue >> 1) && max <= min + (Long.MaxValue >> 1) + ) - val range: ULong = (max - min) - - // ASSERT_OR_RETURN_FALSE(min <= max); - + val range: ULong = max - min if range == 0 then return Some(min) @@ -374,7 +403,6 @@ trait Codec { * * @param v The value that is always encoded in the smallest possible number of octets. */ - def encodeUnconstrainedWholeNumber(v: Long): Unit = { require(bitStream.validate_offset_bytes(1 + GetLengthForEncodingSigned(v))) @@ -394,7 +422,6 @@ trait Codec { ).invariant(i >= 0 && i <= nBytes) } - /** * 8.3 Encoding of an integer value reverse OP * @@ -431,6 +458,10 @@ trait Codec { Some(v) } + /** + * Facade function for real encoding + * @param vVal real input in IEEE754 double format + */ @extern def encodeReal(vVal: Double): Unit = { encodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) @@ -514,11 +545,11 @@ trait Codec { val (exponent, mantissa) = CalculateMantissaAndExponent(v) val nManLen: Int = GetLengthForEncodingUnsigned(mantissa) - assert(nManLen <= 7) // 52 bit + runtimeAssert(nManLen <= 7) // 52 bit val compactExp = RemoveLeadingFFBytesIfNegative(exponent) val nExpLen: Int = GetLengthForEncodingUnsigned(compactExp) - assert(nExpLen >= 1 && nExpLen <= 2) + runtimeAssert(nExpLen >= 1 && nExpLen <= 2) // 8.5.7.4 if nExpLen == 2 then @@ -545,6 +576,10 @@ trait Codec { encodeNonNegativeInteger(mantissa) } + /** + * facade function for real decoding + * @return decoded real value in IE754 double format + */ @extern def decodeReal(): Option[Double] = { decodeRealBitString() match @@ -554,6 +589,11 @@ trait Codec { Some(java.lang.Double.longBitsToDouble(ll)) } + + /** + * Real decoding implementation according to the PER standard + * @return decoded double bits as 64 bit integer + */ private def decodeRealBitString(): Option[Long] = { readByte() match case None() => None() @@ -594,6 +634,15 @@ trait Codec { decodeRealFromBitStream(length.toInt - 1, header) } + /** + * Decode real number from bitstream, special cases are decoded by caller + * The exponent length and other details given in the header have be be + * decoded before calling this function + * + * @param lengthVal already decoded exponent length + * @param header already decoded header + * @return decoded real number as 64bit integer + */ private def decodeRealFromBitStream(lengthVal: Int, header: UByte): Option[Long] = { require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) @@ -619,7 +668,7 @@ trait Codec { var expIsNegative = false peekBit() match case Some(b) => expIsNegative = b - case None() => assert(false) + case None() => runtimeAssert(false) var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 @@ -845,7 +894,7 @@ trait Codec { if asn1SizeMin != asn1SizeMax then encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - appendBits(arr, nCount) + appendBitsMSBFirst(arr, nCount) else var nRemainingItemsVar1: Long = nCount.toLong @@ -869,7 +918,7 @@ trait Codec { encodeConstrainedWholeNumber(0xC1, 0, 0xFF) val t: Array[UByte] = Array.fill(nCurBlockSize1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nCurBlockSize1.toInt) - appendBits(t, nCurBlockSize1.toInt) + appendBitsMSBFirst(t, nCurBlockSize1.toInt) nCurOffset1 += nCurBlockSize1 nRemainingItemsVar1 -= nCurBlockSize1 @@ -881,7 +930,7 @@ trait Codec { encodeConstrainedWholeNumber(nRemainingItemsVar1, 0, 0x7FFF) val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) - appendBits(t, nRemainingItemsVar1.toInt) + appendBitsMSBFirst(t, nRemainingItemsVar1.toInt) true } @@ -964,7 +1013,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendBitOne() @@ -977,7 +1026,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendBitZero() @@ -990,7 +1039,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendNBitZero(nBits) @@ -1003,7 +1052,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendNBitOne(nBits) @@ -1011,15 +1060,28 @@ trait Codec { isValidPrecondition } - def appendBits(srcBuffer: Array[UByte], nBits: Long): Boolean = { + def appendBitsLSBFirst(v: Long, nBits: Int): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) + runtimeAssert(isValidPrecondition) + + if isValidPrecondition then + bitStream.appendBitsLSBFirst(v, nBits) + + isValidPrecondition + } + + def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Boolean = { require(bitStream.validate_offset_bits(nBits)) val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then - bitStream.appendBits(srcBuffer, nBits) + bitStream.appendBitsMSBFirst(srcBuffer, nBits) isValidPrecondition } @@ -1029,7 +1091,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendBit(v) @@ -1042,7 +1104,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bit() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => Some(bitStream.readBit()) @@ -1054,7 +1116,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(1) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => Some(bitStream.peekBit()) @@ -1066,7 +1128,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_byte() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendByte(value) @@ -1079,7 +1141,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_byte() stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => Some(bitStream.readByte()) @@ -1089,7 +1151,7 @@ trait Codec { def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { val isValidPrecondition = bitStream.validate_offset_bytes(noOfBytes) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendByteArray(arr, noOfBytes) @@ -1104,7 +1166,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bytes(nBytes) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => SomeMut(bitStream.readByteArray(nBytes)) @@ -1116,7 +1178,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => SomeMut(bitStream.readBits(nBits)) @@ -1126,7 +1188,7 @@ trait Codec { def appendPartialByte(vVal: UByte, nBits: UByte): Boolean = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.appendPartialByte(vVal, nBits) @@ -1140,7 +1202,7 @@ trait Codec { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => Some(bitStream.readPartialByte(nBits)) @@ -1150,7 +1212,7 @@ trait Codec { def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Option[Boolean] = { val isValidPrecondition = bitStream.validate_offset_bits(nBits) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) isValidPrecondition match case true => Some(bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits)) @@ -1171,7 +1233,7 @@ trait Codec { NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE) ) stainlessAssert(isValidPrecondition) - assert(isValidPrecondition) + runtimeAssert(isValidPrecondition) if isValidPrecondition then bitStream.alignToByte() diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index b52cc88c4..9e9c19da5 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -88,6 +88,11 @@ extension (l: Long) { else (l & MASK_BYTE).toByte } + + @extern + def toByteArray: Array[Byte] = { + scala.math.BigInt(l).toByteArray + } } def GetNumberOfBitsInUpperBytesAndDecreaseValToLastByte(v: UInt): (UInt, Int) = { From 0699398d80e138d0efad6dbdb0cc32f17d013436 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 22 Dec 2023 20:09:47 +0100 Subject: [PATCH 124/174] fixed some VCs --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 4 +-- .../main/scala/asn1scala/asn1jvm_Codec.scala | 31 ++++++++++++------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 99891a841..7199afbd6 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -322,7 +322,7 @@ case class BitStream( require(nBits >= 0 && nBits <= NO_OF_BITS_IN_LONG) require(validate_offset_bits(nBits)) - var i = nBits + var i = nBits - 1 (while i >= 0 do decreases(i) @@ -332,7 +332,7 @@ case class BitStream( appendBit(b) i -= 1 - ).invariant(i >= -1 && i <= nBits &&& validate_offset_bits(i)) + ).invariant(i >= -1 && i <= nBits &&& validate_offset_bits(i+1)) } /** diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 9ec917196..7f48f45b2 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -213,23 +213,17 @@ trait Codec { // get number of bits that get written val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - stainlessAssert(bitStream.validate_offset_bits(nRangeBits)) + // get value that gets written val encVal = v - min stainlessAssert(encVal >= 0) -// @ghost - val nEncValBits = GetNumberOfBitsForNonNegativeInteger(encVal) + @ghost val nEncValBits = GetNumberOfBitsForNonNegativeInteger(encVal) stainlessAssert(nRangeBits >= nEncValBits) - val done = bitStream.appendBitsNBitFirstToLSB(encVal, nRangeBits-1) - //if !done then - // writeToStdErr("precondition for appendBitsLSBFirst not met") - -// val nBits: Int = GetNumberOfBitsForNonNegativeInteger(encodeVal) - -// appendNBitZero(nRangeBits - nEncValBits); -// encodeNonNegativeInteger((v - min)) + val done = appendBitsNBitFirstToLSB(encVal, nRangeBits) + if !done then + writeToStdErr("precondition for appendBitsLSBFirst not met") } def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { @@ -1060,7 +1054,7 @@ trait Codec { isValidPrecondition } - def appendBitsLSBFirst(v: Long, nBits: Int): Boolean = { + def appendBitsLSBFirst(v: Long, nBits: Int): Boolean = { // TODO remove if never used require(bitStream.validate_offset_bits(nBits)) val isValidPrecondition = bitStream.validate_offset_bits(nBits) @@ -1073,6 +1067,19 @@ trait Codec { isValidPrecondition } + def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) + runtimeAssert(isValidPrecondition) + + if isValidPrecondition then + bitStream.appendBitsNBitFirstToLSB(v, nBits) + + isValidPrecondition + } + def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Boolean = { require(bitStream.validate_offset_bits(nBits)) From 5ca2f3e39c5862431d2058595f0316a7548344a5 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 8 Jan 2024 15:35:51 +0100 Subject: [PATCH 125/174] fixed renaming meths in templates --- StgScala/acn_scala.stg | 40 ++++++++++++++++++++-------------------- StgScala/uper_scala.stg | 28 ++++++++++++++-------------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index f7b3ee462..743a1c166 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -345,8 +345,8 @@ Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse { var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - if !codec.appendBits(if

then true_data else false_data, ) then - Console.err.println("appendBits failed: not enough space for bits") + if !codec.appendBitsMSBFirst(if

then true_data else false_data, ) then + Console.err.println("appendBitsMSBFirst failed: not enough space for bits") } >> @@ -372,8 +372,8 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - if !codec.appendBits(tmp, ) then - Console.err.println("appendBits failed: not enough space for bits") + if !codec.appendBitsMSBFirst(tmp, ) then + Console.err.println("appendBitsMSBFirst failed: not enough space for bits") } @@ -574,8 +574,8 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -if !codec.appendBits(Array({}), ) then - Console.err.println("appendBits failed: not enough space for bits") +if !codec.appendBitsMSBFirst(Array({}), ) then + Console.err.println("appendBitsMSBFirst failed: not enough space for bits") >> @@ -602,8 +602,8 @@ if (ret && checkBitPatternPresentResult.isEmpty) { >> bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if !codec.appendBits(

arr,

nCount) then - Console.err.println(s"appendBits failed: not enough space for ${

nCount} bits") +if !codec.appendBitsMSBFirst(

arr,

nCount) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${

nCount} bits") >> @@ -618,8 +618,8 @@ if (\<=) && (\<=) t >> bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if !codec.appendBits(

arr, ) then - Console.err.println("appendBits failed: not enough space for bits") +if !codec.appendBitsMSBFirst(

arr, ) then + Console.err.println("appendBitsMSBFirst failed: not enough space for bits") >> @@ -633,12 +633,12 @@ if (\<=) && (\<=) t >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -if !codec.appendBits(

arr,

arr.length*8) then // TODO: re-introduce nCount? -> codec.appendBits(

arr,

nCount) - Console.err.println(s"appendBits failed: not enough space for ${

arr.length*8} bits") +if !codec.appendBitsMSBFirst(

arr,

arr.length*8) then // TODO: re-introduce nCount? -> codec.appendBitsMSBFirst(

arr,

nCount) + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${

arr.length*8} bits") -if !codec.appendBits(Array({}), ) then - Console.err.println(s"appendBits failed: not enough space for bits") +if !codec.appendBitsMSBFirst(Array({}), ) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for bits") >> @@ -1069,8 +1069,8 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -if !codec.appendBits(arr, .asInstanceOf[Int]) - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") +if !codec.appendBitsMSBFirst(arr, .asInstanceOf[Int]) + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") >> @@ -1166,13 +1166,13 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit if ret.isRight then val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - if !codec.appendBits(bitStrm.buf, nCount) then - Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") + if !codec.appendBitsMSBFirst(bitStrm.buf, nCount) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${nCount} bits") codec.encodeConstrainedWholeNumber(nCount, , ) - if !codec.appendBits(bitStrm.buf, nCount) then - Console.err.println(s"appendBits failed: not enough space for ${nCount} bits") + if !codec.appendBitsMSBFirst(bitStrm.buf, nCount) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${nCount} bits") } diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index a251dbee9..426d4ce33 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -149,7 +149,7 @@ codec.decodeConstraintPosWholeNumber(, ) match // uper:135 /*case: A :: = INTEGER */ IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -codec.decodeUnConstraintWholeNumber() match // uper:145 +codec.decodeUnconstrainedWholeNumber() match // uper:145 case Some(x) =>

= x case None() => @@ -159,7 +159,7 @@ codec.decodeUnConstraintWholeNumber() match // uper:145 /*case: A :: = INTEGER(MIN..5) */ IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << -if !codec.decodeUnConstraintWholeNumber() then +if !codec.decodeUnconstrainedWholeNumber() then ret = if then 0 else >> @@ -515,8 +515,8 @@ codec.decodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // up /* BIT STRING*/ bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast -if !codec.appendBits(

arr, .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") +if !codec.appendBitsMSBFirst(

arr, .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") >> bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << @@ -551,8 +551,8 @@ while( \< ) { codec.encodeConstrainedWholeNumber(0xC4, 0, 0xFF) - if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + if !codec.appendBitsMSBFirst(&

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") val =(int) @@ -572,8 +572,8 @@ FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize = ; codec.encodeConstrainedWholeNumber(, 0, 0xFF) -if !codec.appendBits(&

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") +if !codec.appendBitsMSBFirst(&

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") for(=(int); \< (int)( + ); ++) @@ -598,8 +598,8 @@ codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) -if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${asInstanceOf[Int]} bits") +if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${asInstanceOf[Int]} bits") for(=(int); \< (int)( + ); ++) @@ -635,8 +635,8 @@ while ( >= 0x4000 && \< (a codec.encodeConstrainedWholeNumber(0xC1, 0, 0xFF) - if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") + if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") =.asInstanceOf[Int] @@ -660,8 +660,8 @@ else codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) -if !codec.appendBits(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBits failed: not enough space for ${.asInstanceOf[Int]} bits") +if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then + Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") = .asInstanceOf[Int] From 2b9d74d7e6fa4d07c15356c95e6150df7bc53410 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 8 Jan 2024 17:48:29 +0100 Subject: [PATCH 126/174] fixed VC in GetBytesNeededForNegativeNumber --- .../src/main/scala/asn1scala/asn1jvm_Helper.scala | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index 9e9c19da5..85d76eb26 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -199,13 +199,22 @@ def GetBytesNeededForNegativeNumber(v: Long): Int = { case x if x >= 0xFFFF_FF80_0000_0000L => 5 case x if x >= 0xFFFF_8000_0000_0000L => 6 case x if x >= 0xFF80_0000_0000_0000L => 7 - case _ => 8 + case _ => NO_OF_BYTES_IN_JVM_LONG // 8 }.ensuring( n => { val pre = n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG - val mask = 0xFFFF_FFFF_FFFF_FFFFL << (NO_OF_BITS_IN_BYTE * n) - pre &&& (n == NO_OF_BYTES_IN_JVM_LONG || (NO_OF_BITS_IN_BYTE - n) * NO_OF_BITS_IN_BYTE == popCountL(v & mask)) + var i = n * NO_OF_BITS_IN_BYTE - 1 + var allOnes = true + + // (∀i : 8n < i < 64: v[i] == 1) + (while i < NO_OF_BITS_IN_LONG do + decreases(NO_OF_BITS_IN_LONG - i) + allOnes &= (v & (1L << i)) != 0 + i += 1 + ).invariant(i >= (n * NO_OF_BITS_IN_BYTE - 1) && i <= NO_OF_BITS_IN_LONG) + + pre &&& allOnes }) /** From 2b761f7082f0fe2d908930b3894565b9f95d7809 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 8 Jan 2024 19:42:26 +0100 Subject: [PATCH 127/174] removed encodeConstraintPosWholeNumber - no unsigned numbers on the JVM --- .../main/scala/asn1scala/asn1jvm_Codec.scala | 36 +++++++++++-------- .../main/scala/asn1scala/asn1jvm_Helper.scala | 11 ------ 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 7f48f45b2..5363a290b 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -208,8 +208,13 @@ trait Codec { require(min <= v && v <= max) val range = max - min + stainlessAssert(range >= 0) if range == 0 then - return + return; + + // runtime only right now + if range < 0 then + writeToStdErr("Range is bigger than the biggest primitive on the JVM - unsafe!") // get number of bits that get written val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) @@ -226,20 +231,21 @@ trait Codec { writeToStdErr("precondition for appendBitsLSBFirst not met") } - def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { - require(max >= 0 && max <= Long.MaxValue) - require(min >= 0 && min <= max) - require(min <= v && v <= max) - - val range: ULong = (max - min) - if range == 0 then - return - - val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) - val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) - appendNBitZero(nRangeBits - nBits) - encodeNonNegativeInteger(v - min) - } + // TODO remove - does exactly the same as encodeConstrainedWholeNumber +// def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { +// require(max >= 0 && max <= Long.MaxValue) +// require(min >= 0 && min <= max) +// require(min <= v && v <= max) +// +// val range: ULong = (max - min) +// if range == 0 then +// return +// +// val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) +// val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) +// appendNBitZero(nRangeBits - nBits) +// encodeNonNegativeInteger(v - min) +// } def decodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { require(min <= max) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index 85d76eb26..070e51b65 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -135,17 +135,6 @@ def GetLengthForEncodingUnsigned(v: ULong): Int = { max((GetNumberOfBitsForNonNegativeInteger(v) + NO_OF_BITS_IN_BYTE - 1) / NO_OF_BITS_IN_BYTE, 1) // even the number 0 needs 1 byte }.ensuring(n => n > 0 && n <= NO_OF_BYTES_IN_JVM_LONG) -/** - * Get the amount of set bits in the given 64bit number v - * - * @param v input - * @return Amount of set bits in v - */ -@extern -private def popCountL(v: Long): Int = { - Integer.bitCount((v >>> 32).toUnsignedInt) + Integer.bitCount((v & 0xFF_FF_FF_FFL).toUnsignedInt) -} - /** * Get number of bytes needed to encode the * positive number v according to PER rules (8.3) From 0afe294b7651bd6835757fad910375312862c695 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 10 Jan 2024 15:06:37 +0100 Subject: [PATCH 128/174] replaced template call --- StgScala/uper_scala.stg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 426d4ce33..7cb348f15 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -135,7 +135,7 @@ codec.decodeConstraintWholeNumber(, ) match // uper:122 /*case: Positive fully constraint A:: = INTEGER (5..20) */ IntFullyConstraintPos_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -codec.encodeConstraintPosWholeNumber(

, , ) +codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraintPos_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << From f06db23c130723df136438b573dccfbfd52f8ec7 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 10 Jan 2024 17:43:56 +0100 Subject: [PATCH 129/174] some VC's - some typos --- StgScala/acn_scala.stg | 6 +- StgScala/uper_scala.stg | 32 +++---- .../scala/asn1scala/asn1jvm_Bitstream.scala | 31 +++++++ .../main/scala/asn1scala/asn1jvm_Codec.scala | 86 ++++++++++--------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 8 +- .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 4 +- 6 files changed, 100 insertions(+), 67 deletions(-) diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 743a1c166..0c03b2187 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -863,7 +863,7 @@ Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_C >> Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << -codec.decodeConstraintWholeNumber(0, ) match +codec.decodeConstrainedWholeNumber(0, ) match case None() => return Left() case Some(x) => @@ -1137,7 +1137,7 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits var nCount: Int = 0 - codec.decodeConstraintWholeNumber(, ) match + codec.decodeConstrainedWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => @@ -1196,7 +1196,7 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit var nCount: Int = 0 - codec.decodeConstraintWholeNumber(, ) match + codec.decodeConstrainedWholeNumber(, ) match case None() => return Left(pErrCode) case Some(x) => diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index 7cb348f15..c2f9834a2 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -97,7 +97,7 @@ codec.encodeConstrainedWholeNumber(charIndex, 0, ) InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< -codec.decodeConstraintWholeNumber(0, ) match +codec.decodeConstrainedWholeNumber(0, ) match case Some(charIndex) =>

() = allowedCharSet(charIndex.toInt) case None() => @@ -110,7 +110,7 @@ codec.encodeConstrainedWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -codec.decodeConstraintWholeNumberByte(0, 127) match // uper:109 +codec.decodeConstrainedWholeNumberByte(0, 127) match // uper:109 case Some(c) =>

() = c case None() => @@ -126,7 +126,7 @@ codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -codec.decodeConstraintWholeNumber(, ) match // uper:122 +codec.decodeConstrainedWholeNumber(, ) match // uper:122 case Some(n) =>

= n case None() => @@ -289,7 +289,7 @@ Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, n >> Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -codec.decodeConstraintWholeNumber(0, ) match // uper:277 +codec.decodeConstrainedWholeNumber(0, ) match // uper:277 case Some(x) => x match @@ -329,7 +329,7 @@ choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, >> choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -codec.decodeConstraintWholeNumber(0, ) match // uper:317 +codec.decodeConstrainedWholeNumber(0, ) match // uper:317 case Some(choice) => choice match }; separator="\n"> @@ -438,7 +438,7 @@ codec.encodeConstrainedWholeNumber(nStringLength, , ) str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << nStringLength = 0 -codec.decodeConstraintWholeNumberInt(, ) match // uper:418 +codec.decodeConstrainedWholeNumberInt(, ) match // uper:418 case Some(n) => nStringLength = n

(nStringLength) = 0 // TODO do we need a 0 terminator? @@ -464,7 +464,7 @@ codec.encodeConstrainedWholeNumber(

nCount, , ) >> seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -codec.decodeConstraintWholeNumber(, ) match // uper:444 +codec.decodeConstrainedWholeNumber(, ) match // uper:444 case Some(n) =>

nCount = n.asInstanceOf[Int] case None() => @@ -497,7 +497,7 @@ if !codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << // decode length -codec.decodeConstraintWholeNumber(, ) match // uper:475 +codec.decodeConstrainedWholeNumber(, ) match // uper:475 case Some(n) => assert(n >= 0)

nCount = n @@ -533,7 +533,7 @@ codec.encodeConstrainedWholeNumber(

nCount, , ) >> bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -codec.decodeConstraintWholeNumber(, ) match // uper:509 +codec.decodeConstrainedWholeNumber(, ) match // uper:509 case Some(n) =>

nCount = n case None() => @@ -680,7 +680,7 @@ FixedSize_Fragmentation_sqf_64K_decode(p, sAcc,sCurOffset, sCurBlockSize, sBlock = 0; *pErrCode = ; for( = 0; ret && \< ; ++) { - ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) + ret = codec.decodeConstrainedWholeNumber(, 0, 0xFF) val check = (ret == 0) && ( == 0xC4); ret = if (check) then Right(0) else Left() if ret == 0 then @@ -706,7 +706,7 @@ for( = 0; ret && \< ; ++) { FixedSize_Fragmentation_sqf_small_block_decode(p, sAcc,sInternalItem, nBlockSize, sBlockId, sCurOffset, sCurBlockSize, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::=<< //decode a single Block with items = ; -ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) +ret = codec.decodeConstrainedWholeNumber(, 0, 0xFF) val check = (ret == 0) && ( == ); ret = if (check) then Right(0) else Left() if ret.isRight then @@ -728,11 +728,11 @@ if ret.isRight then FixedSize_Fragmentation_sqf_remaining_decode(p, sAcc,sInternalItem, bRemainingItemsWithinByte, nRemainingItemsVar, sCurOffset, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::= << //decode remaining items -ret = codec.decodeConstraintWholeNumber(, 0, 0xFF) +ret = codec.decodeConstrainedWholeNumber(, 0, 0xFF) ret = ret && ( == ); -ret = codec.decodeConstraintWholeNumber(, 0, 0xFFFF) +ret = codec.decodeConstrainedWholeNumber(, 0, 0xFFFF) ret = ret && ((0x8000 & ) > 0) && ( (0x7FFF & ) == ); @@ -768,7 +768,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0 -codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:733 +codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:733 case None() => return Left() case Some(x) => @@ -805,7 +805,7 @@ while(( & 0xC0) == 0xC0) { += += - codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:770 + codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:770 case None() => return Left() case Some(x) => @@ -815,7 +815,7 @@ while(( & 0xC0) == 0xC0) { if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 - codec.decodeConstraintWholeNumber(0, 0xFF) match // uper:780 + codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:780 case None() => return Left() case Some(x) => diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 7199afbd6..5f894e493 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -545,6 +545,37 @@ case class BitStream( arr }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - nBits) + /** + * Counter Operation to appendBitsNBitFirstToLSB + * @param nBits number of bits to read [0-64] + * @return value that holds nBits from bitstream + * + * Remarks: + * The last bit from the bitstream will get written into the LSB + */ + def readBitsNBitFirstToLSB(nBits: Int): Long = { + require(nBits >= 0 && nBits <= 64) + require(validate_offset_bits(nBits)) + + var l: Long = 0 + + @ghost val oldThis = snapshot(this) + var i = 0 + (while i < nBits do + decreases(nBits - i) + + l |= (if readBit() then 1L << (nBits - 1 - i) else 0) + + i += 1 + ).invariant( + i >= 0 && i <= nBits &&& + validate_offset_bits(nBits - i) &&& + buf == oldThis.buf &&& + remainingBits == oldThis.remainingBits - i) + + l + }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - nBits.toLong) + // ****************** Read Byte Functions ********************** /** diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 5363a290b..fd535bd77 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -231,23 +231,7 @@ trait Codec { writeToStdErr("precondition for appendBitsLSBFirst not met") } - // TODO remove - does exactly the same as encodeConstrainedWholeNumber -// def encodeConstraintPosWholeNumber(v: ULong, min: ULong, max: ULong): Unit = { -// require(max >= 0 && max <= Long.MaxValue) -// require(min >= 0 && min <= max) -// require(min <= v && v <= max) -// -// val range: ULong = (max - min) -// if range == 0 then -// return -// -// val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) -// val nBits: Int = GetNumberOfBitsForNonNegativeInteger(v - min) -// appendNBitZero(nRangeBits - nBits) -// encodeNonNegativeInteger(v - min) -// } - - def decodeConstraintWholeNumber(min: Long, max: Long): Option[Long] = { + def decodeConstrainedWholeNumber(min: Long, max: Long): Option[Long] = { require(min <= max) require( min >= 0 && max >= 0 || @@ -256,54 +240,60 @@ trait Codec { ) val range: ULong = max - min + + // only one possible number if range == 0 then return Some(min) val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) - decodeNonNegativeInteger(nRangeBits) match - case None() => return None() - case Some(ul) => return Some(ul + min) + readBitsNBitFirstToLSB(nRangeBits) match + case None() => None() + case Some(ul) => Some(min + ul) + +// decodeNonNegativeInteger(nRangeBits) match +// case None() => return None() +// case Some(ul) => return Some(ul + min) } - def decodeConstraintWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { - decodeConstraintWholeNumber(min.toLong, max.toLong) match + decodeConstrainedWholeNumber(min.toLong, max.toLong) match case None() => None() case Some(l) => Some(l.toByte) } - def decodeConstraintWholeNumberShort(min: Short, max: Short): Option[Short] = { + def decodeConstrainedWholeNumberShort(min: Short, max: Short): Option[Short] = { - decodeConstraintWholeNumber(min, max) match + decodeConstrainedWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toShort) } - def decodeConstraintWholeNumberInt(min: Int, max: Int): Option[Int] = { + def decodeConstrainedWholeNumberInt(min: Int, max: Int): Option[Int] = { - decodeConstraintWholeNumber(min, max) match + decodeConstrainedWholeNumber(min, max) match case None() => None() case Some(l) => Some(l.toInt) } - def decodeConstraintWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { + def decodeConstrainedWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { - decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toByte) } - def decodeConstraintWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { + def decodeConstrainedWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { - decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toShort) } - def decodeConstraintWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { + def decodeConstrainedWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { - decodeConstraintWholeNumber(min.unsignedToLong, max.unsignedToLong) match + decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match case None() => None() case Some(l) => Some(l.toInt) } @@ -355,7 +345,7 @@ trait Codec { var nBytes: Long = 0 var v: Long = 0 - decodeConstraintWholeNumber(0, 255) match + decodeConstrainedWholeNumber(0, 255) match case None() => return None() case Some(l) => nBytes = l @@ -378,7 +368,7 @@ trait Codec { var nBytes: Long = 0 var v: ULong = 0 - decodeConstraintWholeNumber(0, 255) match + decodeConstrainedWholeNumber(0, 255) match case None() => return None() case Some(l) => nBytes = l @@ -778,7 +768,7 @@ trait Codec { var nCurOffset1: Long = 0 // get header data - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -813,7 +803,7 @@ trait Codec { nCurOffset1 += nCurBlockSize1 // get next header - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -822,7 +812,7 @@ trait Codec { nRemainingItemsVar1 <<= 8 // put upper at correct position // get size (lower byte) - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size @@ -873,7 +863,7 @@ trait Codec { if asn1SizeMax < 65536 then var nCount: Int = 0 if asn1SizeMin != asn1SizeMax then - decodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax) match case None() => return NoneMut() case Some(l) => nCount = l.toInt else @@ -941,7 +931,7 @@ trait Codec { if (asn1SizeMax < 65536) { var nCount: Long = 0 if asn1SizeMin != asn1SizeMax then - decodeConstraintWholeNumber(asn1SizeMin, asn1SizeMax) match + decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax) match case None() => return NoneMut() case Some(l) => nCount = l else @@ -954,7 +944,7 @@ trait Codec { var nCurBlockSize1: Long = 0 var nCurOffset1: Long = 0 var nLengthTmp1: Long = 0 - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l @@ -983,13 +973,13 @@ trait Codec { arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) nLengthTmp1 += nCurBlockSize1 nCurOffset1 += nCurBlockSize1 - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 = l if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return NoneMut() case Some(l) => nRemainingItemsVar1 |= l @@ -1124,6 +1114,18 @@ trait Codec { case false => None() } + def readBitsNBitFirstToLSB(nBits: Int): Option[Long] = { + require(bitStream.validate_offset_bits(nBits)) + + val isValidPrecondition = bitStream.validate_offset_bits(nBits) + stainlessAssert(isValidPrecondition) + runtimeAssert(isValidPrecondition) + + isValidPrecondition match + case true => Some(bitStream.readBitsNBitFirstToLSB(nBits)) + case false => None() + } + def peekBit(): Option[Boolean] = { require(bitStream.validate_offset_bit()) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 71a03bf53..63084c003 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -980,7 +980,7 @@ case class ACN(bitStream: BitStream) extends Codec { } def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): OptionMut[Array[ASCIIChar]] = { - decodeConstraintWholeNumber(min, max) match + decodeConstrainedWholeNumber(min, max) match case None() => NoneMut() case Some(nCount) => dec_String_Ascii_private(max, if nCount <= max then nCount else max) @@ -990,7 +990,7 @@ case class ACN(bitStream: BitStream) extends Codec { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 while i < charactersToDecode do - decodeConstraintWholeNumber(0, allowedCharSet.length - 1) match + decodeConstrainedWholeNumber(0, allowedCharSet.length - 1) match case None() => return NoneMut() case Some(charIndex) => strVal(i) = allowedCharSet(charIndex.toInt) @@ -1009,7 +1009,7 @@ case class ACN(bitStream: BitStream) extends Codec { def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): OptionMut[Array[ASCIIChar]] = { - decodeConstraintWholeNumber(min, max) match + decodeConstrainedWholeNumber(min, max) match case None() => NoneMut() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) @@ -1051,7 +1051,7 @@ case class ACN(bitStream: BitStream) extends Codec { 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) - decodeConstraintWholeNumber(min, max) match + decodeConstrainedWholeNumber(min, max) match case None() => NoneMut() case Some(nCount) => dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index 25177b996..edd0b1ee0 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -118,12 +118,12 @@ case class UPER(bitStream: BitStream) extends Codec { def objectIdentifier_decode_length(): Option[Long] = { var totalSize: Long = 0 - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return None() case Some(l) => totalSize = l if totalSize > 0x7F then - decodeConstraintWholeNumber(0, 0xFF) match + decodeConstrainedWholeNumber(0, 0xFF) match case None() => return None() case Some(l) => totalSize <<= 8 From 3136fcc1f0a8ba598622e7ad6182761827596f81 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 10 Jan 2024 18:56:08 +0100 Subject: [PATCH 130/174] some more VCs --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 2 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 40 +++++-------------- .../main/scala/asn1scala/asn1jvm_Helper.scala | 27 ++++++++----- 3 files changed, 28 insertions(+), 41 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 5f894e493..4b9b2cc74 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -603,7 +603,7 @@ case class BitStream( remainingBits == oldThis.remainingBits - i &&& validate_offset_bits(NO_OF_BITS_IN_BYTE - i)) - ret.toUnsignedByte + ret.cutToByte }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - NO_OF_BITS_IN_BYTE) def readByteArray(nBytes: Int): Array[UByte] = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index fd535bd77..38d8f2aed 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -117,7 +117,7 @@ trait Codec { if negate then b = ~b - appendByte(b.toUnsignedByte) + appendByte(b.cutToByte) } def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { @@ -250,52 +250,30 @@ trait Codec { readBitsNBitFirstToLSB(nRangeBits) match case None() => None() case Some(ul) => Some(min + ul) - -// decodeNonNegativeInteger(nRangeBits) match -// case None() => return None() -// case Some(ul) => return Some(ul + min) } def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + require(min <= max) decodeConstrainedWholeNumber(min.toLong, max.toLong) match case None() => None() - case Some(l) => Some(l.toByte) + case Some(l) => Some(l.cutToByte) } def decodeConstrainedWholeNumberShort(min: Short, max: Short): Option[Short] = { + require(min <= max) decodeConstrainedWholeNumber(min, max) match case None() => None() - case Some(l) => Some(l.toShort) + case Some(l) => Some(l.cutToShort) } def decodeConstrainedWholeNumberInt(min: Int, max: Int): Option[Int] = { + require(min <= max) decodeConstrainedWholeNumber(min, max) match case None() => None() - case Some(l) => Some(l.toInt) - } - - def decodeConstrainedWholeNumberUByte(min: UByte, max: UByte): Option[UByte] = { - - decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toByte) - } - - def decodeConstrainedWholeNumberUShort(min: UShort, max: UShort): Option[UShort] = { - - decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toShort) - } - - def decodeConstrainedWholeNumberUInt(min: UInt, max: UInt): Option[UInt] = { - - decodeConstrainedWholeNumber(min.unsignedToLong, max.unsignedToLong) match - case None() => None() - case Some(l) => Some(l.toInt) + case Some(l) => Some(l.cutToInt) } def decodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { @@ -324,7 +302,7 @@ trait Codec { /* put required zeros*/ appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) /*Encode number */ - encodeNonNegativeInteger((v - min)) + encodeNonNegativeInteger(v - min) } def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { @@ -406,7 +384,7 @@ trait Codec { (while i > 0 do decreases(i) - appendByte((v >>> ((i - 1) * NO_OF_BITS_IN_BYTE)).toUnsignedByte) + appendByte((v >>> ((i - 1) * NO_OF_BITS_IN_BYTE)).cutToByte) i -= 1 ).invariant(i >= 0 && i <= nBytes) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala index 070e51b65..b8c9b102f 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Helper.scala @@ -17,10 +17,12 @@ val MASK_INT_L = 0xFF_FF_FF_FFL // MSBs (neg bits of the integer) val MASK_MSB_BYTE = 0x80L +val MASK_MSB_SHORT = 0x80_00L val MASK_MSB_INT = 0x80_00_00_00L // pos bits of the integer val MASK_POS_BYTE = 0x7FL +val MASK_POS_SHORT = 0x7F_FFL val MASK_POS_INT = 0x7F_FF_FF_FFL /* @@ -33,18 +35,18 @@ extension (ubL: UByte) { @targetName("unsigned right shift on Bytes") def >>>>(i: Int): UByte = { require(i >= 0 && i <= NO_OF_BITS_IN_BYTE) - ((ubL.toInt & MASK_BYTE) >>> i).toUnsignedByte + ((ubL.toInt & MASK_BYTE) >>> i).cutToByte } @targetName("left shift on Bytes") def <<<<(i: Int): UByte = { require(i >= 0 && i <= NO_OF_BITS_IN_BYTE) - ((ubL.toInt << i) & MASK_BYTE).toUnsignedByte + ((ubL.toInt << i) & MASK_BYTE).cutToByte } @targetName("binary OR on Bytes") def |||(ubR: Byte): UByte = { - (ubL.toInt | ubR.toInt).toUnsignedByte + (ubL.toInt | ubR.toInt).cutToByte } } @@ -69,9 +71,7 @@ extension (i: Int) { } extension (l: Long) { - def toUnsignedInt: UInt = { - require(l >= 0 && l <= MASK_INT_L) - + def cutToInt: UInt = { if(l == MASK_MSB_INT) (-MASK_MSB_INT).toInt else if ((l & MASK_MSB_INT) == MASK_MSB_INT) @@ -80,7 +80,16 @@ extension (l: Long) { l.toInt } - def toUnsignedByte: UByte = { + def cutToShort: UShort = { + if (l == MASK_MSB_SHORT) + (-MASK_MSB_SHORT).toShort + else if ((l & MASK_MSB_SHORT) == MASK_MSB_SHORT) + ((l & MASK_POS_SHORT) - MASK_MSB_SHORT).toShort + else + l.toShort + } + + def cutToByte: UByte = { if ((l & MASK_BYTE) == MASK_MSB_BYTE) (-MASK_MSB_BYTE).toByte else if ((l & MASK_MSB_BYTE) == MASK_MSB_BYTE) @@ -125,9 +134,9 @@ def GetNumberOfBitsForNonNegativeInteger32(vVal: UInt): Int = { def GetNumberOfBitsForNonNegativeInteger(v: ULong): Int = { if v >>> 32 == 0 then - GetNumberOfBitsForNonNegativeInteger32(v.toUnsignedInt) + GetNumberOfBitsForNonNegativeInteger32(v.cutToInt) else - val h = (v >>> 32).toUnsignedInt + val h = (v >>> 32).cutToInt 32 + GetNumberOfBitsForNonNegativeInteger32(h) }.ensuring(n => n >= 0 && n <= 64) From b64ee07466a5b4bbf16e2aa4defc16e946897c3e Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Fri, 12 Jan 2024 17:51:58 +0100 Subject: [PATCH 131/174] stainless like return values staticchecks added to runtime (still problematic in some cases - signed / unsigned) --- PUSCScalaTest/Testframework.cs | 4 +- ST/ST.fs | 3 +- StgScala/acn_scala.stg | 237 +--- StgScala/test_cases_scala.stg | 4 +- StgScala/uper_scala.stg | 209 +--- .../main/scala/asn1scala/asn1jvm_Codec.scala | 797 +++++-------- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 1047 +++++------------ .../scala/asn1scala/asn1jvm_Codec_UPER.scala | 104 +- 8 files changed, 743 insertions(+), 1662 deletions(-) diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index 4c9aec0a8..a16a7c032 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -181,8 +181,8 @@ private void compareTestCases(string folderA, string folderB) private string getCleanWorkingFolderPath(string folderSuffix, ServiceVariation sv) { string outDir = GetOutputFolder(folderSuffix, sv); - if (Directory.Exists(outDir)) - Directory.Delete(outDir, true); + //if (Directory.Exists(outDir)) + // Directory.Delete(outDir, true); return outDir; } diff --git a/ST/ST.fs b/ST/ST.fs index 90a38f9d5..89aadd2b1 100644 --- a/ST/ST.fs +++ b/ST/ST.fs @@ -124,8 +124,7 @@ type BigIntegerFormatRenderer() = else if (obj > BigInteger Int64.MaxValue) then Console.WriteLine("Number exceeded bounds of JVM native types, clamped to Scalas Long.MaxValue") - //Int64.MaxValue.ToString() + "L" - sprintf "BigInt(\"%s\").toLong" (obj.ToString()) + "Long.MaxValue" else obj.ToString() + "L" | _ -> obj.ToString() diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 0c03b2187..2f25a444d 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -96,184 +96,138 @@ codec.alignTo() PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize(_encode(

)

, )" PositiveInteger_ConstSize_decode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize() >> PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_8(_encode(

)

)" PositiveInteger_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_8() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_8() >> PositiveInteger_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_16(_encode(

)

)" PositiveInteger_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_16() >> PositiveInteger_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_32(_encode(

)

)" PositiveInteger_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_32() >> PositiveInteger_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_64(_encode(

)

)" PositiveInteger_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_64() >> PositiveInteger_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_16(_encode(

)

)" PositiveInteger_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_16() >> PositiveInteger_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_32(_encode(

)

)" PositiveInteger_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_32() >> PositiveInteger_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_64(_encode(

)

)" PositiveInteger_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_64() >> PositiveInteger_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= "codec.enc_Int_PositiveInteger_VarSize_LengthEmbedded(_encode(

)

)" PositiveInteger_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= << -codec.dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_PositiveInteger_VarSize_LengthEmbedded() >> TwosComplement_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize(_encode(

)

, )" TwosComplement_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize() >> TwosComplement_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_8(_encode(

)

)" TwosComplement_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_8() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_8() >> TwosComplement_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_16(_encode(

)

)" TwosComplement_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_big_endian_16() >> TwosComplement_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_32(_encode(

)

)" TwosComplement_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_big_endian_32() >> TwosComplement_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_64(_encode(

)

)" TwosComplement_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_big_endian_64() >> TwosComplement_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_16(_encode(

)

)" TwosComplement_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_little_endian_16() >> TwosComplement_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_32(_encode(

)

)" TwosComplement_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_little_endian_32() >> TwosComplement_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_64(_encode(

)

)" TwosComplement_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_TwosComplement_ConstSize_little_endian_64() - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_ConstSize_little_endian_64() >> TwosComplement_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_TwosComplement_VarSize_LengthEmbedded(_encode(

)

)" TwosComplement_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -codec.dec_Int_TwosComplement_VarSize_LengthEmbedded() - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_TwosComplement_VarSize_LengthEmbedded() >> BCD_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= "codec.enc_Int_BCD_ConstSize(_encode(

)

, )" BCD_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= << -codec.dec_Int_BCD_ConstSize() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_BCD_ConstSize() >> BCD_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_BCD_VarSize_LengthEmbedded(_encode(

)

)" BCD_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -codec.dec_Int_BCD_VarSize_LengthEmbedded() - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_BCD_VarSize_LengthEmbedded() >> BCD_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_BCD_VarSize_NullTerminated(_encode(

)

)" BCD_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -codec.dec_Int_BCD_VarSize_NullTerminated() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_Int_BCD_VarSize_NullTerminated() >> ASCII_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= "codec.enc_SInt_ASCII_ConstSize(_encode(

)

, ) " ASCII_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -codec.dec_SInt_ASCII_ConstSize() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_SInt_ASCII_ConstSize() >> ASCII_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_SInt_ASCII_VarSize_LengthEmbedded(_encode(

)

)" ASCII_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -codec.dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_SInt_ASCII_VarSize_LengthEmbedded() >> @@ -282,9 +236,7 @@ codec.enc_SInt_ASCII_VarSize_NullTerminated(_encode(

)

> ASCII_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -codec.dec_SInt_ASCII_VarSize_NullTerminated((byte[]){}, ) match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_SInt_ASCII_VarSize_NullTerminated((byte[]){}, ) >> @@ -293,9 +245,7 @@ codec.enc_UInt_ASCII_ConstSize(_encode(

)

, > ASCII_UINT_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -codec.dec_UInt_ASCII_ConstSize() match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_UInt_ASCII_ConstSize() >> @@ -304,50 +254,27 @@ codec.enc_UInt_ASCII_VarSize_NullTerminated(_encode(

)

> ASCII_UINT_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -codec.dec_UInt_ASCII_VarSize_NullTerminated(

, (byte[]){}, ) match - case None() => return Left() - case Some(x) =>

= x +

= codec.dec_UInt_ASCII_VarSize_NullTerminated(

, (byte[]){}, ) >> Real_32_big_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_big_endian(

.toFloat)" -Real_32_big_endian_decode(p, sSuffix, sErrCode) ::= << -codec.dec_Real_IEEE754_32_big_endian() match - case None() => return Left() - case Some(x) =>

= x ->> +Real_32_big_endian_decode(p, sSuffix, sErrCode) ::= "

= codec.dec_Real_IEEE754_32_big_endian()" Real_64_big_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_big_endian(

)" -Real_64_big_endian_decode(p, sErrCode) ::= << -codec.dec_Real_IEEE754_64_big_endian() match - case None() => return Left() - case Some(x) =>

= x ->> +Real_64_big_endian_decode(p, sErrCode) ::= "

= codec.dec_Real_IEEE754_64_big_endian()" Real_32_little_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_little_endian(

)" -Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= << -codec.dec_Real_IEEE754_32_little_endian() match - case None() => return Left() - case Some(x) =>

= x ->> +Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= "

= codec.dec_Real_IEEE754_32_little_endian()" Real_64_little_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_little_endian(

)" -Real_64_little_endian_decode(p, sErrCode) ::= << -codec.dec_Real_IEEE754_64_little_endian() match - case None() => - return Left() - case Some(x) => -

= x ->> - +Real_64_little_endian_decode(p, sErrCode) ::= "

= codec.dec_Real_IEEE754_64_little_endian()" Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalseValueAsByteArray, arrsBits, sErrCode) ::= << { var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - if !codec.appendBitsMSBFirst(if

then true_data else false_data, ) then - Console.err.println("appendBitsMSBFirst failed: not enough space for bits") - + codec.appendBitsMSBFirst(if

then true_data else false_data, ) } >> @@ -358,12 +285,7 @@ Boolean_decode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse var tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - codec.BitStream_ReadBitPattern(tmp, ) match - case None() => - return Left() - case Some(x) => -

= x - +

= codec.BitStream_ReadBitPattern(tmp, )

= !

; } >> @@ -372,9 +294,7 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - if !codec.appendBitsMSBFirst(tmp, ) then - Console.err.println("appendBitsMSBFirst failed: not enough space for bits") - + codec.appendBitsMSBFirst(tmp, ) } >> @@ -382,18 +302,13 @@ Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSav Null_pattern_decode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << -codec.BitStream_ReadBitPattern_ignore_value() match - case None() => ret = Left() - case Some(i) => ret = Right(i) - +ret = Right(codec.BitStream_ReadBitPattern_ignore_value()) { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) - codec.BitStream_ReadBitPattern(tmp, ) match - case None() => ret = Left() - case Some(b) => - if !b then ret = Left() + if !codec.BitStream_ReadBitPattern(tmp, ) then + ret = Left() } @@ -519,37 +434,28 @@ codec.enc_IA5String_CharIndex_External_Field_Determinant(,

) >> Acn_IA5String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) match - case NoneMut() => return Left() - case SomeMut(x) =>

= x +

= codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) >> oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -codec.encodeOctetString_no_length(

arr,

nCount.toInt) match - case false => return Left() - case true => ret = Right(0) +codec.encodeOctetString_no_length(

arr,

nCount.toInt) >> oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then

nCount = .asInstanceOf[Int] - codec.decodeOctetString_no_length(

nCount.toInt) match - case NoneMut() => return Left() - case SomeMut(x) => x.copyToArray(

arr) + /* TODO copyToArray? */ + codec.decodeOctetString_no_length(

nCount.toInt).copyToArray(

arr) >> oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -codec.encodeOctetString_no_length(

arr, ) match - case false => return Left() - case true => ret = Right(0) +codec.encodeOctetString_no_length(

arr, ) >> oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << if ((\<=) && (\<=)) then - codec.decodeOctetString_no_length() match - case NoneMut() => return Left() - case SomeMut(x) =>

arr = x + codec.decodeOctetString_no_length().copyToArray(

arr) >> @@ -559,7 +465,7 @@ sqf_external_field_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFl sqf_external_field_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << if ((\<=) && (\<=)) then -

nCount = .asInstanceOf[Int] +

nCount = .toInt >> @@ -574,9 +480,7 @@ if ((\<=) && (\<=)) oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -if !codec.appendBitsMSBFirst(Array({}), ) then - Console.err.println("appendBitsMSBFirst failed: not enough space for bits") - +codec.appendBitsMSBFirst(Array({}), ) >> oct_sqf_null_terminated_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << @@ -602,44 +506,27 @@ if (ret && checkBitPatternPresentResult.isEmpty) { >> bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if !codec.appendBitsMSBFirst(

arr,

nCount) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${

nCount} bits") - +codec.appendBitsMSBFirst(

arr,

nCount) >> bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then -

nCount = .asInstanceOf[Int] - codec.readBits(

nCount) match - case NoneMut() => return Left() - case SomeMut(arr) => -

arr = arr - ret = Right(0) +

nCount = .toInt + codec.readBits(

nCount).copyToArray(

arr) match >> bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if !codec.appendBitsMSBFirst(

arr, ) then - Console.err.println("appendBitsMSBFirst failed: not enough space for bits") - +codec.appendBitsMSBFirst(

arr, ) >> bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << if (\<=) && (\<=) then - codec.readBits() match - case NoneMut() => return Left() - case SomeMut(arr) => -

arr = arr - ret = Right(0) + codec.readBits().copyToArray(

arr) >> bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << -if !codec.appendBitsMSBFirst(

arr,

arr.length*8) then // TODO: re-introduce nCount? -> codec.appendBitsMSBFirst(

arr,

nCount) - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${

arr.length*8} bits") - - -if !codec.appendBitsMSBFirst(Array({}), ) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for bits") - +codec.appendBitsMSBFirst(

arr,

arr.length*8) // TODO: re-introduce nCount? -> codec.appendBitsMSBFirst(

arr,

nCount) +codec.appendBitsMSBFirst(Array({}), ) >> bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << @@ -667,17 +554,11 @@ ret = _ACN_Decode(

, codec, pErrCode, exist.) then - Console.err.println("appendBit failed: not enough space for 1 bit") - +codec.appendBit(

exist.) >> sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << -codec.readBit() match - case Some(bit) => -

exist. = bit - case None() => - return Left() +

exist. = codec.readBit() >> sequence_presense_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << @@ -1069,9 +950,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -if !codec.appendBitsMSBFirst(arr, .asInstanceOf[Int]) - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") - +codec.appendBitsMSBFirst(arr, .asInstanceOf[Int]) >> bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << @@ -1166,14 +1045,10 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit if ret.isRight then val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - if !codec.appendBitsMSBFirst(bitStrm.buf, nCount) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${nCount} bits") - + codec.appendBitsMSBFirst(bitStrm.buf, nCount) codec.encodeConstrainedWholeNumber(nCount, , ) - if !codec.appendBitsMSBFirst(bitStrm.buf, nCount) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${nCount} bits") - + codec.appendBitsMSBFirst(bitStrm.buf, nCount) } >> diff --git a/StgScala/test_cases_scala.stg b/StgScala/test_cases_scala.stg index 436755c6a..044950423 100644 --- a/StgScala/test_cases_scala.stg +++ b/StgScala/test_cases_scala.stg @@ -101,9 +101,7 @@ val file = new File(filename+".dat") val bw = new FileOutputStream(file) val l = codec.getLength codec.resetBitIndex() -codec.readByteArray(l) match - case SomeMut(arr) => bw.write(arr) - case NoneMut() => return Left(5) +bw.write(codec.readByteArray(l)) bw.close() >> diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index c2f9834a2..d5592f2a2 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -97,12 +97,7 @@ codec.encodeConstrainedWholeNumber(charIndex, 0, ) InternalItem_string_with_alpha_decode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< -codec.decodeConstrainedWholeNumber(0, ) match - case Some(charIndex) => -

() = allowedCharSet(charIndex.toInt) - case None() => -

() = CHAR_0000 - return Left() +

() = allowedCharSet(codec.decodeConstrainedWholeNumber(0, ).toInt) >> InternalItem_string_no_alpha_encode(p, sErrCode, i) ::=<< @@ -110,27 +105,18 @@ codec.encodeConstrainedWholeNumber(

(), 0, 127) >> InternalItem_string_no_alpha_decode(p, sErrCode, i) ::=<< -codec.decodeConstrainedWholeNumberByte(0, 127) match // uper:109 - case Some(c) => -

() = c - case None() => - return Left() +

() = codec.decodeConstrainedWholeNumberByte(0, 127) // uper:109 >> /* INTEGER START*/ - /*case: A:: = INTEGER (-5..20) */ IntFullyConstraint_encode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -codec.decodeConstrainedWholeNumber(, ) match // uper:122 - case Some(n) => -

= n - case None() => - return Left() +

= codec.decodeConstrainedWholeNumber(, ) // uper:122 >> /*case: Positive fully constraint A:: = INTEGER (5..20) */ @@ -139,27 +125,19 @@ codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraintPos_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -codec.decodeConstraintPosWholeNumber(, ) match // uper:135 - case Some(decPosNr) => -

= decPosNr - case None() => - return Left() +

= codec.decodeConstraintPosWholeNumber(, ) // uper:135 >> /*case: A :: = INTEGER */ IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -codec.decodeUnconstrainedWholeNumber() match // uper:145 - case Some(x) => -

= x - case None() => - return Left() +

= codec.decodeUnconstrainedWholeNumber() // uper:145 >> /*case: A :: = INTEGER(MIN..5) */ IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnconstrainedWholeNumber(

)" IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << -if !codec.decodeUnconstrainedWholeNumber() then +if !codec.decodeUnconstrainedWholeNumber() then // TODO meth does not return a boolean value...? ret = if then 0 else >> @@ -188,9 +166,7 @@ IntNoneRequired_decode(p, nConst, sErrCode) ::= << /*case: A:: = INTEGER (5..40,...) */ IntRootExt_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< -if !codec.appendBitZero() then /* write extension bit*/ - Console.err.println("appendBitZero failed: not enough space for 1 bit") - +codec.appendBitZero() /* write extension bit*/ >> @@ -213,15 +189,11 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< /*case: A:: = INTEGER (5..40,..., 60..70) */ IntRootExt2_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< if then - if !codec.appendBitZero() then /* write extension bit, value within root range, so ext bit is zero */ - Console.err.println("appendBitZero failed: not enough space for 1 bit") - + codec.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ else /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ - if !codec.appendBitOne() then - Console.err.println("appendBitOne failed: not enough space for 1 bit") - + codec.appendBitOne() >> @@ -231,31 +203,21 @@ IntRootExt2_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=") then - Console.err.println("appendBit failed: not enough space for 1 bit") - +codec.appendBit(

) >> Boolean_decode(p, sErrCode) ::= << -codec.readBit() match // uper:225 - case Some(bit) => -

= bit - case None() => - return Left() +

= codec.readBit() // uper:225 >> Real_encode(p, sSuffix, sErrCode) ::= "codec.encodeReal(

)" Real_decode(p, sSuffix, sErrCode) ::= << -codec.decodeReal() match // uper:234 - case Some(d) => -

= d.asInstanceOf[Double] - case None() => - return Left() +

= codec.decodeReal().toDouble // uper:234 >> ObjectIdentifier_encode(p, sErrCode) ::= "codec.ObjectIdentifier_encode(

);" ObjectIdentifier_decode(p, sErrCode) ::= << -if !codec.ObjectIdentifier_decode() then +if !codec.ObjectIdentifier_decode() then // uper:234 TODO ret = >> @@ -290,13 +252,9 @@ Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, n Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << codec.decodeConstrainedWholeNumber(0, ) match // uper:277 - case Some(x) => - x match - - case _ => - return Left() - case None() => - return Left() // TODO C impl returns first element from enum, even in error case + + case _ => + return Left() >> /* CHOICE START*/ @@ -330,12 +288,8 @@ choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << codec.decodeConstrainedWholeNumber(0, ) match // uper:317 - case Some(choice) => - choice match - }; separator="\n"> - case _ => - return Left() - case None() => + }; separator="\n"> + case _ => return Left() >> @@ -343,29 +297,21 @@ codec.decodeConstrainedWholeNumber(0, ) match // uper:317 /* SEQUENCE START */ sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= << -if !codec.appendBit(

exist.) then - Console.err.println("appendBit failed: not enough space for 1 bit") - +codec.appendBit(

exist.) >> + sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << -codec.readBit() match // uper:332 - case Some(bit) => -

exist. = bit - case None() => - return Left() +

exist. = codec.readBit() // uper:332 >> sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= << -if !codec.appendBit() then - Console.err.println("appendBit failed: not enough space for 1 bit") - +codec.appendBit() >> sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << >> - sequence_mandatory_child_encode(sChName, sChildContent) ::= << /*Encode */ @@ -437,13 +383,8 @@ codec.encodeConstrainedWholeNumber(nStringLength, , ) >> str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << -nStringLength = 0 -codec.decodeConstrainedWholeNumberInt(, ) match // uper:418 - case Some(n) => - nStringLength = n -

(nStringLength) = 0 // TODO do we need a 0 terminator? - case None() => - return Left(405) +nStringLength = codec.decodeConstrainedWholeNumberInt(, ) // uper:418 +

(nStringLength) = 0 = 0 @@ -464,67 +405,42 @@ codec.encodeConstrainedWholeNumber(

nCount, , ) >> seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -codec.decodeConstrainedWholeNumber(, ) match // uper:444 - case Some(n) => -

nCount = n.asInstanceOf[Int] - case None() => - return Left() - +

nCount = codec.decodeConstrainedWholeNumber(, ).toInt // uper:444 = 0 >> octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << -if !codec.encodeOctetString_no_length(

arr, .asInstanceOf[Int]) then - Console.err.println(s"encodeOctetString_no_length failed: not enough space for ${.asInstanceOf[Int]} bytes") - return Left(479) - +codec.encodeOctetString_no_length(

arr, .asInstanceOf[Int]) >> octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << -codec.decodeOctetString_no_length() match // uper:460 - case SomeMut(x) => - x.copyToArray(

arr) - case NoneMut() => - return Left(454) +/* TODO copyToArray? */ +codec.decodeOctetString_no_length().copyToArray(

arr) // uper:460 >> octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << codec.encodeConstrainedWholeNumber(

nCount, , ) -if !codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) then - ret = Left() +codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) >> octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << // decode length -codec.decodeConstrainedWholeNumber(, ) match // uper:475 - case Some(n) => - assert(n >= 0) -

nCount = n - case None() => - return Left() - +

nCount = codec.decodeConstrainedWholeNumber(, ) // uper:475 // decode payload -codec.decodeOctetString_no_length(

nCount.asInstanceOf[Int]) match // uper:483 - case SomeMut(a) => - a.copyToArray(

arr) - case NoneMut() => - return Left() +/* TODO copyToArray? */ +codec.decodeOctetString_no_length(

nCount.toInt).copyToArray(

arr) // uper:483 >> /* BIT STRING*/ bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast -if !codec.appendBitsMSBFirst(

arr, .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") - +codec.appendBitsMSBFirst(

arr, .toInt) >> + bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << -codec.readBits(.asInstanceOf[Int]) match // uper:496 - case SomeMut(a) => - a.copyToArray(

arr) - case NoneMut() => - return Left() +/* TODO copyToArray instead of assigning*/ +codec.readBits(.toInt).copyToArray(

arr) // uper:496 >> bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << @@ -533,11 +449,7 @@ codec.encodeConstrainedWholeNumber(

nCount, , ) >> bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -codec.decodeConstrainedWholeNumber(, ) match // uper:509 - case Some(n) => -

nCount = n - case None() => - return Left() +

nCount = codec.decodeConstrainedWholeNumber(, ) // uper:509 >> @@ -551,8 +463,7 @@ while( \< ) { codec.encodeConstrainedWholeNumber(0xC4, 0, 0xFF) - if !codec.appendBitsMSBFirst(&

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") + codec.appendBitsMSBFirst(&

arr[/8], .asInstanceOf[Int]) val =(int) @@ -572,9 +483,7 @@ FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize = ; codec.encodeConstrainedWholeNumber(, 0, 0xFF) -if !codec.appendBitsMSBFirst(&

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") - +codec.appendBitsMSBFirst(&

arr[/8], .toInt) for(=(int); \< (int)( + ); ++) { @@ -589,18 +498,12 @@ FixedSize_Fragmentation_sqf_remaining_encode(p, sAcc,sInternalItem, bRemainingIt //encode remaining items codec.encodeConstrainedWholeNumber(, 0, 0xFF) - -if !codec.appendBitOne() then - Console.err.println("appendBitOne failed: not enough space for 1 bit") - +codec.appendBitOne() codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) - -if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${asInstanceOf[Int]} bits") - +codec.appendBitsMSBFirst(

arr[/8], .toInt) for(=(int); \< (int)( + ); ++) { @@ -635,9 +538,7 @@ while ( >= 0x4000 && \< (a codec.encodeConstrainedWholeNumber(0xC1, 0, 0xFF) - if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") - + codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) =.asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -654,15 +555,11 @@ while ( >= 0x4000 && \< (a if \<= 0x7F then codec.encodeConstrainedWholeNumber(, 0, 0xFF) else - if !codec.appendBitOne() then - Console.err.println("appendBitOne failed: not enough space for 1 bit") - + codec.appendBitOne() codec.encodeConstrainedWholeNumber(, 0, 0x7FFF) -if !codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) then - Console.err.println(s"appendBitsMSBFirst failed: not enough space for ${.asInstanceOf[Int]} bits") - +codec.appendBitsMSBFirst(

arr[/8], .toInt) = .asInstanceOf[Int] while( \< ( + ).asInstanceOf[Int]) @@ -768,11 +665,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0 -codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:733 - case None() => - return Left() - case Some(x) => - = x.asInstanceOf[Int] + = codec.decodeConstrainedWholeNumber(0, 0xFF).toInt // uper:733 while(( & 0xC0) == 0xC0) { if == 0xC4 then @@ -805,21 +698,13 @@ while(( & 0xC0) == 0xC0) { += += - codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:770 - case None() => - return Left() - case Some(x) => - = x.asInstanceOf[Int] + = codec.decodeConstrainedWholeNumber(0, 0xFF).toInt // uper:770 } if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 - codec.decodeConstrainedWholeNumber(0, 0xFF) match // uper:780 - case None() => - return Left() - case Some(x) => - len2 = x.asInstanceOf[Int] + len2 = codec.decodeConstrainedWholeNumber(0, 0xFF).toInt // uper:780 |= len2; &= 0x7FFF; diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 38d8f2aed..9c6429b8a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -6,7 +6,7 @@ import stainless.collection.* import stainless.annotation.* import stainless.proof.* import stainless.math.* -import StaticChecks.{assert => stainlessAssert, _} +import StaticChecks.{require => staticRequire, _} val masks2: Array[UInt] = Array( 0x00000000, // 0 / 0000 0000 0000 0000 0000 0000 0000 0000 / 0x0000 0000 @@ -29,8 +29,8 @@ def ByteStream_Init(count: Int): ByteStream = { ByteStream(Array.fill(count)(0), 0, false) } -@extern -def runtimeAssert(condition: Boolean, s: String =""): Unit = assert(condition, s) +//@extern +//def runtimeAssert(condition: Boolean, s: String =""): Unit = assert(condition, s) @extern def writeToStdErr(s: String): Unit = Console.err.println(s) @@ -120,31 +120,27 @@ trait Codec { appendByte(b.cutToByte) } - def decodeNonNegativeInteger32Neg(nBitsVal : Int): Option[UInt] = { - + def decodeNonNegativeInteger32Neg(nBitsVal : Int): Int = { + // TODO precondition var v: UInt = 0 var nBits = nBitsVal - while nBits >= 8 do + (while nBits >= 8 do decreases(nBits) v = v << 8 - readByte() match - case None() => return None() - case Some(ub) => - // mask the Byte-Bits, because negative values eg. -1 (1111 1111) - // will be casted to an Int -1 (1111 ... 1111) - v = v | (ub & 0xFF) + // mask the Byte-Bits, because negative values eg. -1 (1111 1111) + // will be casted to an Int -1 (1111 ... 1111) + v = v | (readByte() & 0xFF) nBits -= 8 + ).invariant(true) // TODO invariant if nBits != 0 then v = v << nBits - readPartialByte(nBits.toByte) match - case None() => return None() - case Some(ub) => v = v | (ub & 0xFF) + v = v | (readPartialByte(nBits.toByte) & 0xFF) - Some(v) + v } def encodeNonNegativeInteger(v: ULong): Unit = { @@ -160,28 +156,24 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } - def decodeNonNegativeInteger(nBits: Int): Option[ULong] = { + def decodeNonNegativeInteger(nBits: Int): Long = { + // TODO precondition + if nBits <= 32 then - decodeNonNegativeInteger32Neg(nBits) match - case None() => return None() - case Some(lo) => - return Some(lo & 0xFFFFFFFFL) - - val hi_ret = decodeNonNegativeInteger32Neg(32) - val lo_ret = decodeNonNegativeInteger32Neg(nBits - 32) - - (hi_ret, lo_ret) match - case (Some(hi), Some(lo)) => - var v: ULong = hi & 0xFFFFFFFFL - v = v << nBits - 32L - v |= lo & 0xFFFFFFFFL - return Some(v) - case _ => return None() - //else - // return decodeNonNegativeInteger32Neg(v, nBits) + return decodeNonNegativeInteger32Neg(nBits) & 0xFFFFFFFFL + + var v: Long = + decodeNonNegativeInteger32Neg(32) & 0xFFFFFFFFL // high + v = v << nBits - 32L + + v |= decodeNonNegativeInteger32Neg(nBits - 32) & 0xFFFFFFFFL // low + + v } - def encodeNonNegativeIntegerNeg(v: ULong): Unit = { + def encodeNonNegativeIntegerNeg(v: Long): Unit = { + // TODO precondition + if v >>> 32 == 0 then encodeNonNegativeInteger32Neg(v.toInt, true) else @@ -198,6 +190,16 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } + /** + * + * @param v number that gets encoded, needs to be within [min,max] range + * @param min lower boundary of range + * @param max upper boundary of range + * + * Remarks: + * range size is limited to Long.MaxValue - a higher range will fail + * + */ def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) require( @@ -208,30 +210,22 @@ trait Codec { require(min <= v && v <= max) val range = max - min - stainlessAssert(range >= 0) if range == 0 then - return; - - // runtime only right now - if range < 0 then - writeToStdErr("Range is bigger than the biggest primitive on the JVM - unsafe!") + return // get number of bits that get written val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) // get value that gets written val encVal = v - min - stainlessAssert(encVal >= 0) @ghost val nEncValBits = GetNumberOfBitsForNonNegativeInteger(encVal) - stainlessAssert(nRangeBits >= nEncValBits) + assert(nRangeBits >= nEncValBits) - val done = appendBitsNBitFirstToLSB(encVal, nRangeBits) - if !done then - writeToStdErr("precondition for appendBitsLSBFirst not met") + appendBitsNBitFirstToLSB(encVal, nRangeBits) } - def decodeConstrainedWholeNumber(min: Long, max: Long): Option[Long] = { + def decodeConstrainedWholeNumber(min: Long, max: Long): Long = { require(min <= max) require( min >= 0 && max >= 0 || @@ -239,74 +233,75 @@ trait Codec { min <= (Long.MaxValue >> 1) && max <= min + (Long.MaxValue >> 1) ) - val range: ULong = max - min + val range: Long = max - min // only one possible number if range == 0 then - return Some(min) + return min val nRangeBits = GetNumberOfBitsForNonNegativeInteger(range) + val decVal = readBitsNBitFirstToLSB(nRangeBits) + + assert(min + decVal <= max) // TODO sanity check needed? - readBitsNBitFirstToLSB(nRangeBits) match - case None() => None() - case Some(ul) => Some(min + ul) + min + decVal } - def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Option[Byte] = { + def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Byte = { require(min <= max) + decodeConstrainedWholeNumber(min, max).cutToByte - decodeConstrainedWholeNumber(min.toLong, max.toLong) match - case None() => None() - case Some(l) => Some(l.cutToByte) + // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstrainedWholeNumberShort(min: Short, max: Short): Option[Short] = { + def decodeConstrainedWholeNumberShort(min: Short, max: Short): Short = { require(min <= max) + decodeConstrainedWholeNumber(min, max).cutToShort - decodeConstrainedWholeNumber(min, max) match - case None() => None() - case Some(l) => Some(l.cutToShort) + // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstrainedWholeNumberInt(min: Int, max: Int): Option[Int] = { + def decodeConstrainedWholeNumberInt(min: Int, max: Int): Int = { require(min <= max) - - decodeConstrainedWholeNumber(min, max) match - case None() => None() - case Some(l) => Some(l.cutToInt) + decodeConstrainedWholeNumber(min, max).cutToInt + // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstraintPosWholeNumber(min: ULong, max: ULong): Option[ULong] = { + def decodeConstraintPosWholeNumber(min: Long, max: Long): Long = { require(max >= 0 && max <= Long.MaxValue) require(min >= 0 && min <= max) - val range: ULong = max - min + val range: Long = max - min + // only one possible number if range == 0 then - return Some(min) + return min val nRangeBits: Int = GetNumberOfBitsForNonNegativeInteger(range) + val decVal = decodeNonNegativeInteger(nRangeBits) // TODO simpler call - decodeNonNegativeInteger(nRangeBits) match - case None() => None() - case Some(uv) => Some(uv + min) + assert(min + decVal <= max) // TODO sanity check needed? + + min + decVal } def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { - assert(v >= min) - val nBytes: Int = GetLengthForEncodingUnsigned((v - min)) + require(min <= v) + + val nBytes: Int = GetLengthForEncodingUnsigned(v - min) /* encode length */ encodeConstrainedWholeNumber(nBytes.toLong, 0, 255) /*8 bits, first bit is always 0*/ /* put required zeros*/ - appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger((v - min))) + appendNBitZero(nBytes * 8 - GetNumberOfBitsForNonNegativeInteger(v - min)) /*Encode number */ encodeNonNegativeInteger(v - min) } def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { - assert(v >= min) + require(min <= v) + val nBytes: Int = GetLengthForEncodingUnsigned(v - min) /* encode length */ @@ -318,49 +313,45 @@ trait Codec { encodeNonNegativeInteger(v - min) } - def decodeSemiConstraintWholeNumber(min: Long): Option[Long] = { - - var nBytes: Long = 0 - var v: Long = 0 + def decodeSemiConstraintWholeNumber(min: Long): Long = { + // TODO add precondition - decodeConstrainedWholeNumber(0, 255) match - case None() => return None() - case Some(l) => nBytes = l + // get length in bytes + val nBytes = decodeConstrainedWholeNumber(0, 255) + // get value + var v: Long = 0 var i: Long = 0 - while i < nBytes do + (while i < nBytes do decreases(nBytes - i) - readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + v = (v << 8) | (readByte() & 0xFF).toLong i += 1 + ).invariant(true) // TODO do invariant - v += min - - return Some(v) + min + v } - def decodeSemiConstraintPosWholeNumber(min: ULong): Option[ULong] = { + def decodeSemiConstraintPosWholeNumber(min: ULong): ULong = { + require(min >= 0) + // TODO precondition - var nBytes: Long = 0 - var v: ULong = 0 - decodeConstrainedWholeNumber(0, 255) match - case None() => return None() - case Some(l) => nBytes = l + // get length in bytes + val nBytes = decodeConstrainedWholeNumber(0, 255) + // get value + var v: ULong = 0 var i: Long = 0 - while i < nBytes do + (while i < nBytes do decreases(nBytes - i) - readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + v = (v << 8) | (readByte() & 0xFF).toLong i += 1 - v += min - return Some(v) + ).invariant(true) // TODO do invariant + + min + v } /** @@ -399,31 +390,25 @@ trait Codec { * * @return decoded number */ - def decodeUnconstrainedWholeNumber(): Option[Long] = { + def decodeUnconstrainedWholeNumber(): Long = { require(bitStream.validate_offset_bytes(2)) - val nBytes = readByte() match - case None() => return None() - case Some(b) => b - - val valIsNegative = peekBit() match - case Some(b) => b - case None() => return None() - - var v: Long = if valIsNegative then -1 else 0 + // get length + val nBytes = readByte() + // get sign + var v: Long = if peekBit() then -1 else 0 + // get value var i = 0 (while i < nBytes do decreases(nBytes - i) - readByte() match - case None() => return None() - case Some(ub) => v = (v << 8) | (ub & 0xFF).toLong + v = (v << 8) | (readByte() & 0xFF).toLong i += 1 - ).invariant(i >= 0 && i<= nBytes) + ).invariant(i >= 0 && i <= nBytes) - Some(v) + v } /** @@ -513,11 +498,11 @@ trait Codec { val (exponent, mantissa) = CalculateMantissaAndExponent(v) val nManLen: Int = GetLengthForEncodingUnsigned(mantissa) - runtimeAssert(nManLen <= 7) // 52 bit + assert(nManLen <= 7) // 52 bit val compactExp = RemoveLeadingFFBytesIfNegative(exponent) val nExpLen: Int = GetLengthForEncodingUnsigned(compactExp) - runtimeAssert(nExpLen >= 1 && nExpLen <= 2) + assert(nExpLen >= 1 && nExpLen <= 2) // 8.5.7.4 if nExpLen == 2 then @@ -549,57 +534,43 @@ trait Codec { * @return decoded real value in IE754 double format */ @extern - def decodeReal(): Option[Double] = { - decodeRealBitString() match - case None() => - None() - case Some(ll) => - Some(java.lang.Double.longBitsToDouble(ll)) - } - + def decodeReal(): Double = java.lang.Double.longBitsToDouble(decodeRealBitString()) /** * Real decoding implementation according to the PER standard * @return decoded double bits as 64 bit integer */ - private def decodeRealBitString(): Option[Long] = { - readByte() match - case None() => None() - case Some(length) => - // 8.5.2 Plus Zero - if length == 0 then - return Some(0) - - // invalid state - if length < 0 || length > DoubleMaxLengthOfSentBytes then - return None() - - readByte() match - case None() => None() - case Some(header) => - // 8.5.6 a) - if (header.unsignedToInt & 0x80) != 0x80 then - return None() - - // 8.5.9 PLUS-INFINITY - if header == 0x40 then - Some(DoublePosInfBitString) - - // 8.5.9 MINUS-INFINITY - else if header == 0x41 then - Some(DoubleNegInfBitString) - - // 8.5.9 NOT-A-NUMBER - else if header == 0x42 then - Some(DoubleNotANumber) - - // 8.5.3 Minus Zero - else if header == 0x43 then - Some(DoubleNegZeroBitString) - - // Decode 8.5.7 - else - decodeRealFromBitStream(length.toInt - 1, header) + private def decodeRealBitString(): Long = { + // TODO precondition? + + // get length + val length = readByte() + + // 8.5.2 Plus Zero + if length == 0 then + return 0 + + // sanity check + assert(length > 0 && length <= DoubleMaxLengthOfSentBytes) + + // get value + val retVal = readByte() match + // 8.5.6 a) + case header if (header.unsignedToInt & 0x80) == 0x80 => header match + // 8.5.9 PLUS-INFINITY + case header if header == 0x40 => Right(DoublePosInfBitString) + // 8.5.9 MINUS-INFINITY + case header if header == 0x41 => Right(DoubleNegInfBitString) + // 8.5.9 NOT-A-NUMBER + case header if header == 0x42 => Right(DoubleNotANumber) + // 8.5.3 MINUS-ZERO + case header if header == 0x43 => Right(DoubleNegZeroBitString) + // Decode 8.5.7 + case header => Right(decodeRealFromBitStream(length.toInt - 1, header)) + case _ => Left(0) + + assert(retVal.isRight, "only binary mode supported") + retVal.get } /** @@ -611,7 +582,7 @@ trait Codec { * @param header already decoded header * @return decoded real number as 64bit integer */ - private def decodeRealFromBitStream(lengthVal: Int, header: UByte): Option[Long] = { + private def decodeRealFromBitStream(lengthVal: Int, header: UByte): Long = { require(lengthVal >= 1 && lengthVal < DoubleMaxLengthOfSentBytes) // without header byte require((header.unsignedToInt & 0x80) == 0x80) require(bitStream.validate_offset_bytes(lengthVal)) @@ -629,41 +600,31 @@ trait Codec { val expLen = (header & 0x03) + 1 // sanity check - if expLen > lengthVal then - return None() + assert(expLen <= lengthVal) // decode exponent - var expIsNegative = false - peekBit() match - case Some(b) => expIsNegative = b - case None() => runtimeAssert(false) - - var exponent: Int = if expIsNegative then 0xFF_FF_FF_FF else 0 + var exponent: Int = if peekBit() then 0xFF_FF_FF_FF else 0 var i: Int = 0 (while i < expLen do decreases(expLen - i) - readByte() match - case None() => return None() - case Some(ub) => exponent = exponent << 8 | (ub.toInt & 0xFF) + exponent = exponent << 8 | (readByte().toInt & 0xFF) i += 1 - ).invariant(i >= 0 && i <= expLen) + ).invariant(i >= 0 && i <= expLen) - // decode mantissa + // decode mantissa parts val length = lengthVal - expLen var N: ULong = 0 var j: Int = 0 (while j < length do decreases(length - j) - readByte() match - case None() => return None() - case Some(ub) => N = (N << 8) | (ub.toInt & 0xFF) + N = (N << 8) | (readByte().toInt & 0xFF) j += 1 - ).invariant(j >= 0 && j <= length) + ).invariant(j >= 0 && j <= length) var v: Long = GetDoubleBitStringByMantissaAndExp(N * factor, expFactor * exponent) @@ -671,23 +632,21 @@ trait Codec { if (header & 0x40) > 0 then v |= SignBitMask - Some(v) + v } - def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Boolean = { + def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Unit = { appendByteArray(arr, nCount) } - def decodeOctetString_no_length(nCount: Int): OptionMut[Array[UByte]] = { - readByteArray(nCount) match - case NoneMut() => NoneMut() - case SomeMut(a) => - val arr: Array[UByte] = Array.fill(nCount + 1)(0) // TODO: why is +1 needed? - arrayCopyOffsetLen(a, arr, 0, 0, a.length) - SomeMut(arr) + def decodeOctetString_no_length(nCount: Int): Array[UByte] = { + val a = readByteArray(nCount) + val arr: Array[UByte] = Array.fill(nCount + 1)(0) // TODO: why is +1 needed? + arrayCopyOffsetLen(a, arr, 0, 0, a.length) + arr } - def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { + def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { // TODO return value legacy C? remove? var nRemainingItemsVar1: Int = nCount var nCurBlockSize1: Int = 0 var nCurOffset1: Int = 0 @@ -731,27 +690,24 @@ trait Codec { appendByte(arr(i1)) i1 += 1 - return ret + ret } - def decodeOctetString_fragmentation(asn1SizeMax: Long): OptionMut[Array[UByte]] = { + def decodeOctetString_fragmentation(asn1SizeMax: Long): Array[UByte] = { require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) var nCount: Int = 0 var nLengthTmp1: Long = 0 - var nRemainingItemsVar1: Long = 0 var nCurBlockSize1: Long = 0 var nCurOffset1: Long = 0 // get header data - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l + var nRemainingItemsVar1: Long = decodeConstrainedWholeNumber(0, 0xFF) // 11xx_xxxx header, there is a next fragment - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + (while (nRemainingItemsVar1 & 0xC0) == 0xC0 do decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease // get current block size @@ -764,16 +720,15 @@ trait Codec { else if nRemainingItemsVar1 == 0xC1 then nCurBlockSize1 = 0x4000 else - return NoneMut() + assert(false, "unsupported format") // fill current payload fragment into dest var i1: Int = nCurOffset1.toInt - while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do + (while (nCurOffset1 + nCurBlockSize1 <= asn1SizeMax) && (i1 < (nCurOffset1 + nCurBlockSize1).toInt) do decreases((nCurOffset1 + nCurBlockSize1).toInt - i1) - readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub + arr(i1) = readByte() i1 += 1 + ).invariant(true) // TODO invariant // sum combined length nLengthTmp1 += nCurBlockSize1 @@ -781,83 +736,75 @@ trait Codec { nCurOffset1 += nCurBlockSize1 // get next header - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l + nRemainingItemsVar1 = decodeConstrainedWholeNumber(0, 0xFF) + + ).invariant(true) // TODO invariant // 1000_0000 header, last fragment has size bigger than 255 - current byte is upper, need to get lower if (nRemainingItemsVar1 & 0x80) > 0 then nRemainingItemsVar1 <<= 8 // put upper at correct position + // get size (lower byte) - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l // combine 15bit (7 upper, 8 lower) into size - nRemainingItemsVar1 &= 0x7FFF // clear the control bit + nRemainingItemsVar1 |= decodeConstrainedWholeNumber(0, 0xFF) // combine 15bit (7 upper, 8 lower) into size + nRemainingItemsVar1 &= 0x7FFF // clear the control bit - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - var i1: Int = nCurOffset1.toInt + assert(nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) // TODO check with C implementation and standard - // fill last payload fragment into dest - while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do - decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) - readByte() match - case None() => return NoneMut() - case Some(ub) => arr(i1) = ub - i1 += 1 + var i1: Int = nCurOffset1.toInt - // add remainingSize to already written size - this var holds the absolut number in all fragments - nLengthTmp1 += nRemainingItemsVar1 + // fill last payload fragment into dest + (while i1 < (nCurOffset1 + nRemainingItemsVar1).toInt do + decreases((nCurOffset1 + nRemainingItemsVar1).toInt - i1) + arr(i1) = readByte() + i1 += 1 + ).invariant(true) // TODO invariant - // resize output array and copy data - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) - arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) - return SomeMut(newArr) - else - return NoneMut() + // add remainingSize to already written size - this var holds the absolut number in all fragments + nLengthTmp1 += nRemainingItemsVar1 + + // resize output array and copy data + assert((nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax)) // TODO check with C implementation and standard - NoneMut() + val newArr: Array[UByte] = Array.fill(nLengthTmp1.toInt)(0) + arrayCopyOffsetLen(arr, newArr, 0, 0, newArr.length) + newArr } def encodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + // TODO require & return type - seems old C style + var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax if ret then if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) - ret = encodeOctetString_no_length(arr, nCount) + encodeOctetString_no_length(arr, nCount) else ret = encodeOctetString_fragmentation(arr, nCount) - return ret + ret } - def decodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { - - if asn1SizeMax < 65536 then - var nCount: Int = 0 - if asn1SizeMin != asn1SizeMax then - decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l.toInt - else - nCount = asn1SizeMin.toInt + def decodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { - if (nCount >= asn1SizeMin && nCount <= asn1SizeMax) then - return decodeOctetString_no_length(nCount) - else - return NoneMut() + if asn1SizeMax >= 0x1_00_00 then // 65'536, bigger than 2 unsigned bytes + return decodeOctetString_fragmentation(asn1SizeMax) + var nCount: Int = 0 + if asn1SizeMin != asn1SizeMax then + nCount = decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax).toInt else - return decodeOctetString_fragmentation(asn1SizeMax) + nCount = asn1SizeMin.toInt + assert(nCount >= asn1SizeMin && nCount <= asn1SizeMax) // TODO check with C implementation and standard + + decodeOctetString_no_length(nCount) } - def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Unit = { if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) @@ -868,7 +815,7 @@ trait Codec { var nRemainingItemsVar1: Long = nCount.toLong var nCurBlockSize1: Long = 0 var nCurOffset1: Long = 0 - while nRemainingItemsVar1 >= 0x4000 do + (while nRemainingItemsVar1 >= 0x4000 do decreases(nRemainingItemsVar1) if nRemainingItemsVar1 >= 0x10000 then @@ -889,7 +836,7 @@ trait Codec { appendBitsMSBFirst(t, nCurBlockSize1.toInt) nCurOffset1 += nCurBlockSize1 nRemainingItemsVar1 -= nCurBlockSize1 - + ).invariant(true) // TODO invariant if nRemainingItemsVar1 <= 0x7F then encodeConstrainedWholeNumber(nRemainingItemsVar1, 0, 0xFF) @@ -899,317 +846,162 @@ trait Codec { val t: Array[UByte] = Array.fill(nRemainingItemsVar1.toInt)(0) // STAINLESS: arr.slice((nCurOffset1 / 8).toInt, (nCurOffset1 / 8).toInt + nRemainingItemsVar1.toInt) appendBitsMSBFirst(t, nRemainingItemsVar1.toInt) - - true } - def decodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): OptionMut[Array[UByte]] = { + def decodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { require(asn1SizeMax <= Int.MaxValue) + // TODO enhance precondition if (asn1SizeMax < 65536) { var nCount: Long = 0 if asn1SizeMin != asn1SizeMax then - decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax) match - case None() => return NoneMut() - case Some(l) => nCount = l + nCount = decodeConstrainedWholeNumber(asn1SizeMin, asn1SizeMax) else nCount = asn1SizeMin return readBits(nCount.toInt) - } else { - var nRemainingItemsVar1: Long = 0 - var nCurBlockSize1: Long = 0 - var nCurOffset1: Long = 0 - var nLengthTmp1: Long = 0 - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) - while (nRemainingItemsVar1 & 0xC0) == 0xC0 do - decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease - if nRemainingItemsVar1 == 0xC4 then - nCurBlockSize1 = 0x10000 - else if nRemainingItemsVar1 == 0xC3 then - nCurBlockSize1 = 0xC000 - else if nRemainingItemsVar1 == 0xC2 then - nCurBlockSize1 = 0x8000 - else if nRemainingItemsVar1 == 0xC1 then - nCurBlockSize1 = 0x4000 - else - return NoneMut() - - /*COVERAGE_IGNORE*/ - if nCurOffset1 + nCurBlockSize1 > asn1SizeMax then - return NoneMut() - /*COVERAGE_IGNORE*/ - - readBits(nCurBlockSize1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) - nLengthTmp1 += nCurBlockSize1 - nCurOffset1 += nCurBlockSize1 - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => nRemainingItemsVar1 = l - - if (nRemainingItemsVar1 & 0x80) > 0 then - nRemainingItemsVar1 <<= 8 - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return NoneMut() - case Some(l) => - nRemainingItemsVar1 |= l - nRemainingItemsVar1 &= 0x7FFF - - if (nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) then - - readBits(nRemainingItemsVar1.toInt) match - case NoneMut() => return NoneMut() - case SomeMut(t) => - arrayCopyOffsetLen(t, arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) - nLengthTmp1 += nRemainingItemsVar1 - if (nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax) then - return SomeMut(arr) } - return NoneMut() - } - def appendBitOne(): Boolean = { - require(bitStream.validate_offset_bit()) - - val isValidPrecondition = bitStream.validate_offset_bit() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) + var nCurBlockSize1: Long = 0 + var nCurOffset1: Long = 0 + var nLengthTmp1: Long = 0 + var nRemainingItemsVar1: Long = decodeConstrainedWholeNumber(0, 0xFF) - if isValidPrecondition then - bitStream.appendBitOne() + val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) + (while (nRemainingItemsVar1 & 0xC0) == 0xC0 do + decreases(asn1SizeMax - nCurOffset1) // TODO: check experimental decrease + if nRemainingItemsVar1 == 0xC4 then + nCurBlockSize1 = 0x10000 + else if nRemainingItemsVar1 == 0xC3 then + nCurBlockSize1 = 0xC000 + else if nRemainingItemsVar1 == 0xC2 then + nCurBlockSize1 = 0x8000 + else if nRemainingItemsVar1 == 0xC1 then + nCurBlockSize1 = 0x4000 + else + assert(false, "broken State") // TODO check with C implementation and standard - isValidPrecondition - } + assert(nCurOffset1 + nCurBlockSize1 > asn1SizeMax) - def appendBitZero(): Boolean = { - require(bitStream.validate_offset_bit()) + arrayCopyOffsetLen(readBits(nCurBlockSize1.toInt), arr, 0, (nCurOffset1 / 8).toInt, nCurBlockSize1.toInt) + nLengthTmp1 += nCurBlockSize1 + nCurOffset1 += nCurBlockSize1 + nRemainingItemsVar1 = decodeConstrainedWholeNumber(0, 0xFF) - val isValidPrecondition = bitStream.validate_offset_bit() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) + ).invariant(true) // TODO invariant - if isValidPrecondition then - bitStream.appendBitZero() + if (nRemainingItemsVar1 & 0x80) > 0 then + nRemainingItemsVar1 <<= 8 + nRemainingItemsVar1 |= decodeConstrainedWholeNumber(0, 0xFF) + nRemainingItemsVar1 &= 0x7FFF - isValidPrecondition - } + assert(nCurOffset1 + nRemainingItemsVar1 <= asn1SizeMax) - def appendNBitZero(nBits: Long): Boolean = { - require(bitStream.validate_offset_bits(nBits)) + arrayCopyOffsetLen(readBits(nRemainingItemsVar1.toInt), arr, 0, (nCurOffset1 / 8).toInt, nRemainingItemsVar1.toInt) + nLengthTmp1 += nRemainingItemsVar1 + assert((nLengthTmp1 >= 1) && (nLengthTmp1 <= asn1SizeMax)) - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) + arr + } - if isValidPrecondition then - bitStream.appendNBitZero(nBits) + // ***** Public wrapper for bitstream functions - isValidPrecondition + def appendBitOne(): Unit = { + require(bitStream.validate_offset_bit()) + bitStream.appendBitOne() } - def appendNBitOne(nBits: Long): Boolean = { - require(bitStream.validate_offset_bits(nBits)) + def appendBitZero(): Unit = { + require(bitStream.validate_offset_bit()) + bitStream.appendBitZero() + } - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) + def appendBit(v: Boolean): Unit = { + require(bitStream.validate_offset_bit()) + bitStream.appendBit(v) + } - if isValidPrecondition then - bitStream.appendNBitOne(nBits) + def peekBit(): Boolean = { + require(bitStream.validate_offset_bit()) + bitStream.peekBit() + } - isValidPrecondition + def readBit(): Boolean = { + require(bitStream.validate_offset_bit()) + bitStream.readBit() } - def appendBitsLSBFirst(v: Long, nBits: Int): Boolean = { // TODO remove if never used + def appendNBitZero(nBits: Long): Unit = { require(bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendBitsLSBFirst(v, nBits) - - isValidPrecondition + bitStream.appendNBitZero(nBits) } - def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Boolean = { + def appendNBitOne(nBits: Long): Unit = { require(bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendBitsNBitFirstToLSB(v, nBits) - - isValidPrecondition + bitStream.appendNBitOne(nBits) } - def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Boolean = { + def appendBitsLSBFirst(v: Long, nBits: Int): Unit = { // TODO remove if never used require(bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendBitsMSBFirst(srcBuffer, nBits) - - isValidPrecondition + bitStream.appendBitsLSBFirst(v, nBits) } - def appendBit(v: Boolean): Boolean = { - require(bitStream.validate_offset_bit()) - - val isValidPrecondition = bitStream.validate_offset_bit() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendBit(v) - - isValidPrecondition + def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Unit = { + require(bitStream.validate_offset_bits(nBits)) + bitStream.appendBitsMSBFirst(srcBuffer, nBits) } - def readBit(): Option[Boolean] = { - require(bitStream.validate_offset_bit()) - - val isValidPrecondition = bitStream.validate_offset_bit() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.readBit()) - case false => None() + def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Unit = { + require(bitStream.validate_offset_bits(nBits)) + bitStream.appendBitsNBitFirstToLSB(v, nBits) } - def readBitsNBitFirstToLSB(nBits: Int): Option[Long] = { + def readBitsNBitFirstToLSB(nBits: Int): Long = { require(bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.readBitsNBitFirstToLSB(nBits)) - case false => None() + bitStream.readBitsNBitFirstToLSB(nBits) } - def peekBit(): Option[Boolean] = { - require(bitStream.validate_offset_bit()) - - val isValidPrecondition = bitStream.validate_offset_bits(1) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.peekBit()) - case false => None() + def readBits(nBits: Long): Array[UByte] = { + require(nBits >= 0 && bitStream.validate_offset_bits(nBits)) + bitStream.readBits(nBits) } - def appendByte(value: Byte): Boolean = { + def appendByte(value: Byte): Unit = { require(bitStream.validate_offset_byte()) - - val isValidPrecondition = bitStream.validate_offset_byte() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendByte(value) - - isValidPrecondition + bitStream.appendByte(value) } - def readByte(): Option[UByte] = { + def readByte(): Byte = { require(bitStream.validate_offset_byte()) - - val isValidPrecondition = bitStream.validate_offset_byte() - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.readByte()) - case false => None() + bitStream.readByte() } - def appendByteArray(arr: Array[UByte], noOfBytes: Int): Boolean = { - val isValidPrecondition = bitStream.validate_offset_bytes(noOfBytes) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendByteArray(arr, noOfBytes) - - isValidPrecondition + def appendByteArray(arr: Array[Byte], noOfBytes: Int): Unit = { + require(bitStream.validate_offset_bytes(noOfBytes)) + bitStream.appendByteArray(arr, noOfBytes) } - - def readByteArray(nBytes: Int): OptionMut[Array[UByte]] = { + def readByteArray(nBytes: Int): Array[Byte] = { require(nBytes >= 0 && nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) require(bitStream.validate_offset_bytes(nBytes)) - - val isValidPrecondition = bitStream.validate_offset_bytes(nBytes) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => SomeMut(bitStream.readByteArray(nBytes)) - case false => NoneMut() + bitStream.readByteArray(nBytes) } - def readBits(nBits: Long): OptionMut[Array[UByte]] = { - require(nBits >= 0 && bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => SomeMut(bitStream.readBits(nBits)) - case false => NoneMut() - } - - def appendPartialByte(vVal: UByte, nBits: UByte): Boolean = { - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.appendPartialByte(vVal, nBits) - - isValidPrecondition + def appendPartialByte(vVal: Byte, nBits: Byte): Unit = { + require(bitStream.validate_offset_bits(nBits)) + bitStream.appendPartialByte(vVal, nBits) } - def readPartialByte(nBits: Int): Option[UByte] = { + def readPartialByte(nBits: Int): Byte = { require(nBits >= 0 && nBits <= NO_OF_BITS_IN_BYTE) require(bitStream.validate_offset_bits(nBits)) - - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.readPartialByte(nBits)) - case false => None() + bitStream.readPartialByte(nBits) } - def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Option[Boolean] = { - val isValidPrecondition = bitStream.validate_offset_bits(nBits) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - isValidPrecondition match - case true => Some(bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits)) - case false => None() + def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { + require(bitStream.validate_offset_bits(nBits)) + bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits) } // broken in C - do not translate @@ -1221,17 +1013,10 @@ trait Codec { // case false => NoneMut() // } - def alignToByte(): Boolean = { - val isValidPrecondition = bitStream.validate_offset_bits( - NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE) - ) - stainlessAssert(isValidPrecondition) - runtimeAssert(isValidPrecondition) - - if isValidPrecondition then - bitStream.alignToByte() - - isValidPrecondition + def alignToByte(): Unit = { + require(bitStream.validate_offset_bits( + NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE))) + bitStream.alignToByte() } def alignToShort(): Unit = { diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala index 63084c003..d41e85460 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_ACN.scala @@ -82,78 +82,69 @@ case class ACN(bitStream: BitStream) extends Codec { enc_Int_PositiveInteger_ConstSize_little_endian_N(intVal, NO_OF_BYTES_IN_JVM_LONG) } - - def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): Option[ULong] = { - decodeNonNegativeInteger(encodedSizeInBits) match - case None() => None() - case Some(ul) => Some(ul) + def dec_Int_PositiveInteger_ConstSize(encodedSizeInBits: Int): ULong = { + decodeNonNegativeInteger(encodedSizeInBits) } - - def dec_Int_PositiveInteger_ConstSize_8(): Option[ULong] = { - readByte() match - case None() => None() - case Some(ub) => Some(ub & 0xFF) + def dec_Int_PositiveInteger_ConstSize_8(): ULong = { + readByte().unsignedToInt } - def dec_Int_PositiveInteger_ConstSize_big_endian_N(SizeInBytes: Int): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_big_endian_N(sizeInBytes: Int): ULong = { var ret: ULong = 0 var i: Int = 0 - while i < SizeInBytes do - readByte() match - case None() => return None() - case Some(ub) => - ret <<= 8 - ret |= (ub & 0xFF) + (while i < sizeInBytes do + decreases(sizeInBytes < i) + ret <<= 8 + ret |= readByte().unsignedToInt i += 1 + ).invariant(true) // TODO invariant - Some(ret) + ret } // TODO remove those and call dec_Int_PositiveInteger_ConstSize_big_endian_N directly - def dec_Int_PositiveInteger_ConstSize_big_endian_16(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_big_endian_16(): ULong = { dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_SHORT) } - def dec_Int_PositiveInteger_ConstSize_big_endian_32(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_big_endian_32(): ULong = { dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_INT) } - def dec_Int_PositiveInteger_ConstSize_big_endian_64(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_big_endian_64(): ULong = { dec_Int_PositiveInteger_ConstSize_big_endian_N(NO_OF_BYTES_IN_JVM_LONG) } - def dec_Int_PositiveInteger_ConstSize_little_endian_N(SizeInBytes: Int): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_little_endian_N(sizeInBytes: Int): ULong = { var ret: ULong = 0 - var tmp: ULong = 0 + var tmp: ULong = 0 // TODO is this var even needed? var i: Int = 0 - while i < SizeInBytes do - readByte() match - case None() => return None() - case Some(ub) => - tmp = ub & 0xFF - tmp <<= i * 8 - ret |= tmp + (while i < sizeInBytes do + decreases(sizeInBytes - i) + tmp = readByte().unsignedToInt + tmp <<= i * 8 + ret |= tmp i += 1 + ).invariant(true) // TODO invariant - Some(ret) + ret } - def dec_Int_PositiveInteger_ConstSize_little_endian_16(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_little_endian_16(): ULong = { dec_Int_PositiveInteger_ConstSize_little_endian_N(2) } - def dec_Int_PositiveInteger_ConstSize_little_endian_32(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_little_endian_32(): ULong = { dec_Int_PositiveInteger_ConstSize_little_endian_N(4) } - def dec_Int_PositiveInteger_ConstSize_little_endian_64(): Option[ULong] = { + def dec_Int_PositiveInteger_ConstSize_little_endian_64(): ULong = { dec_Int_PositiveInteger_ConstSize_little_endian_N(NO_OF_BYTES_IN_JVM_LONG) } - def encode_UnsignedInteger(v: ULong, nBytes: Byte): Unit = { val MAX_BYTE_MASK = 0xFF00000000000000L assert(nBytes <= 8) @@ -168,7 +159,6 @@ case class ACN(bitStream: BitStream) extends Codec { i += 1 } - def enc_Int_PositiveInteger_VarSize_LengthEmbedded(intVal: ULong): Unit = { val nBytes: Byte = GetLengthForEncodingUnsigned(intVal).toByte @@ -178,21 +168,19 @@ case class ACN(bitStream: BitStream) extends Codec { encode_UnsignedInteger(intVal, nBytes) } - def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): Option[ULong] = { + def dec_Int_PositiveInteger_VarSize_LengthEmbedded(): ULong = { var v: ULong = 0 - readByte() match - case None() => return None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - readByte() match - case None() => return None() - case Some(ub) => - v = (v << 8) | (ub & 0xFF) - i += 1 + val nBytes = readByte() + var i: Int = 0 + + (while i < nBytes do + decreases(nBytes - i) + v = (v << 8) | readByte().unsignedToInt + i += 1 + ).invariant(true) // TODO invariant - Some(v) + v } @@ -235,11 +223,8 @@ case class ACN(bitStream: BitStream) extends Codec { enc_Int_PositiveInteger_ConstSize_little_endian_64(int2uint(intVal)) } - def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Option[Long] = { - var valIsNegative: Boolean = false - peekBit() match - case Some(b) => valIsNegative = b - case None() => assert(false) + def dec_Int_TwosComplement_ConstSize(encodedSizeInBits: Int): Long = { + val valIsNegative = peekBit() val nBytes: Int = encodedSizeInBits / 8 val rstBits: Int = encodedSizeInBits % 8 @@ -247,66 +232,47 @@ case class ACN(bitStream: BitStream) extends Codec { var pIntVal: Long = if valIsNegative then Long.MaxValue else 0 var i: Int = 0 - while i < nBytes do - readByte() match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << 8) | (ub & 0xFF) + (while i < nBytes do + decreases(nBytes - i) + pIntVal = (pIntVal << 8) | (readByte().unsignedToInt) i += 1 + ).invariant(true) // TODO invariant if rstBits > 0 then - readPartialByte(rstBits.toByte) match - case None() => return None() - case Some(ub) => - pIntVal = (pIntVal << rstBits) | (ub & 0xFF) + pIntVal = (pIntVal << rstBits) | (readPartialByte(rstBits.toByte) & 0xFF) - Some(pIntVal) + pIntVal } - def dec_Int_TwosComplement_ConstSize_8(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 1)) + def dec_Int_TwosComplement_ConstSize_8(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_8(), 1) } - def dec_Int_TwosComplement_ConstSize_big_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) + def dec_Int_TwosComplement_ConstSize_big_endian_16(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_big_endian_16(), NO_OF_BYTES_IN_JVM_SHORT) } - def dec_Int_TwosComplement_ConstSize_big_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) + def dec_Int_TwosComplement_ConstSize_big_endian_32(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_big_endian_32(), NO_OF_BYTES_IN_JVM_INT) } - def dec_Int_TwosComplement_ConstSize_big_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + def dec_Int_TwosComplement_ConstSize_big_endian_64(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_big_endian_64(), NO_OF_BYTES_IN_JVM_LONG) } - def dec_Int_TwosComplement_ConstSize_little_endian_16(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 2)) + def dec_Int_TwosComplement_ConstSize_little_endian_16(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_little_endian_16(), NO_OF_BYTES_IN_JVM_SHORT) } - def dec_Int_TwosComplement_ConstSize_little_endian_32(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(ul) => Some(uint2int(ul, 4)) + def dec_Int_TwosComplement_ConstSize_little_endian_32(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_little_endian_32(), NO_OF_BYTES_IN_JVM_INT) } - def dec_Int_TwosComplement_ConstSize_little_endian_64(): Option[Long] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(ul) => Some(uint2int(ul, NO_OF_BYTES_IN_JVM_LONG)) + def dec_Int_TwosComplement_ConstSize_little_endian_64(): Long = { + uint2int(dec_Int_PositiveInteger_ConstSize_little_endian_64(), NO_OF_BYTES_IN_JVM_LONG) } - def enc_Int_TwosComplement_VarSize_LengthEmbedded(intVal: Long): Unit = { val nBytes: Byte = GetLengthForEncodingSigned(intVal).toByte @@ -316,32 +282,30 @@ case class ACN(bitStream: BitStream) extends Codec { encode_UnsignedInteger(int2uint(intVal), nBytes) } - - def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Option[Long] = { + def dec_Int_TwosComplement_VarSize_LengthEmbedded(): Long = { var v: ULong = 0 var isNegative: Boolean = false - readByte() match - case None() => None() - case Some(nBytes) => - var i: Int = 0 - while i < nBytes do - readByte() match - case None() => return None() - case Some(ub) => - if i == 0 && (ub & 0x80) > 0 then - v = Long.MaxValue - isNegative = true + val nBytes = readByte() - v = (v << 8) | (ub & 0xFF) - i += 1 + var i: Int = 0 + (while i < nBytes do + decreases(nBytes - i) + val ub = readByte() - if isNegative then - Some(-(~v) - 1) - else - Some(v) - } + if i == 0 && (ub.unsignedToInt) > 0 then + v = Long.MaxValue + isNegative = true + + v = (v << 8) | (ub & 0xFF) + i += 1 + ).invariant(true) // TODO invariant + if isNegative then + -(~v) - 1 // TODO fixme + else + v + } //return values is in nibbles def get_Int_Size_BCD(intVal: ULong): Int = { @@ -376,19 +340,19 @@ case class ACN(bitStream: BitStream) extends Codec { } - def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): Option[ULong] = { - var ret: ULong = 0 + def dec_Int_BCD_ConstSize(encodedSizeInNibbles: Int): ULong = { + var l: ULong = 0 var encodedSizeInNibblesVar = encodedSizeInNibbles - while encodedSizeInNibblesVar > 0 do - readPartialByte(4) match - case None() => return None() - case Some(digit) => - ret *= 10 - ret += digit - encodedSizeInNibblesVar -= 1 - Some(ret) + (while encodedSizeInNibblesVar > 0 do + decreases(encodedSizeInNibblesVar) + + l *= 10 + l += readPartialByte(4) + encodedSizeInNibblesVar -= 1 + ).invariant(true) // TODO invariant + l } @@ -402,10 +366,8 @@ case class ACN(bitStream: BitStream) extends Codec { } - def dec_Int_BCD_VarSize_LengthEmbedded(): Option[ULong] = { - readByte() match - case None() => None() - case Some(nNibbles) => dec_Int_BCD_ConstSize(nNibbles) + def dec_Int_BCD_VarSize_LengthEmbedded(): ULong = { + dec_Int_BCD_ConstSize(readByte()) } @@ -420,23 +382,20 @@ case class ACN(bitStream: BitStream) extends Codec { appendPartialByte(0xF, 4) } - def dec_Int_BCD_VarSize_NullTerminated(): Option[ULong] = { - var ret: ULong = 0 + def dec_Int_BCD_VarSize_NullTerminated(): ULong = { + var l: ULong = 0 while true do - readPartialByte(4) match - case None() => return None() - case Some(digit) => - if (digit > 9) - return Some(ret) + val digit = readPartialByte(4) + if (digit > 9) + return l - ret *= 10 - ret += digit + l *= 10 + l += digit - Some(ret) + l } - def enc_UInt_ASCII_ConstSize(intVal: ULong, encodedSizeInBytes: Int): Unit = { var intVar = intVal var totalNibbles: Int = 0 @@ -467,39 +426,37 @@ case class ACN(bitStream: BitStream) extends Codec { enc_UInt_ASCII_ConstSize(absIntVal, encodedSizeInBytes - 1) } - def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[ULong] = { + def dec_UInt_ASCII_ConstSize(encodedSizeInBytes: Int): ULong = { var encodedSizeInBytesVar = encodedSizeInBytes var ret: ULong = 0 - while encodedSizeInBytesVar > 0 do - readByte() match - case None() => return None() - case Some(digit) => - assert(digit >= CHAR_ZERO && digit <= CHAR_NINE) + (while encodedSizeInBytesVar > 0 do + decreases(encodedSizeInBytesVar) + val digit = readByte() - ret *= 10 - ret += (digit.toInt - CHAR_ZERO).toByte + assert(digit >= CHAR_ZERO && digit <= CHAR_NINE) + + ret *= 10 + ret += (digit.toInt - CHAR_ZERO).toByte encodedSizeInBytesVar -= 1 + ).invariant(true) // TODO invariant - Some(ret) + ret } - def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Option[Long] = { - readByte() match - case None() => None() - case Some(digit) => - var sign: Int = 1 - if digit == CHAR_PLUS then - sign = 1 - else if digit == CHAR_MINUS then - sign = -1 - else - assert(false) + def dec_SInt_ASCII_ConstSize(encodedSizeInBytes: Int): Long = { + val digit = readByte() - dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) match - case None() => None() - case Some(ul) => Some(sign * ul) + var sign: Int = 1 + if digit == CHAR_PLUS then + sign = 1 + else if digit == CHAR_MINUS then + sign = -1 + else + assert(false) + + sign * dec_UInt_ASCII_ConstSize(encodedSizeInBytes - 1) } @@ -559,18 +516,8 @@ case class ACN(bitStream: BitStream) extends Codec { } - def dec_UInt_ASCII_VarSize_LengthEmbedded(): Option[ULong] = { - readByte() match - case None() => None() - case Some(nChars) => dec_UInt_ASCII_ConstSize(nChars) - } - - def dec_SInt_ASCII_VarSize_LengthEmbedded(): Option[Long] = { - readByte() match - case None() => None() - case Some(nChars) => dec_SInt_ASCII_ConstSize(nChars) - } - + def dec_UInt_ASCII_VarSize_LengthEmbedded(): ULong = dec_UInt_ASCII_ConstSize(readByte()) + def dec_SInt_ASCII_VarSize_LengthEmbedded(): Long = dec_SInt_ASCII_ConstSize(readByte()) def enc_UInt_ASCII_VarSize_NullTerminated(intVal: ULong, null_characters: Array[Byte], null_characters_size: Int): Unit = { val (digitsArray100, nChars) = getIntegerDigits(intVal) @@ -593,7 +540,7 @@ case class ACN(bitStream: BitStream) extends Codec { enc_UInt_ASCII_VarSize_NullTerminated(absValue, null_characters, null_characters_size) } - def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[ULong] = { + def dec_UInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): ULong = { var digit: Byte = 0 var ret: ULong = 0 val tmp: Array[Byte] = Array.fill(10)(0) @@ -602,11 +549,11 @@ case class ACN(bitStream: BitStream) extends Codec { //read null_character_size characters into the tmp buffer var j: Int = 0 - while j < null_characters_size do - readByte() match - case None() => return None() - case Some(ub) => tmp(j) = ub + (while j < null_characters_size do + decreases(null_characters_size - j) + tmp(j) = readByte() j += 1 + ).invariant(true) // TODO invariant var i: Long = 0 while !arraySameElements(null_characters, tmp) do @@ -618,77 +565,67 @@ case class ACN(bitStream: BitStream) extends Codec { tmp(j) = tmp(j + 1) j += 1 - readByte() match - case None() => return None() - case Some(ub) => tmp(null_characters_size - 1) = ub + tmp(null_characters_size - 1) = readByte() digit = (digit - CHAR_ZERO).toByte ret *= 10 ret += digit - Some(ret) + ret } - def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Option[Long] = { + def dec_SInt_ASCII_VarSize_NullTerminated(null_characters: Array[Byte], null_characters_size: Int): Long = { var isNegative: Boolean = false - readByte() match - case None() => None() - case Some(digit) => - assert(digit == CHAR_MINUS || digit == CHAR_PLUS) - if digit == CHAR_MINUS then - isNegative = true + val digit = readByte() + assert(digit == CHAR_MINUS || digit == CHAR_PLUS) + if digit == CHAR_MINUS then + isNegative = true - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(ul) => Some(if isNegative then -ul else ul) + val ul = dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) + if isNegative then -ul else ul } /* Boolean Decode */ // TODO move to codec? - def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Option[Boolean] = { + def BitStream_ReadBitPattern(patternToRead: Array[Byte], nBitsToRead: Int): Boolean = { val nBytesToRead: Int = nBitsToRead / 8 val nRemainingBitsToRead: Int = nBitsToRead % 8 var pBoolValue: Boolean = true var i: Int = 0 - while i < nBytesToRead do - readByte() match - case None() => return None() - case Some(curByte) => - if curByte != patternToRead(i) then - pBoolValue = false + (while i < nBytesToRead do + decreases(nBytesToRead - i) + if readByte() != patternToRead(i) then + pBoolValue = false i += 1 + ).invariant(true) // TODO if nRemainingBitsToRead > 0 then - readPartialByte(nRemainingBitsToRead.toByte) match - case None() => return None() - case Some(curByte) => - if curByte != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then - pBoolValue = false + if readPartialByte(nRemainingBitsToRead.toByte) != ((patternToRead(nBytesToRead) & 0xFF) >>> (8 - nRemainingBitsToRead)) then + pBoolValue = false - Some(pBoolValue) + pBoolValue } // TODO move to codec? - def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Either[ErrorCode, Int] = { + def BitStream_ReadBitPattern_ignore_value(nBitsToRead: Int): Unit = { + // TODO replace implementation with readBits(nBitsToRead)? val nBytesToRead: Int = nBitsToRead / 8 val nRemainingBitsToRead: Int = nBitsToRead % 8 var i: Int = 0 - while i < nBytesToRead do - readByte() match - case None() => return Left(FAILED_READ_ERR_CODE) - case Some(_) => i += 1 + (while i < nBytesToRead do + decreases(nBytesToRead - i) + readByte() + i += 1 + ).invariant(true) // TODO invariant if nRemainingBitsToRead > 0 then - if readPartialByte(nRemainingBitsToRead.toByte).isEmpty then - return Left(FAILED_READ_ERR_CODE) - - Right(0) + readPartialByte(nRemainingBitsToRead.toByte) } /* Real encoding functions */ @@ -729,68 +666,64 @@ case class ACN(bitStream: BitStream) extends Codec { } /* Real decoding functions */ - def dec_Real_IEEE754_32_big_endian(): Option[Float] = { + def dec_Real_IEEE754_32_big_endian(): Float = { var ret: Int = 0 var i: Int = 1 assert(NO_OF_BYTES_IN_JVM_INT == NO_OF_BYTES_IN_JVM_FLOAT) - while i <= NO_OF_BYTES_IN_JVM_INT do - readByte() match - case None() => return None() - case Some(b) => - ret |= b.unsignedToInt << (NO_OF_BYTES_IN_JVM_INT - i) * NO_OF_BITS_IN_BYTE + (while i <= NO_OF_BYTES_IN_JVM_INT do + decreases(NO_OF_BYTES_IN_JVM_INT - i) + ret |= readByte().unsignedToInt << (NO_OF_BYTES_IN_JVM_INT - i) * NO_OF_BITS_IN_BYTE i += 1 + ).invariant(true) // TODO - Some(java.lang.Float.intBitsToFloat(ret)) + java.lang.Float.intBitsToFloat(ret) } - def dec_Real_IEEE754_32_little_endian(): Option[Float] = { + def dec_Real_IEEE754_32_little_endian(): Float = { var ret: Int = 0 var i: Int = 0 assert(NO_OF_BYTES_IN_JVM_INT == NO_OF_BYTES_IN_JVM_FLOAT) - while i < NO_OF_BYTES_IN_JVM_INT do - readByte() match - case None() => return None() - case Some(b) => - ret |= b.unsignedToInt << i * NO_OF_BITS_IN_BYTE + (while i < NO_OF_BYTES_IN_JVM_INT do + decreases(NO_OF_BYTES_IN_JVM_INT - i) + ret |= readByte().unsignedToInt << i * NO_OF_BITS_IN_BYTE i += 1 + ).invariant(true) // TODO - Some(java.lang.Float.intBitsToFloat(ret)) + java.lang.Float.intBitsToFloat(ret) } - def dec_Real_IEEE754_64_big_endian(): Option[Double] = { + def dec_Real_IEEE754_64_big_endian(): Double = { var ret: Long = 0 var i: Int = 1 assert(NO_OF_BYTES_IN_JVM_LONG == NO_OF_BYTES_IN_JVM_DOUBLE) - while i <= NO_OF_BYTES_IN_JVM_LONG do - readByte() match - case None() => return None() - case Some(b) => - ret |= b.unsignedToLong << (NO_OF_BYTES_IN_JVM_LONG - i) * NO_OF_BITS_IN_BYTE + (while i <= NO_OF_BYTES_IN_JVM_LONG do + decreases(NO_OF_BYTES_IN_JVM_LONG - i) + ret |= readByte().unsignedToLong << (NO_OF_BYTES_IN_JVM_LONG - i) * NO_OF_BITS_IN_BYTE i += 1 + ).invariant(true) // TODO - Some(java.lang.Double.longBitsToDouble(ret)) + java.lang.Double.longBitsToDouble(ret) } - def dec_Real_IEEE754_64_little_endian(): Option[Double] = { + def dec_Real_IEEE754_64_little_endian(): Double = { var ret: Long = 0 var i: Int = 0 assert(NO_OF_BYTES_IN_JVM_LONG == NO_OF_BYTES_IN_JVM_DOUBLE) - while i < NO_OF_BYTES_IN_JVM_LONG do - readByte() match - case None() => return None() - case Some(b) => - ret |= b.unsignedToLong << i * NO_OF_BITS_IN_BYTE + (while i < NO_OF_BYTES_IN_JVM_LONG do + decreases(NO_OF_BYTES_IN_JVM_LONG - i) + ret |= readByte().unsignedToLong << i * NO_OF_BITS_IN_BYTE i += 1 + ).invariant(true) // TODO - Some(java.lang.Double.longBitsToDouble(ret)) + java.lang.Double.longBitsToDouble(ret) } /* String functions*/ @@ -906,117 +839,109 @@ case class ACN(bitStream: BitStream) extends Codec { } - def dec_String_Ascii_private(max: Long, charactersToDecode: Long): OptionMut[Array[ASCIIChar]] = { + def dec_String_Ascii_private(max: Long, charactersToDecode: Long): Array[ASCIIChar] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 - while i < charactersToDecode do - readByte() match - case None() => return NoneMut() - case Some(decodedCharacter) => - strVal(i) = decodedCharacter + (while i < charactersToDecode do + decreases(charactersToDecode - i) + strVal(i) = readByte() i += 1 - SomeMut(strVal) + ).invariant(true) // TODO + + strVal } - def dec_String_Ascii_FixSize(max: Long): OptionMut[Array[ASCIIChar]] = { + def dec_String_Ascii_FixSize(max: Long): Array[ASCIIChar] = { dec_String_Ascii_private(max, max) } - def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): OptionMut[Array[ASCIIChar]] = { + def dec_String_Ascii_Null_Teminated(max: Long, null_character: ASCIIChar): Array[ASCIIChar] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) + var endReached = false var i: Int = 0 - while i <= max do - readByte() match - case None() => return NoneMut() - case Some(decodedCharacter) => - if decodedCharacter != null_character then - strVal(i) = decodedCharacter - i += 1 - else - strVal(i) = 0x0 - return SomeMut(strVal) - - NoneMut() + (while i <= max && endReached do + val decodedCharacter = readByte() + if decodedCharacter != null_character then + strVal(i) = decodedCharacter + i += 1 + else + strVal(i) = 0x0 + endReached = true + ).invariant(true) // TODO + strVal } - def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): OptionMut[Array[ASCIIChar]] = { + def dec_String_Ascii_Null_Teminated_mult(max: Long, null_character: Array[ASCIIChar], null_character_size: Int): Array[ASCIIChar] = { val tmp: Array[Byte] = Array.fill(null_character_size)(0) val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) //read null_character_size characters into the tmp buffer + var j: Int = 0 - while j < null_character_size do - readByte() match - case None() => return NoneMut() - case Some(ub) => tmp(j) = ub + (while j < null_character_size do + decreases(null_character_size - j) + tmp(j) = readByte() j += 1 - + ).invariant(true) // TODO var i: Int = 0 while i <= max && !arraySameElements(null_character, tmp) do strVal(i) = tmp(0) i += 1 j = 0 - while j < null_character_size - 1 do + (while j < null_character_size - 1 do + decreases(null_character_size - j) tmp(j) = tmp(j + 1) j += 1 - - readByte() match - case None() => return NoneMut() - case Some(ub) => tmp(null_character_size - 1) = ub + ).invariant(true) // TODO + tmp(null_character_size - 1) = readByte() strVal(i) = 0x0 - if !arraySameElements(null_character, tmp) then - return NoneMut() + assert(arraySameElements(null_character, tmp)) - SomeMut(strVal) + strVal } - def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { + def dec_String_Ascii_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Array[ASCIIChar] = { dec_String_Ascii_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max) } - def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): OptionMut[Array[ASCIIChar]] = { - decodeConstrainedWholeNumber(min, max) match - case None() => NoneMut() - case Some(nCount) => - dec_String_Ascii_private(max, if nCount <= max then nCount else max) + def dec_String_Ascii_Internal_Field_Determinant(max: Long, min: Long): Array[ASCIIChar] = { + val nCount = decodeConstrainedWholeNumber(min, max) + dec_String_Ascii_private(max, if nCount <= max then nCount else max) } - def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): OptionMut[Array[ASCIIChar]] = { + def dec_String_CharIndex_private(max: Long, charactersToDecode: Long, allowedCharSet: Array[Byte]): Array[ASCIIChar] = { val strVal: Array[ASCIIChar] = Array.fill(max.toInt + 1)(0) var i: Int = 0 - while i < charactersToDecode do - decodeConstrainedWholeNumber(0, allowedCharSet.length - 1) match - case None() => return NoneMut() - case Some(charIndex) => - strVal(i) = allowedCharSet(charIndex.toInt) + (while i < charactersToDecode do + decreases(charactersToDecode - i) + strVal(i) = allowedCharSet(decodeConstrainedWholeNumber(0, allowedCharSet.length - 1).toInt) i += 1 + ).invariant(true) // TODO - SomeMut(strVal) + strVal } - def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): OptionMut[Array[ASCIIChar]] = { + def dec_String_CharIndex_FixSize(max: Long, allowedCharSet: Array[ASCIIChar]): Array[ASCIIChar] = { dec_String_CharIndex_private(max, max, allowedCharSet) } - def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { + def dec_String_CharIndex_External_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], extSizeDeterminatFld: Long): Array[ASCIIChar] = { dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) } - def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): OptionMut[Array[ASCIIChar]] = { - decodeConstrainedWholeNumber(min, max) match - case None() => NoneMut() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + def dec_String_CharIndex_Internal_Field_Determinant(max: Long, allowedCharSet: Array[ASCIIChar], min: Long): Array[ASCIIChar] = { + val nCount = decodeConstrainedWholeNumber(min, max) + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) } - def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): OptionMut[Array[ASCIIChar]] = { + def dec_IA5String_CharIndex_External_Field_Determinant(max: Long, extSizeDeterminatFld: Long): Array[ASCIIChar] = { val allowedCharSet: Array[ASCIIChar] = Array( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, @@ -1035,7 +960,7 @@ case class ACN(bitStream: BitStream) extends Codec { dec_String_CharIndex_private(max, if extSizeDeterminatFld <= max then extSizeDeterminatFld else max, allowedCharSet) } - def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): OptionMut[Array[ASCIIChar]] = { + def dec_IA5String_CharIndex_Internal_Field_Determinant(max: Long, min: Long): Array[ASCIIChar] = { val allowedCharSet: Array[ASCIIChar] = Array( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, @@ -1051,10 +976,8 @@ case class ACN(bitStream: BitStream) extends Codec { 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F ) - decodeConstrainedWholeNumber(min, max) match - case None() => NoneMut() - case Some(nCount) => - dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) + val nCount = decodeConstrainedWholeNumber(min, max) + dec_String_CharIndex_private(max, if nCount <= max then nCount else max, allowedCharSet) } @@ -1064,7 +987,7 @@ case class ACN(bitStream: BitStream) extends Codec { enc_Int_PositiveInteger_ConstSize(lengthValue, lengthSizeInBits) } - def dec_Length(lengthSizeInBits: Int): Option[ULong] = { + def dec_Length(lengthSizeInBits: Int): ULong = { dec_Int_PositiveInteger_ConstSize(lengthSizeInBits) } @@ -1076,443 +999,83 @@ case class ACN(bitStream: BitStream) extends Codec { if v == 0 then 32 else v } - def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_8UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): Option[UInt] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): Option[UShort] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): Option[UByte] = { - dec_Int_PositiveInteger_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_PositiveInteger_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Option[Byte] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Option[Short] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Option[Int] = { - dec_Int_TwosComplement_ConstSize(encodedSizeInBits) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_8Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_8() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_big_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_16() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_32() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Option[Int] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Option[Short] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Option[Byte] = { - dec_Int_TwosComplement_ConstSize_little_endian_64() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_Int_TwosComplement_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): Option[UByte] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): Option[UShort] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): Option[UInt] = { - dec_Int_BCD_ConstSize(encodedSizeInNibbles) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt8(): Option[UByte] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt16(): Option[UShort] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_Int_BCD_VarSize_NullTerminatedUInt32(): Option[UInt] = { - dec_Int_BCD_VarSize_NullTerminated() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Option[Byte] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Option[Short] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Option[Int] = { - dec_SInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Option[Byte] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Option[Short] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Option[Int] = { - dec_SInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Option[Byte] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Option[Short] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Option[Int] = { - dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): Option[UByte] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): Option[UShort] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): Option[UInt] = { - dec_UInt_ASCII_ConstSize(encodedSizeInBytes) match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): Option[UByte] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): Option[UShort] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): Option[UInt] = { - dec_UInt_ASCII_VarSize_LengthEmbedded() match - case None() => None() - case Some(v) => Some(v.toInt) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): Option[UByte] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toByte) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): Option[UShort] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toShort) - } - - def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): Option[UInt] = { - dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size) match - case None() => None() - case Some(v) => Some(v.toInt) - } + def dec_Int_PositiveInteger_ConstSizeUInt8(encodedSizeInBits: Int): UByte = dec_Int_PositiveInteger_ConstSize(encodedSizeInBits).toByte + def dec_Int_PositiveInteger_ConstSizeUInt16(encodedSizeInBits: Int): UShort = dec_Int_PositiveInteger_ConstSize(encodedSizeInBits).toShort + def dec_Int_PositiveInteger_ConstSizeUInt32(encodedSizeInBits: Int): UInt = dec_Int_PositiveInteger_ConstSize(encodedSizeInBits).toInt + def dec_Int_PositiveInteger_ConstSize_8UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_8().toByte + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_big_endian_16().toShort + def dec_Int_PositiveInteger_ConstSize_big_endian_16UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_big_endian_16().toByte + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt32(): UInt = dec_Int_PositiveInteger_ConstSize_big_endian_32().toInt + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_big_endian_32().toShort + def dec_Int_PositiveInteger_ConstSize_big_endian_32UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_big_endian_32().toByte + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt32(): UInt = dec_Int_PositiveInteger_ConstSize_big_endian_64().toInt + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_big_endian_64().toShort + def dec_Int_PositiveInteger_ConstSize_big_endian_64UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_big_endian_64().toByte + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_little_endian_16().toShort + def dec_Int_PositiveInteger_ConstSize_little_endian_16UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_little_endian_16().toByte + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt32(): UInt = dec_Int_PositiveInteger_ConstSize_little_endian_32().toInt + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_little_endian_32().toShort + def dec_Int_PositiveInteger_ConstSize_little_endian_32UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_little_endian_32().toByte + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt32(): UInt = dec_Int_PositiveInteger_ConstSize_little_endian_64().toInt + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt16(): UShort = dec_Int_PositiveInteger_ConstSize_little_endian_64().toShort + def dec_Int_PositiveInteger_ConstSize_little_endian_64UInt8(): UByte = dec_Int_PositiveInteger_ConstSize_little_endian_64().toByte + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt8(): UByte = dec_Int_PositiveInteger_VarSize_LengthEmbedded().toByte + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt16(): UShort = dec_Int_PositiveInteger_VarSize_LengthEmbedded().toShort + def dec_Int_PositiveInteger_VarSize_LengthEmbeddedUInt32(): UInt = dec_Int_PositiveInteger_VarSize_LengthEmbedded().toInt + def dec_Int_TwosComplement_ConstSizeInt8(encodedSizeInBits: Int): Byte = dec_Int_TwosComplement_ConstSize(encodedSizeInBits).toByte + def dec_Int_TwosComplement_ConstSizeInt16(encodedSizeInBits: Int): Short = dec_Int_TwosComplement_ConstSize(encodedSizeInBits).toShort + def dec_Int_TwosComplement_ConstSizeInt32(encodedSizeInBits: Int): Int = dec_Int_TwosComplement_ConstSize(encodedSizeInBits).toInt + def dec_Int_TwosComplement_ConstSize_8Int8(): Byte = dec_Int_TwosComplement_ConstSize_8().toByte + def dec_Int_TwosComplement_ConstSize_big_endian_16Int16(): Short = dec_Int_TwosComplement_ConstSize_big_endian_16().toShort + def dec_Int_TwosComplement_ConstSize_big_endian_16Int8(): Byte = dec_Int_TwosComplement_ConstSize_big_endian_16().toByte + def dec_Int_TwosComplement_ConstSize_big_endian_32Int32(): Int = dec_Int_TwosComplement_ConstSize_big_endian_32().toInt + def dec_Int_TwosComplement_ConstSize_big_endian_32Int16(): Short = dec_Int_TwosComplement_ConstSize_big_endian_32().toShort + def dec_Int_TwosComplement_ConstSize_big_endian_32Int8(): Byte = dec_Int_TwosComplement_ConstSize_big_endian_32().toByte + def dec_Int_TwosComplement_ConstSize_big_endian_64Int32(): Int = dec_Int_TwosComplement_ConstSize_big_endian_64().toInt + def dec_Int_TwosComplement_ConstSize_big_endian_64Int16(): Short = dec_Int_TwosComplement_ConstSize_big_endian_64().toShort + def dec_Int_TwosComplement_ConstSize_big_endian_64Int8(): Byte = dec_Int_TwosComplement_ConstSize_big_endian_64().toByte + def dec_Int_TwosComplement_ConstSize_little_endian_16Int16(): Short = dec_Int_TwosComplement_ConstSize_little_endian_16().toShort + def dec_Int_TwosComplement_ConstSize_little_endian_16Int8(): Byte = dec_Int_TwosComplement_ConstSize_little_endian_16().toByte + def dec_Int_TwosComplement_ConstSize_little_endian_32Int32(): Int = dec_Int_TwosComplement_ConstSize_little_endian_32().toInt + def dec_Int_TwosComplement_ConstSize_little_endian_32Int16(): Short = dec_Int_TwosComplement_ConstSize_little_endian_32().toShort + def dec_Int_TwosComplement_ConstSize_little_endian_32Int8(): Byte = dec_Int_TwosComplement_ConstSize_little_endian_32().toByte + def dec_Int_TwosComplement_ConstSize_little_endian_64Int32(): Int = dec_Int_TwosComplement_ConstSize_little_endian_64().toInt + def dec_Int_TwosComplement_ConstSize_little_endian_64Int16(): Short = dec_Int_TwosComplement_ConstSize_little_endian_64().toShort + def dec_Int_TwosComplement_ConstSize_little_endian_64Int8(): Byte = dec_Int_TwosComplement_ConstSize_little_endian_64().toByte + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt8(): Byte = dec_Int_TwosComplement_VarSize_LengthEmbedded().toByte + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt16(): Short = dec_Int_TwosComplement_VarSize_LengthEmbedded().toShort + def dec_Int_TwosComplement_VarSize_LengthEmbeddedInt32(): Int = dec_Int_TwosComplement_VarSize_LengthEmbedded().toInt + def dec_Int_BCD_ConstSizeUInt8(encodedSizeInNibbles: Int): UByte = dec_Int_BCD_ConstSize(encodedSizeInNibbles).toByte + def dec_Int_BCD_ConstSizeUInt16(encodedSizeInNibbles: Int): UShort = dec_Int_BCD_ConstSize(encodedSizeInNibbles).toShort + def dec_Int_BCD_ConstSizeUInt32(encodedSizeInNibbles: Int): UInt = dec_Int_BCD_ConstSize(encodedSizeInNibbles).toInt + def dec_Int_BCD_VarSize_LengthEmbeddedUInt8(): UByte = dec_Int_BCD_VarSize_LengthEmbedded().toByte + def dec_Int_BCD_VarSize_LengthEmbeddedUInt16(): UShort = dec_Int_BCD_VarSize_LengthEmbedded().toShort + def dec_Int_BCD_VarSize_LengthEmbeddedUInt32(): UInt = dec_Int_BCD_VarSize_LengthEmbedded().toInt + def dec_Int_BCD_VarSize_NullTerminatedUInt8(): UByte = dec_Int_BCD_VarSize_NullTerminated().toByte + def dec_Int_BCD_VarSize_NullTerminatedUInt16(): UShort = dec_Int_BCD_VarSize_NullTerminated().toShort + def dec_Int_BCD_VarSize_NullTerminatedUInt32(): UInt = dec_Int_BCD_VarSize_NullTerminated().toInt + def dec_SInt_ASCII_ConstSizeInt8(encodedSizeInBytes: Int): Byte = dec_SInt_ASCII_ConstSize(encodedSizeInBytes).toByte + def dec_SInt_ASCII_ConstSizeInt16(encodedSizeInBytes: Int): Short = dec_SInt_ASCII_ConstSize(encodedSizeInBytes).toShort + def dec_SInt_ASCII_ConstSizeInt32(encodedSizeInBytes: Int): Int = dec_SInt_ASCII_ConstSize(encodedSizeInBytes).toInt + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt8(): Byte = dec_SInt_ASCII_VarSize_LengthEmbedded().toByte + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt16(): Short = dec_SInt_ASCII_VarSize_LengthEmbedded().toShort + def dec_SInt_ASCII_VarSize_LengthEmbeddedInt32(): Int = dec_SInt_ASCII_VarSize_LengthEmbedded().toInt + def dec_SInt_ASCII_VarSize_NullTerminatedInt8(null_characters: Array[Byte], null_characters_size: Int): Byte = + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toByte + def dec_SInt_ASCII_VarSize_NullTerminatedInt16(null_characters: Array[Byte], null_characters_size: Int): Short = + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toShort + def dec_SInt_ASCII_VarSize_NullTerminatedInt32(null_characters: Array[Byte], null_characters_size: Int): Int = + dec_SInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toInt + def dec_UInt_ASCII_ConstSizeUInt8(encodedSizeInBytes: Int): UByte = dec_UInt_ASCII_ConstSize(encodedSizeInBytes).toByte + def dec_UInt_ASCII_ConstSizeUInt16(encodedSizeInBytes: Int): UShort = dec_UInt_ASCII_ConstSize(encodedSizeInBytes).toShort + def dec_UInt_ASCII_ConstSizeUInt32(encodedSizeInBytes: Int): UInt = dec_UInt_ASCII_ConstSize(encodedSizeInBytes).toInt + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt8(): UByte = dec_UInt_ASCII_VarSize_LengthEmbedded().toByte + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt16(): UShort = dec_UInt_ASCII_VarSize_LengthEmbedded().toShort + def dec_UInt_ASCII_VarSize_LengthEmbeddedUInt32(): UInt = dec_UInt_ASCII_VarSize_LengthEmbedded().toInt + def dec_UInt_ASCII_VarSize_NullTerminatedUInt8(null_characters: Array[Byte], null_characters_size: Int): UByte = + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toByte + def dec_UInt_ASCII_VarSize_NullTerminatedUInt16(null_characters: Array[Byte], null_characters_size: Int): UShort = + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toShort + def dec_UInt_ASCII_VarSize_NullTerminatedUInt32(null_characters: Array[Byte], null_characters_size: Int): UInt = + dec_UInt_ASCII_VarSize_NullTerminated(null_characters, null_characters_size).toInt } diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala index edd0b1ee0..05d5f6002 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec_UPER.scala @@ -94,107 +94,83 @@ case class UPER(bitStream: BitStream) extends Codec { i += 1 } - def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): Option[(Long, ULong)] = { + def objectIdentifier_subIdentifiers_decode(pRemainingOctetsVal: Long): (Long, ULong) = { var bLastOctet: Boolean = false var curOctetValue: ULong = 0 var siValue: ULong = 0 var pRemainingOctets: Long = pRemainingOctetsVal - while pRemainingOctets > 0 && !bLastOctet do + + (while pRemainingOctets > 0 && !bLastOctet do decreases(pRemainingOctets) - readByte() match - case None() => return None() - case Some(curByte) => - pRemainingOctets -= 1 + val curByte = readByte() + pRemainingOctets -= 1 - bLastOctet = (curByte & 0x80) == 0 - curOctetValue = (curByte & 0x7F).toLong - siValue = siValue << 7 - siValue |= curOctetValue + bLastOctet = (curByte & 0x80) == 0 + curOctetValue = (curByte & 0x7F).toLong + siValue = siValue << 7 + siValue |= curOctetValue + ).invariant(true) // TODO - return Some((pRemainingOctets, siValue)) + (pRemainingOctets, siValue) } - def objectIdentifier_decode_length(): Option[Long] = { - var totalSize: Long = 0 + def objectIdentifier_decode_length(): Long = { - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return None() - case Some(l) => totalSize = l + var totalSize = decodeConstrainedWholeNumber(0, 0xFF) if totalSize > 0x7F then - decodeConstrainedWholeNumber(0, 0xFF) match - case None() => return None() - case Some(l) => - totalSize <<= 8 - totalSize |= l - totalSize &= 0x7FFF - - return Some(totalSize) - } + totalSize <<= 8 + totalSize |= decodeConstrainedWholeNumber(0, 0xFF) + totalSize &= 0x7FFF - def objectIdentifier_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 + totalSize + } + def objectIdentifier_decode(): Asn1ObjectIdentifier = { val pVal = ObjectIdentifier_Init() - - objectIdentifier_decode_length() match - case None() => return NoneMut() - case Some(l) => totalSize = l - - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul + var (totalSize, si) = objectIdentifier_subIdentifiers_decode(objectIdentifier_decode_length()) pVal.nCount = 2 pVal.values(0) = si / 40 pVal.values(1) = si % 40 - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + (while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul + val tpl = objectIdentifier_subIdentifiers_decode(totalSize) + + totalSize = tpl._1 + si = tpl._2 pVal.values(pVal.nCount) = si pVal.nCount += 1 + ).invariant(true) // TODO //return true, if totalSize reduced to zero. Otherwise we exit the loop because more components we present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() + assert(totalSize == 0) + pVal } - def relativeOID_decode(): OptionMut[Asn1ObjectIdentifier] = { - var si: ULong = 0 - var totalSize: Long = 0 + def relativeOID_decode(): Asn1ObjectIdentifier = { val pVal: Asn1ObjectIdentifier = ObjectIdentifier_Init() - objectIdentifier_decode_length() match - case None() => return NoneMut() - case Some(l) => totalSize = l + var totalSize = objectIdentifier_decode_length() + var si: ULong = 0 - while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do + (while totalSize > 0 && pVal.nCount < OBJECT_IDENTIFIER_MAX_LENGTH do decreases(OBJECT_IDENTIFIER_MAX_LENGTH - pVal.nCount) - objectIdentifier_subIdentifiers_decode(totalSize) match - case None() => return NoneMut() - case Some((l, ul)) => - totalSize = l - si = ul + val tpl = objectIdentifier_subIdentifiers_decode(totalSize) + + totalSize = tpl._1 + si = tpl._2 + pVal.values(pVal.nCount) = si pVal.nCount += 1 + ).invariant(true) // TODO //return true, if totalSize is zero. Otherwise we exit the loop because more components were present than OBJECT_IDENTIFIER_MAX_LENGTH - if totalSize == 0 then - SomeMut(pVal) - else - NoneMut() + assert(totalSize == 0) + pVal } } From 5a92888157657133a31e37189b3f44bdccd57dfd Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 15 Jan 2024 19:21:41 +0100 Subject: [PATCH 132/174] fixed return value stainless problem extended range for non constrained numbers --- .../main/scala/asn1scala/asn1jvm_Codec.scala | 64 ++++++++++--------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 9c6429b8a..3fe7f4dd3 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -76,13 +76,14 @@ trait Codec { /** ******************************************************************************************** */ /** ******************************************************************************************** */ + def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { var cc: UInt = 0 var curMask: UInt = 0 var pbits: UInt = 0 if v == 0 then - return () + return; if v >>> 8 == 0 then cc = 8 @@ -190,6 +191,14 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } + @extern + def rangeCheck(min: Long, max: Long): Boolean = { + val bigMin = scala.math.BigInt(min) + val bigMax = scala.math.BigInt(max) + + (bigMax - bigMin) <= scala.math.BigInt(Long.MaxValue) + } + /** * * @param v number that gets encoded, needs to be within [min,max] range @@ -202,12 +211,8 @@ trait Codec { */ def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) - require( - min >= 0 && max >= 0 || - min < 0 && max < 0 || - min <= (Long.MaxValue >> 1) && max <= min + (Long.MaxValue >> 1) - ) require(min <= v && v <= max) + require(rangeCheck(min, max)) val range = max - min if range == 0 then @@ -227,11 +232,7 @@ trait Codec { def decodeConstrainedWholeNumber(min: Long, max: Long): Long = { require(min <= max) - require( - min >= 0 && max >= 0 || - min < 0 && max < 0 || - min <= (Long.MaxValue >> 1) && max <= min + (Long.MaxValue >> 1) - ) + require(rangeCheck(min, max)) val range: Long = max - min @@ -371,7 +372,7 @@ trait Codec { // encode length - single octet appendByte(nBytes.toByte) - var i = nBytes; + var i = nBytes (while i > 0 do decreases(i) @@ -529,6 +530,7 @@ trait Codec { encodeNonNegativeInteger(mantissa) } + /** * facade function for real decoding * @return decoded real value in IE754 double format @@ -546,7 +548,7 @@ trait Codec { // get length val length = readByte() - // 8.5.2 Plus Zero + // 8.5.2 PLUS-ZERO if length == 0 then return 0 @@ -554,23 +556,24 @@ trait Codec { assert(length > 0 && length <= DoubleMaxLengthOfSentBytes) // get value - val retVal = readByte() match - // 8.5.6 a) - case header if (header.unsignedToInt & 0x80) == 0x80 => header match - // 8.5.9 PLUS-INFINITY - case header if header == 0x40 => Right(DoublePosInfBitString) - // 8.5.9 MINUS-INFINITY - case header if header == 0x41 => Right(DoubleNegInfBitString) - // 8.5.9 NOT-A-NUMBER - case header if header == 0x42 => Right(DoubleNotANumber) - // 8.5.3 MINUS-ZERO - case header if header == 0x43 => Right(DoubleNegZeroBitString) - // Decode 8.5.7 - case header => Right(decodeRealFromBitStream(length.toInt - 1, header)) - case _ => Left(0) - - assert(retVal.isRight, "only binary mode supported") - retVal.get + val header = readByte() + assert((header.unsignedToInt & 0x80) == 0x80, "only binary mode supported") + + // 8.5.9 PLUS-INFINITY + if header == 0x40 then + DoublePosInfBitString + // 8.5.9 MINUS-INFINITY + else if header == 0x41 then + DoubleNegInfBitString + // 8.5.9 NOT-A-NUMBER + else if header == 0x42 then + DoubleNotANumber + // 8.5.3 MINUS-ZERO + else if header == 0x43 then + DoubleNegZeroBitString + // Decode 8.5.7 + else + decodeRealFromBitStream(length.toInt - 1, header) } /** @@ -972,6 +975,7 @@ trait Codec { bitStream.appendByte(value) } + def readByte(): Byte = { require(bitStream.validate_offset_byte()) bitStream.readByte() From 2d0c1d1bb1ef6e1beffc3bfdc33e04c86a65dd3a Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 15 Jan 2024 19:22:49 +0100 Subject: [PATCH 133/174] compatibility to C interop (unsigned / signed) --- PUSCScalaTest/Testframework.cs | 123 +++++++++++++++++++++++++++------ 1 file changed, 102 insertions(+), 21 deletions(-) diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index a16a7c032..16bf70699 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -40,9 +40,9 @@ class TestBasics private readonly string cLang = "-c"; private readonly string uperEnc = "--uper-enc"; private readonly string acnEnc = "--acn-enc"; - private readonly string genTests= "-atc"; + private readonly string genTests = "-atc"; private readonly List stdArgs = new List { "--field-prefix", "AUTO", "--type-prefix", "T", "-o" }; - + private readonly string outFolderPrefix = "../../../../PUSCScalaTest/GenTests/"; private readonly string outFolderTestFix = "Test/"; private readonly string outFolderSuffixUPER = "UPER/PUSC_"; @@ -50,10 +50,10 @@ class TestBasics private readonly string outFolderSuffixScala = "/Scala"; private readonly string outFolderSuffixC = "/C"; private readonly string inputFilePrefix = "../../../../PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/"; - + private readonly string asn1FileEnding = ".asn1"; private readonly string acnFileEnding = ".acn"; - + private readonly string cConfig = "release"; private readonly string cProject = "VsProject"; @@ -68,7 +68,7 @@ private string[] CombineArgs(string outputFolder, string[] files, ServiceVariati if ((sv & ServiceVariation.UPER) == ServiceVariation.UPER) parList.Add(uperEnc); - + if ((sv & ServiceVariation.ACN) == ServiceVariation.ACN) parList.Add(acnEnc); @@ -77,7 +77,7 @@ private string[] CombineArgs(string outputFolder, string[] files, ServiceVariati parList.AddRange(stdArgs); parList.Add(outputFolder); - + // add asn1 input var asn1Files = files.Select(s => inputFilePrefix + s + asn1FileEnding); parList.AddRange(asn1Files.Where(s => File.Exists(s))); @@ -89,7 +89,7 @@ private string[] CombineArgs(string outputFolder, string[] files, ServiceVariati if ((sv & ServiceVariation.ACN) == ServiceVariation.ACN) { var acnFiles = files.Select(s => inputFilePrefix + s + acnFileEnding); parList.AddRange(acnFiles.Where(s => File.Exists(s))); - + var missingACNFiles = acnFiles.Where(s => !File.Exists(s)); if (missingACNFiles.Count() > 0) Console.WriteLine("WARNING: ACN Files not found: " + String.Join(",", missingACNFiles)); @@ -106,7 +106,7 @@ public string GetOutputFolder(string serviceName, ServiceVariation sv) ret += outFolderTestFix; if ((sv & ServiceVariation.UPER) == ServiceVariation.UPER) - ret += outFolderSuffixUPER; + ret += outFolderSuffixUPER; if ((sv & ServiceVariation.ACN) == ServiceVariation.ACN) ret += outFolderSuffixACN; @@ -138,8 +138,8 @@ public void Run_TestService(PUS_C_Service service, string folderSuffix, ServiceV var cOutputDir = getCleanWorkingFolderPath(folderSuffix, sv & ~ServiceVariation.CREATE_SCALA); Run_Test(service, cOutputDir, sv & ~ServiceVariation.CREATE_SCALA); - if((sv & ServiceVariation.COMPARE_ENCODINGS) == ServiceVariation.COMPARE_ENCODINGS) - compareTestCases(scalaOutputDir, cOutputDir); + if ((sv & ServiceVariation.COMPARE_ENCODINGS) == ServiceVariation.COMPARE_ENCODINGS) + compareTestCases(service, sv, scalaOutputDir, cOutputDir); } else { @@ -148,7 +148,7 @@ public void Run_TestService(PUS_C_Service service, string folderSuffix, ServiceV } } - private void compareTestCases(string folderA, string folderB) + private void compareTestCases(PUS_C_Service service, ServiceVariation sv, string folderA, string folderB) { var binsA = Directory.GetFiles(folderA, "*.dat").Order().ToArray(); var binsB = Directory.GetFiles(folderB, "*.dat").Order().ToArray(); @@ -156,7 +156,10 @@ private void compareTestCases(string folderA, string folderB) Assert.IsTrue(binsA.Select(x => Path.GetFileName(x)) .SequenceEqual(binsB.Select(x => Path.GetFileName(x))), "output did not create the same files"); - for (int i = 0; i < binsA.Length; i++) + var testNumbers = getInteropTests(service, sv); + Assert.IsTrue(binsA.Length == testNumbers.end); + + foreach (var i in testNumbers.testRange.Select(x => x - 1)) { using (var f1 = File.OpenRead(binsA[i])) using (var f2 = File.OpenRead(binsB[i])) @@ -167,23 +170,101 @@ private void compareTestCases(string folderA, string folderB) Assert.IsTrue(r1.BaseStream.Length == r2.BaseStream.Length, "filelength is different"); var isSame = true; - while(r1.BaseStream.Position < r1.BaseStream.Length && isSame) + while (r1.BaseStream.Position < r1.BaseStream.Length && isSame) { isSame &= (r1.ReadByte() == r2.ReadByte()); } Assert.IsTrue(isSame, $"file {binsA[i]} contents are not equal to {binsB[i]}"); } - } + } } } + private struct TestRange + { + public TestRange(int s, int e) + { + start = s; + end = e; + testRange = Enumerable.Range(s, e); + } + + public TestRange(int s, int e, IEnumerable ex) + { + start = s; + end = e; + testRange = Enumerable.Range(s, e).Except(ex); + } + + public readonly int start; + public readonly int end; + public readonly IEnumerable testRange; + } + + /** + * Get Range of interop tests between Scala and C. + * + * Exclude tests that do not work because the JVM does not + * support unsigned values. + * + */ + private TestRange getInteropTests(PUS_C_Service service, ServiceVariation sv) + { + if ((sv & ServiceVariation.UPER) != 0) + return service switch + { + PUS_C_Service.S1 => new TestRange(1, 67), + PUS_C_Service.S2 => new TestRange(1, 201, new[] { 80 }), + PUS_C_Service.S3 => new TestRange(1, 325, new[] { 80 }), + PUS_C_Service.S4 => new TestRange(1, 146, new[] { 80 }), + PUS_C_Service.S5 => new TestRange(1, 168, new[] { 80 }), + PUS_C_Service.S6 => new TestRange(1, 236, new[] { 80 }), + PUS_C_Service.S8 => new TestRange(1, 133, new[] { 80 }), + PUS_C_Service.S9 => new TestRange(1, 124, new[] { 80 }), + PUS_C_Service.S11 => new TestRange(1, 226, new[] { 80 }), + PUS_C_Service.S12 => new TestRange(1, 307, new[] { 80 }), + PUS_C_Service.S13 => new TestRange(1, 307, new[] { 80 }), + PUS_C_Service.S14 => new TestRange(1, 212, new[] { 80 }), + PUS_C_Service.S15 => new TestRange(1, 308, new[] { 80 }), + PUS_C_Service.S17 => new TestRange(1, 8, new[] { 80 }), + PUS_C_Service.S18 => new TestRange(1, 180, new[] { 80 }), + PUS_C_Service.S19 => new TestRange(1, 147, new[] { 80 }), + PUS_C_Service.ADDITIONAL_TEST_CASES => new TestRange(1, 200, new[] { 80 }), + _ => throw new InvalidOperationException("unknown service") + }; + else if ((sv & ServiceVariation.ACN) != 0) + return service switch + { + PUS_C_Service.S1 => new TestRange(1, 59), + PUS_C_Service.S2 => new TestRange(1, 179, new[] { 80 }), + PUS_C_Service.S3 => new TestRange(1, 308, new[] { 80 }), + PUS_C_Service.S4 => new TestRange(1, 134, new[] { 80 }), + PUS_C_Service.S5 => new TestRange(1, 159, new[] { 80 }), + PUS_C_Service.S6 => new TestRange(1, 226, new[] { 80 }), + PUS_C_Service.S8 => new TestRange(1, 120, new[] { 80 }), + PUS_C_Service.S9 => new TestRange(1, 118, new[] { 80 }), + PUS_C_Service.S11 => new TestRange(1, 213, new[] { 80 }), + //PUS_C_Service.S12 => Enumerable.Range(1, 129).Except(new[] { 80 }), + PUS_C_Service.S13 => new TestRange(1, 129, new [] { 80 }), + PUS_C_Service.S14 => new TestRange(1, 202, new[] { 80 }), + PUS_C_Service.S15 => new TestRange(1, 291, new[] { 80 }), + PUS_C_Service.S17 => new TestRange(1, 8, new[] { 80 }), + PUS_C_Service.S18 => new TestRange(1, 172, new[] { 80 }), + PUS_C_Service.S19 => new TestRange(1, 141, new[] { 80 }), + PUS_C_Service.ADDITIONAL_TEST_CASES => new TestRange(1, 200, new[] { 80 }), + _ => throw new InvalidOperationException("unknown service") + }; + else + throw new InvalidOperationException("no coding for testing"); + } + private string getCleanWorkingFolderPath(string folderSuffix, ServiceVariation sv) { string outDir = GetOutputFolder(folderSuffix, sv); //if (Directory.Exists(outDir)) // Directory.Delete(outDir, true); - + return outDir; } @@ -271,7 +352,7 @@ private void RunCTests(string outDir, bool printOutput) FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "bash", Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {cConfig}\\{cProject}.exe" : $"-c ./mainprogram", - WorkingDirectory = outDir, + WorkingDirectory = outDir, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardInput = false, @@ -284,7 +365,7 @@ private void RunCTests(string outDir, bool printOutput) var worked = stdout.Contains("All test cases (") && stdout.Contains(") run successfully."); if (!worked) Console.WriteLine(stdout); - + Assert.IsTrue(worked, "C test cases failed"); } } @@ -351,10 +432,10 @@ private void RunMSBuild(string outDir) }) { proc.Start(); - + var o = proc.StandardOutput.ReadToEnd(); var worked = proc.ExitCode == 0; - if(!worked) + if (!worked) Console.WriteLine(o); Assert.IsTrue(worked, "error while compiling C project"); @@ -370,7 +451,7 @@ private void StartSBTWithArg(string outDir, string arg, string check, bool print StartInfo = new ProcessStartInfo { FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "bash", - Arguments= RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {arg}" : $"-c \"{arg}\"", + Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/C {arg}" : $"-c \"{arg}\"", WorkingDirectory = outDir, UseShellExecute = false, RedirectStandardOutput = true, @@ -387,7 +468,7 @@ private void StartSBTWithArg(string outDir, string arg, string check, bool print Console.WriteLine("WORKED? " + worked); // print sbt output - if(printOutput) + if (printOutput) Console.WriteLine(outp); Assert.IsTrue(worked); From 3938f37fc491dea9816eda4945e68e52489ae17a Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Mon, 15 Jan 2024 19:23:41 +0100 Subject: [PATCH 134/174] JVM can not handle extreme numbers, numbers are valid, range is invalid --- .../common/BasicTypes.asn1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/common/BasicTypes.asn1 b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/common/BasicTypes.asn1 index 5733405bb..ef2c8cfb3 100644 --- a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/common/BasicTypes.asn1 +++ b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/common/BasicTypes.asn1 @@ -48,7 +48,7 @@ PUSC-UINT16 ::= INTEGER (0 .. 65535) --PFC-12 PUSC-UINT24 ::= INTEGER (0 .. 16777215) --PFC-13 PUSC-UINT32 ::= INTEGER (0 .. 4294967295) --PFC-14 PUSC-UINT48 ::= INTEGER (0 .. 281474976710655) --PFC-15 -PUSC-UINT64 ::= INTEGER (0 .. 18446744073709551615) --PFC-16 +PUSC-UINT64 ::= INTEGER (0 .. 9223372036854775807) --PFC-16 PUSC-UINT1 ::= INTEGER (0 .. 1) --PFC-17 PUSC-UINT2 ::= INTEGER (0 .. 3) --PFC-18 PUSC-UINT3 ::= INTEGER (0 .. 7) --PFC-19 @@ -70,7 +70,7 @@ PUSC-INT16 ::= INTEGER (-32768 .. 32767) --PFC-12 PUSC-INT24 ::= INTEGER (-8388608 .. 8388607) --PFC-13 PUSC-INT32 ::= INTEGER (-2147483648 .. 2147483647) --PFC-14 PUSC-INT48 ::= INTEGER (-140737488355328 .. 140737488355327) --PFC-15 -PUSC-INT64 ::= INTEGER (-9223372036854775808 .. 9223372036854775807) --PFC16 +PUSC-INT64 ::= INTEGER (-4611686018427387903 .. 4611686018427387903) --PFC16 -- PTC-5 PUSC-FLOAT32 ::= REAL From 54e1c292fafc364102dabb1573aaae6daff8b630 Mon Sep 17 00:00:00 2001 From: Mario Bucev Date: Wed, 3 Jan 2024 13:31:34 +0100 Subject: [PATCH 135/174] Make bitStream a field --- .../scala/asn1scala/asn1jvm_Bitstream.scala | 13 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 112 +++++++++--------- 2 files changed, 68 insertions(+), 57 deletions(-) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala index 4b9b2cc74..97e6797ca 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Bitstream.scala @@ -81,7 +81,7 @@ case class BitStream( require(BitStream.invariant(currentBit, currentByte, buf.length)) @pure - private def remainingBits: Long = { + def remainingBits: Long = { (buf.length.toLong * NO_OF_BITS_IN_BYTE) - (currentByte.toLong * NO_OF_BITS_IN_BYTE + currentBit) } @@ -151,6 +151,9 @@ case class BitStream( ret } + @ghost @pure + def getBuf: Array[Byte] = buf + // @ghost // @pure // private def readBitPure(): (BitStream, Option[Boolean]) = { @@ -606,6 +609,14 @@ case class BitStream( ret.cutToByte }.ensuring(_ => buf == old(this).buf && remainingBits == old(this).remainingBits - NO_OF_BITS_IN_BYTE) + @ghost @pure + def readBytePure(): (BitStream, UByte) = { + require(validate_offset_bits(8)) + val cpy = snapshot(this) + val res = cpy.readByte() + (cpy, res) + } + def readByteArray(nBytes: Int): Array[UByte] = { require(nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) require(nBytes >= 0 && nBytes <= remainingBits / NO_OF_BITS_IN_BYTE) diff --git a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala index 3fe7f4dd3..d5712941a 100644 --- a/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala +++ b/asn1scala/src/main/scala/asn1scala/asn1jvm_Codec.scala @@ -62,9 +62,9 @@ def BitString_equal(arr1: Array[UByte], arr2: Array[UByte]): Boolean = { * * @param count represents the number of bytes in the internal buffer */ +@mutable trait Codec { - - def bitStream: BitStream + val bitStream: BitStream /** ******************************************************************************************** */ /** ******************************************************************************************** */ @@ -77,7 +77,7 @@ trait Codec { /** ******************************************************************************************** */ - def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { + final def encodeNonNegativeInteger32Neg(v: Int, negate: Boolean): Unit = { var cc: UInt = 0 var curMask: UInt = 0 var pbits: UInt = 0 @@ -121,7 +121,7 @@ trait Codec { appendByte(b.cutToByte) } - def decodeNonNegativeInteger32Neg(nBitsVal : Int): Int = { + final def decodeNonNegativeInteger32Neg(nBitsVal : Int): Int = { // TODO precondition var v: UInt = 0 @@ -144,7 +144,7 @@ trait Codec { v } - def encodeNonNegativeInteger(v: ULong): Unit = { + final def encodeNonNegativeInteger(v: ULong): Unit = { if v >>> 32 == 0 then encodeNonNegativeInteger32Neg(v.toInt, false) else @@ -157,7 +157,7 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } - def decodeNonNegativeInteger(nBits: Int): Long = { + final def decodeNonNegativeInteger(nBits: Int): Long = { // TODO precondition if nBits <= 32 then @@ -172,7 +172,7 @@ trait Codec { v } - def encodeNonNegativeIntegerNeg(v: Long): Unit = { + final def encodeNonNegativeIntegerNeg(v: Long): Unit = { // TODO precondition if v >>> 32 == 0 then @@ -191,8 +191,8 @@ trait Codec { encodeNonNegativeInteger32Neg(lo, false) } - @extern - def rangeCheck(min: Long, max: Long): Boolean = { + @extern @pure + final def rangeCheck(min: Long, max: Long): Boolean = { val bigMin = scala.math.BigInt(min) val bigMax = scala.math.BigInt(max) @@ -209,7 +209,7 @@ trait Codec { * range size is limited to Long.MaxValue - a higher range will fail * */ - def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { + final def encodeConstrainedWholeNumber(v: Long, min: Long, max: Long): Unit = { require(min <= max) require(min <= v && v <= max) require(rangeCheck(min, max)) @@ -230,7 +230,7 @@ trait Codec { appendBitsNBitFirstToLSB(encVal, nRangeBits) } - def decodeConstrainedWholeNumber(min: Long, max: Long): Long = { + final def decodeConstrainedWholeNumber(min: Long, max: Long): Long = { require(min <= max) require(rangeCheck(min, max)) @@ -248,27 +248,27 @@ trait Codec { min + decVal } - def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Byte = { + final def decodeConstrainedWholeNumberByte(min: Byte, max: Byte): Byte = { require(min <= max) decodeConstrainedWholeNumber(min, max).cutToByte // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstrainedWholeNumberShort(min: Short, max: Short): Short = { + final def decodeConstrainedWholeNumberShort(min: Short, max: Short): Short = { require(min <= max) decodeConstrainedWholeNumber(min, max).cutToShort // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstrainedWholeNumberInt(min: Int, max: Int): Int = { + final def decodeConstrainedWholeNumberInt(min: Int, max: Int): Int = { require(min <= max) decodeConstrainedWholeNumber(min, max).cutToInt // TODO maybe add PostCondition: is val in given (signed/unsigned??) range? } - def decodeConstraintPosWholeNumber(min: Long, max: Long): Long = { + final def decodeConstraintPosWholeNumber(min: Long, max: Long): Long = { require(max >= 0 && max <= Long.MaxValue) require(min >= 0 && min <= max) @@ -286,7 +286,7 @@ trait Codec { min + decVal } - def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { + final def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { require(min <= v) val nBytes: Int = GetLengthForEncodingUnsigned(v - min) @@ -300,7 +300,7 @@ trait Codec { encodeNonNegativeInteger(v - min) } - def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { + final def encodeSemiConstraintPosWholeNumber(v: ULong, min: ULong): Unit = { require(min <= v) val nBytes: Int = GetLengthForEncodingUnsigned(v - min) @@ -314,7 +314,7 @@ trait Codec { encodeNonNegativeInteger(v - min) } - def decodeSemiConstraintWholeNumber(min: Long): Long = { + final def decodeSemiConstraintWholeNumber(min: Long): Long = { // TODO add precondition // get length in bytes @@ -334,7 +334,7 @@ trait Codec { min + v } - def decodeSemiConstraintPosWholeNumber(min: ULong): ULong = { + final def decodeSemiConstraintPosWholeNumber(min: ULong): ULong = { require(min >= 0) // TODO precondition @@ -363,7 +363,7 @@ trait Codec { * * @param v The value that is always encoded in the smallest possible number of octets. */ - def encodeUnconstrainedWholeNumber(v: Long): Unit = { + final def encodeUnconstrainedWholeNumber(v: Long): Unit = { require(bitStream.validate_offset_bytes(1 + GetLengthForEncodingSigned(v))) // call func that fulfills 8.3.2 @@ -391,7 +391,7 @@ trait Codec { * * @return decoded number */ - def decodeUnconstrainedWholeNumber(): Long = { + final def decodeUnconstrainedWholeNumber(): Long = { require(bitStream.validate_offset_bytes(2)) // get length @@ -417,7 +417,7 @@ trait Codec { * @param vVal real input in IEEE754 double format */ @extern - def encodeReal(vVal: Double): Unit = { + final def encodeReal(vVal: Double): Unit = { encodeRealBitString(java.lang.Double.doubleToRawLongBits(vVal)) } @@ -536,7 +536,7 @@ trait Codec { * @return decoded real value in IE754 double format */ @extern - def decodeReal(): Double = java.lang.Double.longBitsToDouble(decodeRealBitString()) + final def decodeReal(): Double = java.lang.Double.longBitsToDouble(decodeRealBitString()) /** * Real decoding implementation according to the PER standard @@ -638,18 +638,18 @@ trait Codec { v } - def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Unit = { + final def encodeOctetString_no_length(arr: Array[UByte], nCount: Int): Unit = { appendByteArray(arr, nCount) } - def decodeOctetString_no_length(nCount: Int): Array[UByte] = { + final def decodeOctetString_no_length(nCount: Int): Array[UByte] = { val a = readByteArray(nCount) val arr: Array[UByte] = Array.fill(nCount + 1)(0) // TODO: why is +1 needed? arrayCopyOffsetLen(a, arr, 0, 0, a.length) arr } - def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { // TODO return value legacy C? remove? + final def encodeOctetString_fragmentation(arr: Array[UByte], nCount: Int): Boolean = { // TODO return value legacy C? remove? var nRemainingItemsVar1: Int = nCount var nCurBlockSize1: Int = 0 var nCurOffset1: Int = 0 @@ -696,7 +696,7 @@ trait Codec { ret } - def decodeOctetString_fragmentation(asn1SizeMax: Long): Array[UByte] = { + final def decodeOctetString_fragmentation(asn1SizeMax: Long): Array[UByte] = { require(asn1SizeMax >= 0 && asn1SizeMax < Int.MaxValue) val arr: Array[UByte] = Array.fill(asn1SizeMax.toInt)(0) @@ -774,7 +774,7 @@ trait Codec { newArr } - def encodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { + final def encodeOctetString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Boolean = { // TODO require & return type - seems old C style var ret: Boolean = nCount.toLong >= asn1SizeMin && nCount.toLong <= asn1SizeMax @@ -791,7 +791,7 @@ trait Codec { ret } - def decodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { + final def decodeOctetString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { if asn1SizeMax >= 0x1_00_00 then // 65'536, bigger than 2 unsigned bytes return decodeOctetString_fragmentation(asn1SizeMax) @@ -807,7 +807,7 @@ trait Codec { decodeOctetString_no_length(nCount) } - def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Unit = { + final def encodeBitString(arr: Array[UByte], nCount: Int, asn1SizeMin: Long, asn1SizeMax: Long): Unit = { if asn1SizeMax < 65536 then if asn1SizeMin != asn1SizeMax then encodeConstrainedWholeNumber(nCount.toLong, asn1SizeMin, asn1SizeMax) @@ -851,7 +851,7 @@ trait Codec { appendBitsMSBFirst(t, nRemainingItemsVar1.toInt) } - def decodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { + final def decodeBitString(asn1SizeMin: Long, asn1SizeMax: Long): Array[UByte] = { require(asn1SizeMax <= Int.MaxValue) // TODO enhance precondition @@ -910,100 +910,100 @@ trait Codec { // ***** Public wrapper for bitstream functions - def appendBitOne(): Unit = { + final def appendBitOne(): Unit = { require(bitStream.validate_offset_bit()) bitStream.appendBitOne() } - def appendBitZero(): Unit = { + final def appendBitZero(): Unit = { require(bitStream.validate_offset_bit()) bitStream.appendBitZero() } - def appendBit(v: Boolean): Unit = { + final def appendBit(v: Boolean): Unit = { require(bitStream.validate_offset_bit()) bitStream.appendBit(v) } - def peekBit(): Boolean = { + final def peekBit(): Boolean = { require(bitStream.validate_offset_bit()) bitStream.peekBit() } - def readBit(): Boolean = { + final def readBit(): Boolean = { require(bitStream.validate_offset_bit()) bitStream.readBit() } - def appendNBitZero(nBits: Long): Unit = { + final def appendNBitZero(nBits: Long): Unit = { require(bitStream.validate_offset_bits(nBits)) bitStream.appendNBitZero(nBits) } - def appendNBitOne(nBits: Long): Unit = { + final def appendNBitOne(nBits: Long): Unit = { require(bitStream.validate_offset_bits(nBits)) bitStream.appendNBitOne(nBits) } - def appendBitsLSBFirst(v: Long, nBits: Int): Unit = { // TODO remove if never used + final def appendBitsLSBFirst(v: Long, nBits: Int): Unit = { // TODO remove if never used require(bitStream.validate_offset_bits(nBits)) bitStream.appendBitsLSBFirst(v, nBits) } - def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Unit = { + final def appendBitsMSBFirst(srcBuffer: Array[UByte], nBits: Long): Unit = { require(bitStream.validate_offset_bits(nBits)) bitStream.appendBitsMSBFirst(srcBuffer, nBits) } - def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Unit = { + final def appendBitsNBitFirstToLSB(v: Long, nBits: Int): Unit = { require(bitStream.validate_offset_bits(nBits)) bitStream.appendBitsNBitFirstToLSB(v, nBits) } - def readBitsNBitFirstToLSB(nBits: Int): Long = { + final def readBitsNBitFirstToLSB(nBits: Int): Long = { require(bitStream.validate_offset_bits(nBits)) bitStream.readBitsNBitFirstToLSB(nBits) } - def readBits(nBits: Long): Array[UByte] = { + final def readBits(nBits: Long): Array[UByte] = { require(nBits >= 0 && bitStream.validate_offset_bits(nBits)) bitStream.readBits(nBits) } - def appendByte(value: Byte): Unit = { + final def appendByte(value: Byte): Unit = { require(bitStream.validate_offset_byte()) bitStream.appendByte(value) } - def readByte(): Byte = { + final def readByte(): Byte = { require(bitStream.validate_offset_byte()) bitStream.readByte() } - def appendByteArray(arr: Array[Byte], noOfBytes: Int): Unit = { + final def appendByteArray(arr: Array[Byte], noOfBytes: Int): Unit = { require(bitStream.validate_offset_bytes(noOfBytes)) bitStream.appendByteArray(arr, noOfBytes) } - def readByteArray(nBytes: Int): Array[Byte] = { + final def readByteArray(nBytes: Int): Array[Byte] = { require(nBytes >= 0 && nBytes <= Integer.MAX_VALUE / NO_OF_BITS_IN_BYTE) require(bitStream.validate_offset_bytes(nBytes)) bitStream.readByteArray(nBytes) } - def appendPartialByte(vVal: Byte, nBits: Byte): Unit = { + final def appendPartialByte(vVal: Byte, nBits: Byte): Unit = { require(bitStream.validate_offset_bits(nBits)) bitStream.appendPartialByte(vVal, nBits) } - def readPartialByte(nBits: Int): Byte = { + final def readPartialByte(nBits: Int): Byte = { require(nBits >= 0 && nBits <= NO_OF_BITS_IN_BYTE) require(bitStream.validate_offset_bits(nBits)) bitStream.readPartialByte(nBits) } - def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { + final def checkBitPatternPresent(bit_terminated_pattern: Array[UByte], nBits: Long): Boolean = { require(bitStream.validate_offset_bits(nBits)) bitStream.checkBitPatternPresent(bit_terminated_pattern, nBits) } @@ -1017,31 +1017,31 @@ trait Codec { // case false => NoneMut() // } - def alignToByte(): Unit = { + final def alignToByte(): Unit = { require(bitStream.validate_offset_bits( NO_OF_BITS_IN_BYTE - (bitStream.bitIndex() % NO_OF_BITS_IN_BYTE))) bitStream.alignToByte() } - def alignToShort(): Unit = { + final def alignToShort(): Unit = { // TODO: precondition bitStream.alignToShort() // alignToByte() // currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_SHORT - 1)) / NO_OF_BYTES_IN_JVM_SHORT) * NO_OF_BYTES_IN_JVM_SHORT } - def alignToInt(): Unit = { + final def alignToInt(): Unit = { // TODO: precondition bitStream.alignToInt() // alignToByte() // currentByte = ((currentByte + (NO_OF_BYTES_IN_JVM_INT - 1)) / NO_OF_BYTES_IN_JVM_INT) * NO_OF_BYTES_IN_JVM_INT } - def resetBitIndex(): Unit = { + final def resetBitIndex(): Unit = { bitStream.resetBitIndex() } - def getBufferLength: Int = { + final def getBufferLength: Int = { bitStream.getBufferLength } @@ -1051,7 +1051,7 @@ trait Codec { * if the currentBit is not 0, currentByte is added by 1 * */ - def getLength: Int = { + final def getLength: Int = { bitStream.getLength } } From b875e1dc53941fabfced3363fbc3b743272073b0 Mon Sep 17 00:00:00 2001 From: Filip Schramka Date: Wed, 17 Jan 2024 20:48:06 +0100 Subject: [PATCH 136/174] use wrapping for extreme cases --- PUSCScalaTest/Testframework.cs | 5 +---- .../main/scala/asn1scala/asn1jvm_Codec.scala | 18 ++++-------------- 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/PUSCScalaTest/Testframework.cs b/PUSCScalaTest/Testframework.cs index 16bf70699..36c3f0cdb 100644 --- a/PUSCScalaTest/Testframework.cs +++ b/PUSCScalaTest/Testframework.cs @@ -156,10 +156,7 @@ private void compareTestCases(PUS_C_Service service, ServiceVariation sv, string Assert.IsTrue(binsA.Select(x => Path.GetFileName(x)) .SequenceEqual(binsB.Select(x => Path.GetFileName(x))), "output did not create the same files"); - var testNumbers = getInteropTests(service, sv); - Assert.IsTrue(binsA.Length == testNumbers.end); - - foreach (var i in testNumbers.testRange.Select(x => x - 1)) + for(var i = 0; i= nEncValBits) @@ -232,9 +223,8 @@ trait Codec { def decodeConstrainedWholeNumber(min: Long, max: Long): Long = { require(min <= max) - require(rangeCheck(min, max)) - val range: Long = max - min + val range: Long = stainless.math.wrapping(max - min) // only one possible number if range == 0 then @@ -286,7 +276,7 @@ trait Codec { min + decVal } - def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { + def encodeSemiConstraintWholeNumber(v: Long, min: Long): Unit = { require(min <= v) val nBytes: Int = GetLengthForEncodingUnsigned(v - min) From 5bfdd795797bf8f5d0731a0f45594abbcca56e9b Mon Sep 17 00:00:00 2001 From: Mario Bucev Date: Thu, 7 Dec 2023 16:07:42 +0100 Subject: [PATCH 137/174] Changes to Scala backend for more suitable verification --- ADA_RTL2/src/adaasn1rtl-encoding-acn.adb | 16 +- ADA_RTL2/src/adaasn1rtl-encoding-acn.ads | 16 +- Antlr/acn.g | 174 +- Antlr/asn1.g | 256 +-- BackendAst/BAst.fs | 80 +- BackendAst/BAstConstruction.fs | 242 +- BackendAst/BackendAst.fs | 70 +- BackendAst/BackendAst.fsproj | 39 +- BackendAst/BastAddAcnInsertFields.fs | 22 +- BackendAst/CAst.fs | 155 +- BackendAst/CAstAcnEncodingClasses.fs | 186 +- BackendAst/CAstConstruction.fs | 72 +- BackendAst/Constraints.fs | 258 +-- BackendAst/ConstraintsMapping.fs | 222 +- BackendAst/CustomStgExport.fs | 112 +- BackendAst/DAstACN.fs | 2045 ++++++++--------- BackendAst/DAstAsn1.fs | 50 +- BackendAst/DAstConstruction.fs | 270 ++- BackendAst/DAstEqual.fs | 236 +- BackendAst/DAstEqualExp.fs | 2 +- BackendAst/DAstExportToXml.fs | 108 +- BackendAst/DAstInitialize.fs | 951 ++++---- BackendAst/DAstProgramUnit.fs | 138 +- BackendAst/DAstTypeDefinition.fs | 291 ++- BackendAst/DAstTypeDefinition2.fs | 32 +- BackendAst/DAstUPer.fs | 719 +++--- BackendAst/DAstUtilFunctions.fs | 316 ++- BackendAst/DAstValidate.fs | 408 ++-- BackendAst/DAstVariables.fs | 253 +- BackendAst/DAstXer.fs | 202 +- BackendAst/DastFold.fs | 97 +- BackendAst/DastTestCaseCreation.fs | 156 +- BackendAst/DastValidate2.fs | 593 +++-- BackendAst/EncodeDecodeTestCase.fs | 178 +- BackendAst/GenerateAcnIcd.fs | 300 +-- BackendAst/GenerateFiles.fs | 124 +- BackendAst/GenerateUperIcd.fs | 144 +- BackendAst/GrammarGenerator.fs | 105 +- BackendAst/PrintAcn.fs | 40 +- BackendAst/PrintAsn1.fs | 110 +- BackendAst/createDefinitions.fs | 70 +- BackendAst/print_debug.fs | 94 +- BackendAst/validate.fs | 60 +- CommonTypes/AbstractMacros.fs | 159 +- CommonTypes/AcnGenericTypes.fs | 151 +- CommonTypes/CommonTypes.fs | 354 +-- CommonTypes/FsUtils.fs | 262 +-- CommonTypes/SimpleSets.fs | 138 +- CommonTypes/SizeableSet.fs | 34 +- .../a_out/adaasn1rtl-encoding-acn.adb | 378 +-- .../a_out/adaasn1rtl-encoding-acn.ads | 392 ++-- FrontEndAst/AcnCreateFromAntlr.fs | 817 ++++--- FrontEndAst/AcnEncodingClasses.fs | 164 +- FrontEndAst/AcnGenericCreateFromAntlr.fs | 299 ++- FrontEndAst/AcnType2.fs | 18 +- FrontEndAst/AcnTypes.fs | 46 +- FrontEndAst/Asn1AcnAst.fs | 202 +- FrontEndAst/Asn1AcnAstUtilFunctions.fs | 84 +- FrontEndAst/Asn1Ast.fs | 165 +- FrontEndAst/Asn1Fold.fs | 329 ++- FrontEndAst/Asn1Schema.xsd | 140 +- FrontEndAst/CheckAsn1.fs | 286 +-- FrontEndAst/CheckLongReferences.fs | 202 +- FrontEndAst/CloneTree.fs | 24 +- FrontEndAst/ConstraintsMapping.fs | 360 +-- FrontEndAst/CreateAsn1AstFromAntlrTree.fs | 456 ++-- FrontEndAst/DAst.fs | 297 +-- FrontEndAst/EnsureUniqueEnumNames.fs | 96 +- FrontEndAst/ExportToXml.fs | 244 +- FrontEndAst/FE_TypeDefinition.fs | 250 +- FrontEndAst/FrontEndAst.fsproj | 8 +- FrontEndAst/GenericFold2.fs | 218 +- FrontEndAst/Language.fs | 86 +- FrontEndAst/LoadAcnInfo.fs | 194 +- FrontEndAst/LspAst.fs | 90 +- FrontEndAst/MapParamAstToNonParamAst.fs | 145 +- FrontEndAst/ParameterizedAsn1Ast.fs | 288 +-- ...edTypes.fs => RemoveParameterizedTypes.fs} | 125 +- FrontEndAst/ValuesMapping.fs | 52 +- .../README.md | 2 +- .../service-12/PUS-12-8.asn1 | 4 +- StgAda/LangGeneric_a.fs | 190 +- StgAda/acn_a.stg | 188 +- StgAda/equal_a.stg | 14 +- StgAda/init_a.stg | 52 +- StgAda/isvalid_a.stg | 34 +- StgAda/spec_a.stg | 36 +- StgAda/uper_a.stg | 146 +- StgAda/variables_a.stg | 14 +- StgAda/xer_a.stg | 24 +- StgC/LangGeneric_c.fs | 295 +-- StgC/acn_c.stg | 179 +- StgC/equal_c.stg | 18 +- StgC/header_c.stg | 46 +- StgC/init_c.stg | 38 +- StgC/isvalid_c.stg | 48 +- StgC/test_cases_c.stg | 6 +- StgC/uper_c.stg | 138 +- StgC/variables_c.stg | 10 +- StgC/xer_c.stg | 18 +- StgScala/LangGeneric_scala.fs | 275 +-- StgScala/acn_scala.stg | 727 +++--- StgScala/equal_scala.stg | 22 +- StgScala/header_scala.stg | 54 +- StgScala/init_scala.stg | 65 +- StgScala/isvalid_scala.stg | 53 +- StgScala/uper_scala.stg | 278 ++- StgScala/variables_scala.stg | 10 +- StgScala/xer_scala.stg | 12 +- StgVarious/generic.stg | 6 +- StgVarious/icdtemplate_acn.stg | 24 +- StgVarious/icdtemplate_uper.stg | 40 +- StgVarious/python.stg | 6 +- StgVarious/stg_ACN.stg | 16 +- StgVarious/stg_ASN.stg | 60 +- StgVarious/xml.stg | 26 +- Tests/cross-tests/README.md | 2 +- asn1crt/asn1crt_encoding_acn.c | 30 +- asn1crt/asn1crt_encoding_acn.h | 52 +- .../main/scala/asn1scala/asn1jvm_Codec.scala | 2 +- .../scala/asn1scala/asn1jvm_Codec_ACN.scala | 20 +- asn1scc/Program.fs | 190 +- contrib/icd_uper_latex.stg | 32 +- contrib/vdm.stg | 8 +- github-issues/issue113/uper.html | 48 +- github-issues/issue168/c_out1/acn.c | 72 +- github-issues/issue168/c_out1/asn1crt.h | 52 +- github-issues/issue168/c_out2/acn.c | 72 +- github-issues/issue168/c_out2/asn1crt.h | 52 +- lsp/Server/Server/LspHandlers.cs | 10 +- lsp/Server/Server/Program.cs | 22 +- mantis/0000442/stgfolder/generic.stg | 6 +- mantis/0000498/icd.asn1 | 4 +- mantis/0000565/uper.html | 28 +- mantis/0000810/xml.stg | 26 +- mantis/0000873/xml.stg | 26 +- mantis/0000911/backend_ast.xml | 160 +- .../acn/21-PresentWhenExpression/001.asn1 | 6 +- .../acn/21-PresentWhenExpression/001.asn1 | 6 +- 139 files changed, 10570 insertions(+), 11095 deletions(-) rename FrontEndAst/{RemoveParamterizedTypes.fs => RemoveParameterizedTypes.fs} (87%) diff --git a/ADA_RTL2/src/adaasn1rtl-encoding-acn.adb b/ADA_RTL2/src/adaasn1rtl-encoding-acn.adb index f78912cec..84b5f43db 100644 --- a/ADA_RTL2/src/adaasn1rtl-encoding-acn.adb +++ b/ADA_RTL2/src/adaasn1rtl-encoding-acn.adb @@ -1428,7 +1428,7 @@ is strVal (strVal'Last) := Standard.Ascii.NUL; end Acn_Dec_String_Ascii_FixSize; - procedure Acn_Enc_String_Ascii_Null_Teminated + procedure Acn_Enc_String_Ascii_Null_Terminated (bs : in out Bitstream; null_characters : OctetBuffer; strVal : String) is i : Integer := strVal'First; @@ -1449,9 +1449,9 @@ is bs.Current_Bit_Pos'Loop_Entry + (i - null_characters'First) * 8); BitStream_AppendByte (bs, null_characters (i), False); end loop; - end Acn_Enc_String_Ascii_Null_Teminated; + end Acn_Enc_String_Ascii_Null_Terminated; - procedure Acn_Dec_String_Ascii_Null_Teminated + procedure Acn_Dec_String_Ascii_Null_Terminated (bs : in out Bitstream; null_characters : OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) is @@ -1519,7 +1519,7 @@ is I := I + 1; end loop; - end Acn_Dec_String_Ascii_Null_Teminated; + end Acn_Dec_String_Ascii_Null_Terminated; procedure Acn_Enc_String_Ascii_Internal_Field_Determinant (bs : in out Bitstream; asn1Min : Asn1Int; @@ -1597,7 +1597,7 @@ is end Acn_Enc_String_Ascii_External_Field_Determinant; procedure Acn_Dec_String_Ascii_External_Field_Determinant - (bs : in out Bitstream; extSizeDeterminatFld : Asn1Int; + (bs : in out Bitstream; extSizeDeterminantFld : Asn1Int; strVal : in out String; Result : out ASN1_RESULT) is I : Integer := strVal'First; @@ -1607,7 +1607,7 @@ is ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); while Result.Success and then I <= strVal'Last - 1 - and then I <= Integer (extSizeDeterminatFld) + and then I <= Integer (extSizeDeterminantFld) loop pragma Loop_Invariant (I >= strVal'First and I <= strVal'Last and @@ -1649,7 +1649,7 @@ is procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out Bitstream; charSet : String; nCharSize : Integer; - extSizeDeterminatFld : Asn1Int; strVal : out String; + extSizeDeterminantFld : Asn1Int; strVal : out String; Result : out ASN1_RESULT) is I : Integer := strVal'First; @@ -1660,7 +1660,7 @@ is ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); strVal := (others => Standard.Ascii.NUL); while Result.Success and then I <= strVal'Last - 1 - and then I <= Integer (extSizeDeterminatFld) + and then I <= Integer (extSizeDeterminantFld) loop pragma Loop_Invariant (I >= strVal'First and I <= strVal'Last and diff --git a/ADA_RTL2/src/adaasn1rtl-encoding-acn.ads b/ADA_RTL2/src/adaasn1rtl-encoding-acn.ads index b6aedb908..71a7e63ee 100644 --- a/ADA_RTL2/src/adaasn1rtl-encoding-acn.ads +++ b/ADA_RTL2/src/adaasn1rtl-encoding-acn.ads @@ -900,7 +900,7 @@ is bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (strVal'Last - strVal'First) * 8; - procedure Acn_Enc_String_Ascii_Null_Teminated + procedure Acn_Enc_String_Ascii_Null_Terminated (bs : in out Bitstream; null_characters : OctetBuffer; strVal : String) with Depends => (bs => (bs, strVal, null_characters)), @@ -919,7 +919,7 @@ is bs'Old.Current_Bit_Pos + (strVal'Length - 1 + null_characters'Length) * 8; - procedure Acn_Dec_String_Ascii_Null_Teminated + procedure Acn_Dec_String_Ascii_Null_Terminated (bs : in out Bitstream; null_characters : OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) with Pre => null_characters'Length >= 1 and then null_characters'Length <= 10 @@ -996,10 +996,10 @@ is bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First) * 8); procedure Acn_Dec_String_Ascii_External_Field_Determinant - (bs : in out Bitstream; extSizeDeterminatFld : Asn1Int; + (bs : in out Bitstream; extSizeDeterminantFld : Asn1Int; strVal : in out String; Result : out ASN1_RESULT) with - Pre => extSizeDeterminatFld >= 0 - and then extSizeDeterminatFld <= Asn1Int (Integer'Last) + Pre => extSizeDeterminantFld >= 0 + and then extSizeDeterminantFld <= Asn1Int (Integer'Last) and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last / 8 - 8 and then bs.Current_Bit_Pos < @@ -1032,10 +1032,10 @@ is procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out Bitstream; charSet : String; nCharSize : Integer; - extSizeDeterminatFld : Asn1Int; strVal : out String; + extSizeDeterminantFld : Asn1Int; strVal : out String; Result : out ASN1_RESULT) with - Pre => extSizeDeterminatFld >= 0 - and then extSizeDeterminatFld <= Asn1Int (Integer'Last) + Pre => extSizeDeterminantFld >= 0 + and then extSizeDeterminantFld <= Asn1Int (Integer'Last) and then nCharSize >= 1 and then nCharSize <= 8 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then charSet'Last < Natural'Last diff --git a/Antlr/acn.g b/Antlr/acn.g index d0b33730c..4b36550b0 100644 --- a/Antlr/acn.g +++ b/Antlr/acn.g @@ -110,11 +110,11 @@ public override string GetErrorHeader(RecognitionException e) /* ************************************* PARSER ************************************************************* */ /* ********************************************************************************************************************* */ -moduleDefinitions +moduleDefinitions : moduleDefinition+ ->^(ASN1_FILE moduleDefinition+) - ; + ; -moduleDefinition : a=modulereference +moduleDefinition : a=modulereference d=DEFINITIONS ASSIG_OP BEGIN constant* @@ -124,35 +124,35 @@ moduleDefinition : a=modulereference ; constant - : CONSTANT^ UID ASSIG_OP! intExpression; + : CONSTANT^ UID ASSIG_OP! intExpression; typeEncoding - : typereference paramList? encodingSpec -> ^(TYPE_ENCODING typereference paramList? encodingSpec) ; - - + : typereference paramList? encodingSpec -> ^(TYPE_ENCODING typereference paramList? encodingSpec) ; + + paramList: '<' singleParam (',' singleParam)* '>' -> ^(PARAM_LIST singleParam+); - + singleParam - : asn1Type ':' asn1LID ->^(PARAM asn1Type asn1LID); - + : asn1Type ':' asn1LID ->^(PARAM asn1Type asn1LID); + asn1Type : asn1UID ('.' asn1UID) -> ^(REFERENCED_TYPE asn1UID asn1UID) | asn1UID -> ^(REFERENCED_TYPE asn1UID ) | INTEGER | BOOLEAN | NULL - ; - + ; + encodingSpec : a='[' propertyList? R_SBRACKET childrenSpec? ->^(ENCODING_SPEC[$a] propertyList? R_SBRACKET childrenSpec? ) - ; - - + ; + + propertyList : property (',' property)* ->^(ENCODING_PROPERTIES property+) - ; - + ; + property : encodingProp | sizeProp @@ -171,37 +171,37 @@ property | postEncodingFunctionProp | preDecodingFunctionProp | savePositionProp - ; + ; -endiannessProp - : ENDIANNES^ BIG - | ENDIANNES^ LITTLE +endiannessProp + : ENDIANNESS^ BIG + | ENDIANNESS^ LITTLE ; -encodingProp - : ENCODING^ POS_INT - | ENCODING^ TWOSCOMPLEMENT - | ENCODING^ BCD - | ENCODING^ ASCII - | ENCODING^ IEEE754_1985_32 - | ENCODING^ IEEE754_1985_64 +encodingProp + : ENCODING^ POS_INT + | ENCODING^ TWOSCOMPLEMENT + | ENCODING^ BCD + | ENCODING^ ASCII + | ENCODING^ IEEE754_1985_32 + | ENCODING^ IEEE754_1985_64 ; sizeProp - : - SIZE^ NULL_TERMINATED + : + SIZE^ NULL_TERMINATED | SIZE^ INT | SIZE^ UID //UID referes to a constant declared in the constant section | SIZE^ longFld ; -/* -adjustProp +/* +adjustProp : ADJUST^ INT | ADJUST^ UID //UID referes to a constant declared in the constant section ; -*/ +*/ longFld : asn1LID ('.' asn1LID)* -> ^(LONG_FIELD asn1LID+); @@ -209,17 +209,17 @@ mappingFunctionProp : MAPPING_FUNCTION^ ( (asn1LID|asn1UID) ('.' (asn1 postEncodingFunctionProp : POST_ENCODING_FUNCTION^ ( (asn1LID|asn1UID) ('.' (asn1LID|asn1UID))* ); preDecodingFunctionProp : POST_DECODING_VALIDATOR^ ( (asn1LID|asn1UID) ('.' (asn1LID|asn1UID))* ); -alignToNextProp +alignToNextProp : ALIGNTONEXT^ BYTE | ALIGNTONEXT^ WORD | ALIGNTONEXT^ DWORD ; -encodeValuesProp +encodeValuesProp : ENCODE_VALUES ; -trueValProp : TRUE_VALUE^ BitStringLiteral +trueValProp : TRUE_VALUE^ BitStringLiteral ; falseValProp : FALSE_VALUE^ BitStringLiteral @@ -230,7 +230,7 @@ patternProp : PATTERN^ (BitStringLiteral | OctectStringLiteral) savePositionProp : SAVE_POSITION; -presentWhenProp +presentWhenProp : PRESENT_WHEN^ presentWhenCond+ | PRESENT_WHEN conditionalOrExpression -> ^(PRESENT_WHEN_EXP conditionalOrExpression) ; @@ -242,30 +242,30 @@ terminationPatternProp presentWhenCond : longFld EQUAL^ (INT|UID) | longFld a=EQUAL StringLiteral -> ^(PRESENT_WHEN_STR_EQUAL[$a] longFld StringLiteral) - | longFld + | longFld ; determinantProp - : DETERMINANT^ longFld + : DETERMINANT^ longFld ; enumSetValue - : INT|UID + : INT|UID ; childrenSpec : '{' '}' ->^(CHILDREN_ENC_SPEC ) | '{' childSpec (',' childSpec)* '}' ->^(CHILDREN_ENC_SPEC childSpec+) - ; - -childSpec + ; + +childSpec : asn1LID? argumentList? encodingSpec ->^(CHILD asn1LID? encodingSpec argumentList?) | asn1LID asn1Type encodingSpec ->^(CHILD_NEW asn1LID asn1Type encodingSpec) - ; - + ; + argumentList : '<' longFld (',' longFld)*'>' ->^(ARGUMENTS longFld+); - + /* *************************************************************************************************************************** */ /* ****************************** ACN PRESENT WHEN EXPRESSIONS*************************************************************** */ @@ -284,22 +284,22 @@ equalityExpression EQUAL^ relationalExpression | NOTEQUAL^ relationalExpression )* ; - + relationalExpression : additiveExpression ( - LT^ additiveExpression - | LTE^ additiveExpression - | GT^ additiveExpression - | GTE^ additiveExpression + LT^ additiveExpression + | LTE^ additiveExpression + | GT^ additiveExpression + | GTE^ additiveExpression )? ; - + additiveExpression : multiplicativeExpression ( PLUS^ multiplicativeExpression - | MINUS^ multiplicativeExpression + | MINUS^ multiplicativeExpression )* ; @@ -312,25 +312,25 @@ multiplicativeExpression | MODULO^ unaryExpression )* ; - + unaryExpression : PLUS^ unaryExpression | MINUS^ unaryExpression | BANG^ unaryExpression | primaryExpression ; - - - + + + primaryExpression - : '('! conditionalOrExpression ')'! - | INT + : '('! conditionalOrExpression ')'! + | INT | REAL | UID //UID referes to a constant declared in the constant section | longFld ; - + /* *************************************************************************************************************************** */ @@ -341,7 +341,7 @@ primaryExpression intExpression : multiplicative_expression (PLUS^ multiplicative_expression | MINUS^ multiplicative_expression )* ; -multiplicative_expression : power_expression +multiplicative_expression : power_expression ( MULTIPLICATION^ power_expression | DIVISION^ power_expression @@ -351,44 +351,44 @@ multiplicative_expression : power_expression power_expression : unary_expression (POWER_SYMBOL^ power_expression)? // right associative via tail recursion ; - + unary_expression : atom - | PLUS! atom + | PLUS! atom | MINUS atom ->^(UNARY_MINUS atom) - ; - + ; + atom - : INT + : INT | UID //CONSTANT - | '('! intExpression ')'! + | '('! intExpression ')'! ; - -asn1LID + +asn1LID : LID - | a=ENDIANNES -> LID[$a] + | a=ENDIANNESS -> LID[$a] | a=BIG -> LID[$a] | a=LITTLE -> LID[$a] | a=ENCODING -> LID[$a] | a=POS_INT -> LID[$a] | a=TWOSCOMPLEMENT -> LID[$a] - | a=SIZE -> LID[$a] - | a=NULL_TERMINATED -> LID[$a] -// | a=ADJUST -> LID[$a] - | a=ALIGNTONEXT -> LID[$a] - | a=BYTE -> LID[$a] - | a=WORD -> LID[$a] - | a=DWORD -> LID[$a] - | a=ENCODE_VALUES -> LID[$a] + | a=SIZE -> LID[$a] + | a=NULL_TERMINATED -> LID[$a] +// | a=ADJUST -> LID[$a] + | a=ALIGNTONEXT -> LID[$a] + | a=BYTE -> LID[$a] + | a=WORD -> LID[$a] + | a=DWORD -> LID[$a] + | a=ENCODE_VALUES -> LID[$a] | a=TRUE_VALUE -> LID[$a] | a=FALSE_VALUE -> LID[$a] | a=PATTERN -> LID[$a] | a=PRESENT_WHEN -> LID[$a] | a=DETERMINANT -> LID[$a] ; - + modulereference : asn1UID; typereference : asn1UID; @@ -409,7 +409,7 @@ asn1UID /* ************************************** LEXER ************************************************************ */ /* ***************************************************************************************************************** */ /* ***************************************************************************************************************** */ -ENDIANNES : 'endianness'; +ENDIANNESS : 'endianness'; BIG : 'big'; LITTLE : 'little'; @@ -485,8 +485,8 @@ POWER_SYMBOL : '^^'; ASSIG_OP : '::='; DOUBLE_COLON : '::'; -L_BRACKET : '{'; -R_BRACKET : '}'; +L_BRACKET : '{'; +R_BRACKET : '}'; L_PAREN : '('; R_PAREN : ')'; COMMA : ','; @@ -509,16 +509,16 @@ OctectStringLiteral : ; HexByteOrNible : - '0x' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F')? + '0x' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F')? | '\'' ( options {greedy=false;} : .) '\'' - ; + ; StringLiteral : STR+ ; fragment STR : '"' ( options {greedy=false;} : .)* '"' ; - + UID : ('A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9'|'-')* ; @@ -530,7 +530,7 @@ REAL : INT DOT (DIGITS)? (Exponent)? ; INT : ( '0' | ('1'..'9') ('0'..'9')*); - + fragment DIGITS : ('0'..'9')+; @@ -542,7 +542,7 @@ Exponent : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; WS : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;} - ; + ; COMMENT : '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;} diff --git a/Antlr/asn1.g b/Antlr/asn1.g index 0e873156b..cb68f2e72 100644 --- a/Antlr/asn1.g +++ b/Antlr/asn1.g @@ -72,7 +72,7 @@ tokens { EXPORTS_ALL; IMPORTS_FROM_MODULE; ASN1_FILE; - OCTECT_STING; + OCTET_STRING; SIMPLIFIED_SIZE_CONSTRAINT; OBJECT_TYPE; NUMBER_LST_ITEM; @@ -121,7 +121,7 @@ public class SyntaxErrorException : Exception public SyntaxErrorException(string msg) : base(msg) { } } -public class AntlrError +public class AntlrError { public int line; public int charPosInline; @@ -208,9 +208,9 @@ public override string GetErrorHeader(RecognitionException e) /* ************************************* PARSER ************************************************************* */ /* ********************************************************************************************************************* */ -moduleDefinitions +moduleDefinitions : moduleDefinition+ ->^(ASN1_FILE moduleDefinition+) - ; + ; definitiveIdentifier @@ -220,8 +220,8 @@ definitiveIdentifier definitiveObjIdComponent : identifier ( L_PAREN INT R_PAREN )? | INT - ; - + ; + moduleDefinition : a=modulereference definitiveIdentifier? d=DEFINITIONS (EXPLICIT TAGS @@ -243,50 +243,50 @@ moduleDefinition : a=modulereference definitiveIdentifier? /* EXPLICIT TAGS (default)==> all tags in explicit mode (i.e. multiple tags per type are encoded in BER) IMPLICIT TAGS ==> all tags are implicit -AUTOMATIC TAGS ==> the components of all its structured types (SEQUENCE,SET or CHOICE) are automatically tagged by the compiler starting - from 0 by one-increment. By default, every component is tagged in the implicit mode except if it is a CHOICE type, an open type or a parameter +AUTOMATIC TAGS ==> the components of all its structured types (SEQUENCE,SET or CHOICE) are automatically tagged by the compiler starting + from 0 by one-increment. By default, every component is tagged in the implicit mode except if it is a CHOICE type, an open type or a parameter that is a type. EXTENSIBILITY ==> An ENUMERATED, SEQUENCE, SET or CHOICE type that does not include an extension marker is extensible if the module includes the EXTENSIBILITY IMPLIED clause in its header -*/ - - +*/ + + exports : a=EXPORTS ALL ';' -> EXPORTS_ALL[$a] - | EXPORTS ((typereference | valuereference) (COMMA (typereference | valuereference))*)? ';' + | EXPORTS ((typereference | valuereference) (COMMA (typereference | valuereference))*)? ';' -> ^(EXPORTS typereference* valuereference*)? -; +; imports : IMPORTS importFromModule* ';' -> importFromModule* ; - + importFromModule : (typereference | valuereference) (COMMA (typereference | valuereference))* FROM modulereference definitiveIdentifier? -> ^(IMPORTS_FROM_MODULE modulereference typereference* valuereference* ) - ; - - -valueAssignment + ; + + +valueAssignment : valuereference type a=ASSIG_OP value -> ^(VAL_ASSIG[$a] valuereference type value) - ; + ; -/* +/* valueSetAssignment : typereference type '::=' L_BRACKET setOfValues R_BRACKET -> ^(VAL_SET_ASSIG typereference type setOfValues) - ; -*/ -typeAssignment + ; +*/ +typeAssignment : /*SPECIAL_COMMENT**/ typereference paramList? a=ASSIG_OP type -> ^(TYPE_ASSIG[$a] typereference type paramList?/*SPECIAL_COMMENT* */) - ; + ; -paramList +paramList : '{' param (COMMA param)* '}' -> ^(PARAM_LIST param*) ; - + param : UID ->^(TYPE_PARAM UID) | type ':' LID ->^(VALUE_PARAM type LID) @@ -296,21 +296,21 @@ param /* ********************************************************************************************************************* */ typeTag - : a='[' (t=UNIVERSAL | t=APPLICATION | t=PRIVATE)? (INT|val=valuereference) ']' ( impOrExp=IMPLICIT | impOrExp=EXPLICIT)? + : a='[' (t=UNIVERSAL | t=APPLICATION | t=PRIVATE)? (INT|val=valuereference) ']' ( impOrExp=IMPLICIT | impOrExp=EXPLICIT)? -> ^(TYPE_TAG[$a] $t? INT? ^(VALUE_REFERENCE[(IToken)val.Start] $val)? $impOrExp?) ; - + /* * In a given context, two tags are considered to be diferent if they are of diferent classes or if their respective numbers are diferent. * If tagging class is missing (i.e. no UNIVERSAL, or APPLICATION, or PRIVATE) are of context-specific class --> The tags make sense only inside the scope of the Father (father may be SEQUENCE, SET etc) --> they do not polute the global space -* UNIVERSAL ==> used by people designing/extending ASN.1 +* UNIVERSAL ==> used by people designing/extending ASN.1 * APPLICATION ==> to tag types that would be referenced several times in a speci?cation * PRIVATE ==> use of PRIVATE class tags is not recommended since 1994 * EXPLICIT (Default)==> In BER, more than one tags are encoded. Eg in Afters ::= CHOICE { cheese [0] IA5String, dessert [1] IA5String } the two tags [0] and [UNIVERSAL 22] are encoded if the alternative cheese is chosen * IMPLICIT ==> Only one tag is encoded ; a tag marked IMPLICIT overwrites the tag that follows it (recursively) -*/ +*/ /* Note on constraints @@ -320,7 +320,7 @@ applies on the type appearing after the keywords SEQUENCE OF or SET OF FOR THIS REASON sequenceOfType AND setOfType ARE NOT FOLLOWED BY A constraint* If Type is a reference to a SEQUENCE OF or SET OF type, the Constraint applies to the SEQUENCE OF or SET OF type, and not to -the type that follows these keywords. +the type that follows these keywords. (2) If several Constraints appear one after the other after Type, the possible values for this type are those of the intersection of constraints . @@ -349,9 +349,9 @@ type : typeTag? ; - -selectionType : + +selectionType : identifier a=LESS_THAN type ->^(SELECTION_TYPE[$a] identifier type) ; @@ -373,23 +373,23 @@ bitStringType : a=BIT STRING (L_BRACKET (bitStringItem (COMMA bitStringItem )* )? R_BRACKET )? -> ^(BIT_STRING_TYPE[$a] bitStringItem*) ; -bitStringItem +bitStringItem : identifier a=L_PAREN (INT|definedValue) R_PAREN -> ^(NUMBER_LST_ITEM[$a] identifier INT? definedValue?) - ; - + ; + booleanType : BOOLEAN ; - -enumeratedType + +enumeratedType : a=ENUMERATED L_BRACKET en1=enumeratedTypeItems ( COMMA ext=EXT_MARK exceptionSpec? (COMMA en2=enumeratedTypeItems)? )? R_BRACKET -> ^(ENUMERATED_TYPE[$a] $en1 ($ext exceptionSpec? $en2?) ?) ; /* -enumeratedTypeItems2 +enumeratedTypeItems2 : enumItemNoValue (COMMA enumItemNoValue)* ->enumItemNoValue+ | enumItemWithValue (COMMA enumItemWithValue)* ->enumItemWithValue+ - ; + ; enumItemNoValue : identifier -> ^(NUMBER_LST_ITEM identifier ) @@ -400,12 +400,12 @@ enumItemWithValue ; */ -enumeratedTypeItems +enumeratedTypeItems : enumeratedLstItem (COMMA enumeratedLstItem)* ->enumeratedLstItem+ - ; + ; -enumeratedLstItem : +enumeratedLstItem : identifier ( L_PAREN (INT|val=valuereference) R_PAREN)? -> ^(NUMBER_LST_ITEM identifier INT? ^(VALUE_REFERENCE[(IToken)val.Start] $val)?) ; @@ -413,63 +413,63 @@ enumeratedLstItem : integerType : a=INTEGER ( L_BRACKET (integerTypeListItem (COMMA integerTypeListItem)*)? R_BRACKET)? -> ^(INTEGER_TYPE[$a] integerTypeListItem*) ; - -integerTypeListItem + +integerTypeListItem : identifier a=L_PAREN (INT|val=valuereference) R_PAREN -> ^(NUMBER_LST_ITEM[$a] identifier INT? ^(VALUE_REFERENCE[(IToken)val.Start] $val)?) - ; - -realType + ; + +realType : REAL ; - - + + choiceType : a=CHOICE L_BRACKET choiceItemsList choiceExtensionBody? R_BRACKET -> ^(CHOICE_TYPE[$a] choiceItemsList choiceExtensionBody?) ; - + choiceExtensionBody - : COMMA a=EXT_MARK exceptionSpec? choiceListExtension? (COMMA extMark2=EXT_MARK)? + : COMMA a=EXT_MARK exceptionSpec? choiceListExtension? (COMMA extMark2=EXT_MARK)? -> ^(CHOICE_EXT_BODY[$a] exceptionSpec? choiceListExtension? $extMark2?) - ; + ; choiceItemsList : choiceItem (COMMA choiceItem)* -> choiceItem+ ; - + choiceItem : identifier type -> ^(CHOICE_ITEM identifier type ) - ; + ; choiceListExtension : COMMA extensionAdditionAlternative (COMMA extensionAdditionAlternative)* -> extensionAdditionAlternative+ - ; - + ; + extensionAdditionAlternative : a='[[' versionNumber? choiceItemsList ']]' -> ^(CHOICE_EXT_ITEM[$a] versionNumber? choiceItemsList) | choiceItem - ; + ; sequenceType : a=SEQUENCE L_BRACKET sequenceOrSetBody? R_BRACKET -> ^(SEQUENCE_TYPE[$a] L_BRACKET R_BRACKET sequenceOrSetBody?) ; - + setType : a=SET L_BRACKET sequenceOrSetBody? R_BRACKET -> ^(SET_TYPE[$a] sequenceOrSetBody?) - ; - + ; + sequenceOrSetBody : componentTypeList ( COMMA seqOrSetExtBody)? -> ^(SEQUENCE_BODY componentTypeList seqOrSetExtBody?) | seqOrSetExtBody -> ^(SEQUENCE_BODY seqOrSetExtBody) ; - + seqOrSetExtBody : a=EXT_MARK exceptionSpec? (COMMA extensionAdditionList)? (COMMA extMark2=EXT_MARK (COMMA componentTypeList )? )? -> ^(SEQUENCE_EXT_BODY[$a] exceptionSpec? extensionAdditionList? $extMark2? componentTypeList?) - ; - + ; + extensionAdditionList : extensionAddition (COMMA extensionAddition)* -> extensionAddition+ - ; + ; extensionAddition : componentType @@ -479,27 +479,27 @@ extensionAdditionGroup : a='[[' versionNumber? componentTypeList ']]' -> ^(SEQUENCE_EXT_GROUP[$a] versionNumber? componentTypeList) ; -componentTypeList +componentTypeList : componentType (COMMA componentType )* -> componentType+ ; - + componentType : identifier type (optOrDef=OPTIONAL | optOrDef=DEFAULT value)? -> ^(SEQUENCE_ITEM identifier type $optOrDef? ^(DEFAULT_VALUE value)? ) | a=COMPONENTS OF referencedType -> ^(COMPONENTS_OF[$a] referencedType) - ; - + ; + sequenceOfType - : a=SEQUENCE (sizeShortConstraint | constraint)? UNITS? OF (identifier)? type + : a=SEQUENCE (sizeShortConstraint | constraint)? UNITS? OF (identifier)? type -> ^(SEQUENCE_OF_TYPE[$a] sizeShortConstraint? constraint? UNITS? identifier? type ) ; - + setOfType : a=SET (sizeShortConstraint | constraint)? UNITS? OF (identifier)? type -> ^(SET_OF_TYPE[$a] sizeShortConstraint? constraint? UNITS? identifier? type ) - ; + ; + - stringType : - a=OCTET STRING -> OCTECT_STING[$a] + a=OCTET STRING -> OCTET_STRING[$a] |NumericString |PrintableString |VisibleString @@ -514,41 +514,41 @@ stringType : |GeneralizedTime |UTCTime ; - + timeType : a=TIME L_PAREN SETTINGS StringLiteral R_PAREN -> ^(TIME_TYPE[$a] StringLiteral) ; referencedType : str1=UID ('.' str2=UID)? -> ^(REFERENCED_TYPE[$str1] $str1 $str2? ) | str1=UID ('.' str2=UID)? actualParameterList -> ^(PREFERENCED_TYPE[$str1] $str1 $str2? actualParameterList?) - ; + ; -actualParameterList +actualParameterList : '{' actualParameter (COMMA actualParameter)* '}' -> ^(ACTUAL_PARAM_LIST actualParameter+) ; - -actualParameter + +actualParameter : type -> ^(ACTUAL_TYPE_PARAM type) | value -> ^(ACTUAL_VALUE_PARAM value) - ; + ; /* ********************************************************************************************************************* */ /* *************************************** VALUES DEFINITION *********************************************************** */ /* ********************************************************************************************************************* */ choiceValue : identifier a=':' value ->^(CHOICE_VALUE[$a] identifier value) - ; + ; namedValue : a=identifier value ->^(NAMED_VALUE[(IToken)a.Start] identifier value) ; - + /* -To resolve another grammar Ambiguouity, we no more declare bitStringValue. The parser will only return valueList. Extra checking +To resolve another grammar Ambiguity, we no more declare bitStringValue. The parser will only return valueList. Extra checking must be done during semantic checking. bitStringValue : L_BRACKET identifier (COMMA identifier)* R_BRACKET ->^(BIT_STRING_VALUE identifier+) ; -*/ +*/ /* @@ -575,14 +575,14 @@ value : | a=L_BRACKET namedValue (COMMA namedValue)* R_BRACKET ->^(NAMED_VALUE_LIST[$a] namedValue+) | a=L_BRACKET value (COMMA value)* R_BRACKET ->^(VALUE_LIST[$a] value+) | a=L_BRACKET objectIdentifierComponent+ R_BRACKET ->^(OBJECT_ID_VALUE[$a] objectIdentifierComponent+ ) - ; - - + ; + + /* a CharacterStringValue is a string literal tuple : L_BRACKET INT COMMA INT R_BRACKET ; -*/ +*/ objectIdentifierComponent : identifier ( L_PAREN (INT | definedValue) R_PAREN )? ->^(OBJ_LST_ITEM1 identifier INT? definedValue?) //3 cases identifier or valuereference or identifier(number) @@ -599,34 +599,34 @@ definedValue /* ********************************************************************************************************************* */ /* *************************************** Constraints DEFINITION ****************************************************** */ /* ********************************************************************************************************************* */ -constraint - : L_PAREN! unionConstraint (COMMA! EXT_MARK^ (COMMA! unionConstraint)? exceptionSpec?)? R_PAREN! +constraint + : L_PAREN! unionConstraint (COMMA! EXT_MARK^ (COMMA! unionConstraint)? exceptionSpec?)? R_PAREN! ; -exceptionSpec - : '!' +exceptionSpec + : '!' ( INT -> ^(EXCEPTION_SPEC ^(EXCEPTION_SPEC_CONST_INT INT)) |val=valuereference -> ^(EXCEPTION_SPEC ^(EXCEPTION_SPEC_VAL_REF ^(VALUE_REFERENCE[(IToken)val.Start] $val))) |type ':' value -> ^(EXCEPTION_SPEC ^(EXCEPTION_SPEC_TYPE_VALUE type value)) ) - + ; unionConstraint - : intersectionConstraint (UnionMark^ intersectionConstraint)* + : intersectionConstraint (UnionMark^ intersectionConstraint)* | ALL EXCEPT constraintExpression -> ^(ALL_EXCEPT constraintExpression) - ; - + ; + // UNION_ELEMENT2 is synonymous to INTERSECTION_SET intersectionConstraint - : exceptConstraint (IntersectionMark^ exceptConstraint)* - ; - -exceptConstraint - : ex1=constraintExpression (EXCEPT^ ex2=constraintExpression)? - ; + : exceptConstraint (IntersectionMark^ exceptConstraint)* + ; + +exceptConstraint + : ex1=constraintExpression (EXCEPT^ ex2=constraintExpression)? + ; //The grammar is unambigues since (NULL) can be interpreted as both single value constraint and Type inclusion constraint @@ -641,10 +641,10 @@ constraintExpression | innerTypeExpression | patternExpression | L_PAREN unionConstraint R_PAREN -> unionConstraint - ; - + ; + valueRangeExpression - : minVal=lowerEndValue ((minIncl='<')? DOUBLE_DOT (maxIncl='<')? maxVal=upperEndValue)? + : minVal=lowerEndValue ((minIncl='<')? DOUBLE_DOT (maxIncl='<')? maxVal=upperEndValue)? -> ^(VALUE_RANGE_EXPR $minVal ^(MAX_VAL_PRESENT $maxVal)? ^(MIN_VAL_INCLUDED[$minIncl] $minIncl)? ^(MAX_VAL_INCLUDED[$maxIncl] $maxIncl) ? ) ; @@ -653,10 +653,10 @@ lowerEndValue | MIN ; -upperEndValue +upperEndValue : value | MAX - ; + ; subtypeExpression: bInlc=INCLUDES? referencedType -> ^(SUBTYPE_EXPR referencedType $bInlc?) @@ -664,33 +664,33 @@ subtypeExpression: bInlc=INCLUDES? referencedType -> ^(SUBTYPE_EXPR referencedT sizeExpression : a=SIZE constraint -> ^(SIZE_EXPR[$a] constraint) ; - + permittedAlphabetExpression : a=FROM constraint -> ^(PERMITTED_ALPHABET_EXPR[$a] constraint) ; -innerTypeExpression +innerTypeExpression : a=WITH COMPONENT constraint -> ^(WITH_COMPONENT_CONSTR[$a] constraint) | a=WITH COMPONENTS L_BRACKET ( EXT_MARK COMMA)? - namedConstraintExpression (COMMA namedConstraintExpression)* + namedConstraintExpression (COMMA namedConstraintExpression)* R_BRACKET -> ^(WITH_COMPONENTS_CONSTR[$a] EXT_MARK? namedConstraintExpression+) ; namedConstraintExpression - : identifier (constraint)? (eNum=PRESENT|eNum=ABSENT | eNum=OPTIONAL)? + : identifier (constraint)? (eNum=PRESENT|eNum=ABSENT | eNum=OPTIONAL)? -> ^(NAME_CONSTRAINT_EXPR identifier ^(INNER_CONSTRAINT constraint)? ^(EXT_MARK $eNum)?) - ; + ; patternExpression : a=PATTERN value -> ^(PATTERN_EXPR[$a] value) ; - + lID : LID; modulereference : UID; typereference : UID; -valuereference : LID; +valuereference : LID; identifier : LID; versionNumber : INT ':' -> INT; objectIdentifier : a=OBJECT IDENTIFIER ->OBJECT_TYPE[$a]; @@ -712,7 +712,7 @@ relativeOID : RELATIVE_OID; /* ***************************************************************************************************************** */ PLUS_INFINITY : 'PLUS-INFINITY'; -MINUS_INFINITY : 'MINUS-INFINITY'; +MINUS_INFINITY : 'MINUS-INFINITY'; GeneralizedTime : 'GeneralizedTime'; UTCTime : 'UTCTime'; MANTISSA : 'mantissa'; @@ -758,7 +758,7 @@ FALSE : 'FALSE'; ABSENT : 'ABSENT'; PRESENT : 'PRESENT'; WITH : 'WITH'; -COMPONENT : 'COMPONENT'; +COMPONENT : 'COMPONENT'; COMPONENTS : 'COMPONENTS'; DEFAULT : 'DEFAULT'; NULL :'NULL'; @@ -781,8 +781,8 @@ INCLUDES :'INCLUDES'; EXCEPT :'EXCEPT'; SET :'SET'; ASSIG_OP : '::='; -L_BRACKET : '{'; -R_BRACKET : '}'; +L_BRACKET : '{'; +R_BRACKET : '}'; L_PAREN : '('; R_PAREN : ')'; COMMA : ','; @@ -797,7 +797,7 @@ LESS_THAN : '<'; BitStringLiteral : '\'' ('0'|'1'|' ' | '\t' | '\r' | '\n')* '\'B' ; - + @@ -809,7 +809,7 @@ StringLiteral : STR+ ; fragment STR : '"' ( options {greedy=false;} : .)* '"' ; - + UID : ('A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9'|'-')* {if (Text.Contains("--")) { MismatchedSetException mse = new MismatchedSetException(null, input); @@ -827,11 +827,11 @@ LID : ('a'..'z') ('a'..'z'|'A'..'Z'|'0'..'9'|'-')* {if (Text.Contains("--")) ; -fragment +fragment INT : ('+'|'-')? ( '0' | ('1'..'9') ('0'..'9')*); - + fragment DIGITS : ('0'..'9')+; @@ -845,17 +845,17 @@ FloatingPointLiteral $r.Type = DOUBLE_DOT; Emit($r);$r.Line = input.Line; } - | INT DOT (DIGITS)? (Exponent)? + | INT DOT (DIGITS)? (Exponent)? | d = INT { $d.Type = INT; Emit($d);$d.Line = input.Line;} ; - - -DOT : '.'; + + +DOT : '.'; UNITS - : '--{' ( options {greedy=false;} : . )* '}--' + : '--{' ( options {greedy=false;} : . )* '}--' ; @@ -865,7 +865,7 @@ Exponent : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; WS : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;} - ; + ; COMMENT : '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;} diff --git a/BackendAst/BAst.fs b/BackendAst/BAst.fs index 38b8f1361..385be0cd1 100644 --- a/BackendAst/BAst.fs +++ b/BackendAst/BAst.fs @@ -29,9 +29,9 @@ type Integer = { withcons : IntegerTypeConstraint list uperRange : uperRange baseType : Integer option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -53,9 +53,9 @@ type Real = { withcons : RealTypeConstraint list uperRange : uperRange baseType : Real option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -71,9 +71,9 @@ type StringType = { maxSize : int charSet : char array baseType : StringType option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -86,7 +86,7 @@ type EnumItem = { ada_name:string } with - member this.getBackendName l = + member this.getBackendName l = match l with | C -> ToC this.c_name | Ada -> ToC this.ada_name @@ -101,13 +101,13 @@ type Enumerated = { cons : EnumConstraint list withcons : EnumConstraint list baseType : Enumerated option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons - + type Boolean = { id : ReferenceToType @@ -117,13 +117,13 @@ type Boolean = { cons : BoolConstraint list withcons : BoolConstraint list baseType : Boolean option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons - + type OctetString = { id : ReferenceToType @@ -135,9 +135,9 @@ type OctetString = { minSize : int maxSize : int baseType : OctetString option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -148,7 +148,7 @@ type NullType = { uperMaxSizeInBits : int uperMinSizeInBits : int baseType : NullType option - Location : SrcLoc + Location : SrcLoc } type BitString = { @@ -161,17 +161,17 @@ type BitString = { minSize : int maxSize : int baseType : BitString option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons -type Asn1Optionality = +type Asn1Optionality = | AlwaysAbsent | AlwaysPresent - | Optional + | Optional | Default of Asn1GenericValue type SequenceOf = { @@ -185,9 +185,9 @@ type SequenceOf = { minSize : int maxSize : int baseType : SequenceOf option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -197,8 +197,8 @@ and ChildInfo = { chType :Asn1Type Optionality :Asn1Optionality option Comments :string list - acnInsertetField :bool - Location : SrcLoc + acnInsertedField :bool + Location : SrcLoc } and Sequence = { @@ -210,9 +210,9 @@ and Sequence = { cons : SequenceConstraint list withcons : SequenceConstraint list baseType : Sequence option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -226,9 +226,9 @@ and Choice = { cons : ChoiceConstraint list withcons : ChoiceConstraint list baseType : Choice option - Location : SrcLoc + Location : SrcLoc } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -263,17 +263,17 @@ with | Choice t -> t.id member this.baseType = match this with - | Integer t -> t.baseType |> Option.map Integer - | Real t -> t.baseType |> Option.map Real - | IA5String t -> t.baseType |> Option.map IA5String - | OctetString t -> t.baseType |> Option.map OctetString - | NullType t -> t.baseType |> Option.map NullType - | BitString t -> t.baseType |> Option.map BitString - | Boolean t -> t.baseType |> Option.map Boolean - | Enumerated t -> t.baseType |> Option.map Enumerated - | SequenceOf t -> t.baseType |> Option.map SequenceOf - | Sequence t -> t.baseType |> Option.map Sequence - | Choice t -> t.baseType |> Option.map Choice + | Integer t -> t.baseType |> Option.map Integer + | Real t -> t.baseType |> Option.map Real + | IA5String t -> t.baseType |> Option.map IA5String + | OctetString t -> t.baseType |> Option.map OctetString + | NullType t -> t.baseType |> Option.map NullType + | BitString t -> t.baseType |> Option.map BitString + | Boolean t -> t.baseType |> Option.map Boolean + | Enumerated t -> t.baseType |> Option.map Enumerated + | SequenceOf t -> t.baseType |> Option.map SequenceOf + | Sequence t -> t.baseType |> Option.map Sequence + | Choice t -> t.baseType |> Option.map Choice member this.uperMaxSizeInBits = match this with | Integer t -> t.uperMaxSizeInBits @@ -301,7 +301,7 @@ with | Sequence t -> t.uperMinSizeInBits | Choice t -> t.uperMinSizeInBits - member this.asn1Name = + member this.asn1Name = match this.id with | ReferenceToType((GenericFold2.MD _)::(GenericFold2.TA tasName)::[]) -> Some tasName | _ -> None diff --git a/BackendAst/BAstConstruction.fs b/BackendAst/BAstConstruction.fs index 13131fd65..ce58c7bfc 100644 --- a/BackendAst/BAstConstruction.fs +++ b/BackendAst/BAstConstruction.fs @@ -13,7 +13,7 @@ type State = { anonymousTypes : Asn1Type list anonymousValues : Asn1GenericValue list } -//with +//with // member this.add (other:State) = // {State.anonymousTypes = this.anonymousTypes@other.anonymousTypes; anonymousValues = this.anonymousValues@other.anonymousValues} @@ -50,7 +50,7 @@ type InterimTypeKind = |InterimSequence of (Sequence option) * (ChildInfo list) |InterimChoice of (Choice option) * (ChildInfo list) -//let combineStates (states:State list)= +//let combineStates (states:State list)= // states |> List.fold (fun s c -> {State.anonymousTypes = s.anonymousTypes@c.anonymousTypes; anonymousValues = s.anonymousValues@c.anonymousValues}) {State.anonymousTypes =[]; anonymousValues = []} let addValue (s:State) (v:Asn1GenericValue)= @@ -62,28 +62,28 @@ let smap = GenericFold2.foldMap let createAstRoot (s:State) (sr:Ast.AstRoot) (dfiles: Asn1File list) (*(acn:AcnTypes.AcnAst)*) = { - AstRoot.Files = dfiles + AstRoot.Files = dfiles args = sr.args TypeAssignments = s.anonymousTypes |> List.filter (fun x -> x.asn1Name.IsSome) - ValueAssignments = s.anonymousValues - valsMap = - let aa = s.anonymousValues |> List.map(fun v -> v.id, v) + ValueAssignments = s.anonymousValues + valsMap = + let aa = s.anonymousValues |> List.map(fun v -> v.id, v) aa |> Seq.groupBy(fun (id,t) -> id) |> Seq.filter(fun (id, gr) -> gr |> (*Seq.distinct |>*) Seq.length > 1) |> Seq.iter (fun x -> printfn "%A" x) aa |> Map.ofList - typesMap = + typesMap = let aa = s.anonymousTypes |> List.map(fun v -> v.id, v) aa |> Seq.groupBy(fun (id,t) -> id) |> Seq.filter(fun (id, gr) -> gr |> (*Seq.distinct |>*) Seq.length > 1) |> Seq.iter (fun x -> printfn "%A" x) aa |> Map.ofList } -let createAsn1File (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (newMods:Asn1Module list) = +let createAsn1File (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (newMods:Asn1Module list) = { Asn1File.FileName = f.FileName; Tokens = f.Tokens - Modules = newMods + Modules = newMods },s -let createAsn1Module (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (newtases: Asn1Type list ) (vases:Asn1GenericValue list ) = +let createAsn1Module (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (newtases: Asn1Type list ) (vases:Asn1GenericValue list ) = { Asn1Module.Name = m.Name.Value Imports = m.Imports @@ -92,47 +92,47 @@ let createAsn1Module (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Modul }, s -let createTypeAssignment (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (tas:Ast.TypeAssignment) (newType:Asn1Type) = +let createTypeAssignment (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (tas:Ast.TypeAssignment) (newType:Asn1Type) = newType,s -let createValueAssignment (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (vas:Ast.ValueAssignment) (t:Asn1Type) (v:Asn1GenericValue) = +let createValueAssignment (s:State) (r:Ast.AstRoot) (f:Ast.Asn1File) (m:Ast.Asn1Module) (vas:Ast.ValueAssignment) (t:Asn1Type) (v:Asn1GenericValue) = v, s - -let createChildInfo (st:State) s (ch:Ast.ChildInfo) (newType:Asn1Type) (newOptionality:Asn1Optionality option) = + +let createChildInfo (st:State) s (ch:Ast.ChildInfo) (newType:Asn1Type) (newOptionality:Asn1Optionality option) = { ChildInfo.Name = ch.Name.Value chType = newType Optionality = newOptionality Comments = ch.Comments |> Seq.toList - acnInsertetField = false + acnInsertedField = false Location = ch.Name.Location }, st -let createChoiceChildInfo (st:State) s (ch:Ast.ChildInfo) (newType:Asn1Type) = +let createChoiceChildInfo (st:State) s (ch:Ast.ChildInfo) (newType:Asn1Type) = { ChildInfo.Name = ch.Name.Value chType = newType Optionality = None Comments = ch.Comments |> Seq.toList - acnInsertetField = false + acnInsertedField = false Location = ch.Name.Location }, st let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn1Type) (newCons:((Asn1AnyConstraint) option ) list, fromWithComps:((Asn1AnyConstraint) option ) list) (newKind:InterimTypeKind) integerSizeInBytes = - let newTypeId = ReferenceToType ts + let newTypeId = ReferenceToType ts match tryGetType s newTypeId with | Some t -> t,s | None -> - let numericStringDefaultConstraint = - let zeroToNine = Constraints.RangeContraint (('0',Literal), ('9',Literal),true,true) + let numericStringDefaultConstraint = + let zeroToNine = Constraints.RangeConstraint (('0',Literal), ('9',Literal),true,true) let space = Constraints.RangeSingleValueConstraint (" ", Literal) - let numericCon = Constraints.AlphabetContraint (Constraints.RangeUnionConstraint (zeroToNine, space, true)) + let numericCon = Constraints.AlphabetConstraint (Constraints.RangeUnionConstraint (zeroToNine, space, true)) numericCon - let rec inheritedCons f1 f2 par = + let rec inheritedCons f1 f2 par = match par with | None -> [] | Some p -> (f1 p)@(inheritedCons f1 f2 (f2 p)) @@ -151,28 +151,28 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn | _ when a<>b && b<65536 -> a*internalSize + (lenSize a b), b*internalSize + (lenSize a b) | _ -> a*internalSize + (lenSize a b), b*internalSize + (b / 65536 + 3) * 8 let tasInfo = newTypeId.Asn1TypeName |> Option.map(fun x -> {TypeAssignmentInfo.modName = x.moduName; tasName = x.tasName}) - let ret = + let ret = match newKind with - | InterimInteger baseType -> - let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getIntegerTypeConstraint - let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getIntegerTypeConstraint + | InterimInteger baseType -> + let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getIntegerTypeConstraint + let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getIntegerTypeConstraint let inhCons = inheritedCons (fun (x:Integer) -> x.cons) (fun x -> x.baseType) baseType let uperCons, rootCons = cons@inhCons |> List.split(fun c -> match c with RangeRootConstraint _ | RangeRootConstraint2 _ -> false | _ -> true) let uperR = getIntTypeConstraintUperRange uperCons oldType.Location - let uperMinSizeInBits, uperMaxSizeInBits = + let uperMinSizeInBits, uperMaxSizeInBits = match rootCons with | [] -> getRequiredBitsForIntUperEncoding uperR - | _ -> + | _ -> let mn,mx = getRequiredBitsForIntUperEncoding uperR 1 + mn, 1 + mx Integer {Integer.baseType = baseType; cons = cons; withcons = withcons; uperRange = uperR; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} - | InterimReal baseType -> - let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getRealTypeConstraint - let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getRealTypeConstraint + | InterimReal baseType -> + let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getRealTypeConstraint + let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getRealTypeConstraint let inhCons = inheritedCons (fun (x:Real) -> x.cons) (fun x -> x.baseType) baseType let uperR = getRealTypeConstraintUperRange (cons@inhCons) oldType.Location Real {Real.baseType = baseType; cons = cons; withcons = withcons; uperRange = uperR; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=(5+integerSizeInBytes)*8; uperMinSizeInBits=8} - | InterimIA5String baseType -> + | InterimIA5String baseType -> let defaultCharSet = [|for i in 0..127 -> System.Convert.ToChar(i) |] let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getIA5StringConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getIA5StringConstraint @@ -185,7 +185,7 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn IA5String {StringType.baseType=baseType; cons = cons; withcons = withcons; minSize=minSize; maxSize=maxSize; charSet=charSet; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} - | InterimNumericString baseType -> + | InterimNumericString baseType -> let defaultCharSet = [| ' ';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9'|] let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getIA5StringConstraint let cons = match baseType with None -> numericStringDefaultConstraint::cons | Some _ -> cons @@ -198,7 +198,7 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn let uperMinSizeInBits, uperMaxSizeInBits = getSizeableTypeSize minSize maxSize charSize IA5String {StringType.baseType=baseType; cons = cons; withcons = withcons; minSize=minSize; maxSize=maxSize; charSet=charSet; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} - | InterimOctetString baseType -> + | InterimOctetString baseType -> let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getOctetStringConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getOctetStringConstraint let inhCons = inheritedCons (fun (x:OctetString) -> x.cons) (fun x -> x.baseType) baseType @@ -207,24 +207,24 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn let uperMinSizeInBits, uperMaxSizeInBits = getSizeableTypeSize minSize maxSize 8 OctetString {OctetString.baseType=baseType; cons = cons; withcons = withcons; minSize=minSize; maxSize=maxSize; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} | InterimNullType baseType -> NullType {NullType.baseType=baseType; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=0; uperMinSizeInBits=0} - | InterimBitString baseType -> - let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getBitStringConstraint + | InterimBitString baseType -> + let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getBitStringConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getBitStringConstraint let inhCons = inheritedCons (fun (x:BitString) -> x.cons) (fun x -> x.baseType) baseType let sizeUperRange = getBitStringUperRange (cons@inhCons) oldType.Location let minSize, maxSize = getSizeMinAndMaxValue sizeUperRange let uperMinSizeInBits, uperMaxSizeInBits = getSizeableTypeSize minSize maxSize 1 BitString {BitString.baseType=baseType; cons = cons; withcons = withcons; minSize=minSize; maxSize=maxSize; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} - | InterimBoolean baseType -> + | InterimBoolean baseType -> let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getBoolConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getBoolConstraint Boolean {Boolean.baseType=baseType; cons=cons; withcons = withcons; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=1; uperMinSizeInBits=1} - | InterimEnumerated (baseType, items, userDefinedValues) -> + | InterimEnumerated (baseType, items, userDefinedValues) -> let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getEnumConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getEnumConstraint let uperSizeInBits = int32(GetNumberOfBitsForNonNegativeInteger(BigInteger((Seq.length items) - 1))) Enumerated {Enumerated.baseType=baseType; items=items;userDefinedValues=userDefinedValues; cons = cons; withcons = withcons; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperSizeInBits; uperMinSizeInBits=uperSizeInBits} - | InterimSequenceOf (baseType,childType) -> + | InterimSequenceOf (baseType,childType) -> let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getSequenceOfConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getSequenceOfConstraint let inhCons = inheritedCons (fun (x:SequenceOf) -> x.cons) (fun x -> x.baseType) baseType @@ -233,15 +233,15 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn let uperMinSizeInBits, _ = getSizeableTypeSize minSize maxSize childType.uperMinSizeInBits let _, uperMaxSizeInBits = getSizeableTypeSize minSize maxSize childType.uperMaxSizeInBits SequenceOf {SequenceOf.baseType=baseType; childType=childType; cons=cons; withcons = withcons; minSize=minSize; maxSize=maxSize; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits} - | InterimSequence (baseType,children) -> + | InterimSequence (baseType,children) -> let optionalChildren = children |> Seq.filter(fun c -> c.Optionality.IsSome) let bitMaskSize = Seq.length optionalChildren let maxChildrenSize = children |> List.map(fun x -> x.chType.uperMaxSizeInBits) |> Seq.sum let minChildrenSize = children |> List.filter(fun x -> x.Optionality.IsNone) |> List.map(fun x -> x.chType.uperMinSizeInBits) |> Seq.sum - let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getSequenceConstraint + let cons = newCons |> List.choose id |> List.map ConstraintsMapping.getSequenceConstraint let withcons = fromWithComps |> List.choose id |> List.map ConstraintsMapping.getSequenceConstraint Sequence {Sequence.baseType = baseType; children=children; cons=cons; withcons = withcons; Location=oldType.Location; id=newTypeId; tasInfo= tasInfo; uperMaxSizeInBits=bitMaskSize+maxChildrenSize; uperMinSizeInBits=bitMaskSize+minChildrenSize } - | InterimChoice (baseType,children) -> + | InterimChoice (baseType,children) -> let indexSize = int (GetNumberOfBitsForNonNegativeInteger(BigInteger(Seq.length children))) let minChildSize = children |> List.map(fun x -> x.chType.uperMinSizeInBits) |> Seq.min let maxChildSize = children |> List.map(fun x -> x.chType.uperMaxSizeInBits) |> Seq.max @@ -252,9 +252,9 @@ let createType (s:State) (ts:GenericFold2.UserDefinedTypeScope) (oldType:Ast.Asn ret, {s with anonymousTypes = s.anonymousTypes@[ret]} let createValue (us:State) (asn1ValName:(StringLoc*StringLoc) option) (ts:GenericFold2.UserDefinedTypeScope) (vs:GenericFold2.UserDefinedVarScope) (v:Asn1GenericValue) = - (*let ret = + (*let ret = { - Asn1GenericValue.asn1Name = asn1ValName + Asn1GenericValue.asn1Name = asn1ValName id = ReferenceToValue (ts, vs) //baseValue = baseValue refToType = ReferenceToType ts @@ -267,8 +267,8 @@ let createValue (us:State) (asn1ValName:(StringLoc*StringLoc) option) (ts:Generi let Asn1typeToInterimType (t:Asn1Type) = match t with - | Integer t -> InterimInteger t.baseType - | Real t -> InterimReal t.baseType + | Integer t -> InterimInteger t.baseType + | Real t -> InterimReal t.baseType | IA5String t -> InterimIA5String t.baseType | OctetString t -> InterimOctetString t.baseType | NullType t -> InterimNullType t.baseType @@ -281,11 +281,11 @@ let Asn1typeToInterimType (t:Asn1Type) = let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnTypes.AcnAst)*) = - let l_aux (asn1ValName: (StringLoc*StringLoc) option) = + let l_aux (asn1ValName: (StringLoc*StringLoc) option) = match asn1ValName with | None -> Literal | Some (md,vs) -> ReferenceToAsn1NamedValue {Asn1ValueName.moduName=md.Value; vasName=vs.Value} - let s_aux v us = + let s_aux v us = v, {us with anonymousValues=us.anonymousValues@[v]} GenericFold2.foldAstRoot //1. rootFunc r files @@ -299,24 +299,24 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT //4. tasFunc r f m tas asn1Type createTypeAssignment - + //5. vasFunc r f m vas asn1Type asn1Value createValueAssignment //6. typeFunc s t newTypeKind baseTypeId (newCons,fromWithComps) - (fun ustate s t newTypeKind (newCons,fromWithComps) -> + (fun ustate s t newTypeKind (newCons,fromWithComps) -> createType ustate s t (newCons,fromWithComps) newTypeKind app.args.integerSizeInBytes) - //7. refTypeFunc s mdName tasName tabularized + //7. refTypeFunc s mdName tasName tabularized (* - (fun ustate mdName tasName tabularized newBaseType -> - let retKind = + (fun ustate mdName tasName tabularized newBaseType -> + let retKind = match newBaseType with | Integer ti -> InterimInteger (Some ti) | Real ti -> InterimReal (Some ti) | IA5String ti -> InterimIA5String (Some ti) | OctetString ti -> InterimOctetString (Some ti) - | NullType ti -> InterimNullType (Some ti) + | NullType ti -> InterimNullType (Some ti) | BitString ti -> InterimBitString (Some ti) | Boolean ti -> InterimBoolean (Some ti) | Enumerated ti -> InterimEnumerated (Some ti, ti.items, ti.userDefinedValues) @@ -326,13 +326,13 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT retKind, ustate) *) - //8 integerFunc s + //8 integerFunc s (fun newBaseType ustate -> InterimInteger (getAsInteger newBaseType),ustate) - //9 realFunc s + //9 realFunc s (fun newBaseType ustate -> InterimReal (getAsReal newBaseType), ustate) - //10 ia5StringFunc s + //10 ia5StringFunc s (fun newBaseType ustate -> InterimIA5String (getAsIA5String newBaseType), ustate) //11 numericStringFunc s @@ -350,30 +350,30 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT //15 booleanFunc (fun newBaseType ustate -> InterimBoolean (getAsBoolean newBaseType), ustate) - //16 enumeratedFunc - (fun ustate newBaseType (enmItems : Ast.NamedItem list)-> - let newEnmItems, userDefinedValues = + //16 enumeratedFunc + (fun ustate newBaseType (enmItems : Ast.NamedItem list)-> + let newEnmItems, userDefinedValues = match enmItems |> Seq.exists (fun nm -> nm._value.IsSome) with | false -> enmItems |> List.mapi(fun i x -> {EnumItem.name = x.Name.Value; c_name = x.c_name; ada_name = x.ada_name; Value = BigInteger i; comments = x.Comments|> Seq.toList} ), false | true -> - let withVals = Ast.allocatedValuesToAllEnumItems enmItems app + let withVals = Ast.allocatedValuesToAllEnumItems enmItems app withVals |> List.mapi(fun i x -> {EnumItem.name = x.Name.Value; c_name = x.c_name; ada_name = x.ada_name; Value = BigInteger i; comments = x.Comments|> Seq.toList} ), true InterimEnumerated ((getAsEnumerated newBaseType), newEnmItems, userDefinedValues), ustate) //17 enmItemFunc (fun ustate ni newVal -> 0, ustate) - //18 seqOfTypeFunc + //18 seqOfTypeFunc (fun ustate newInnerType newBaseType -> InterimSequenceOf ((getAsSequenceOf newBaseType), newInnerType), ustate) - //19 seqTypeFunc + //19 seqTypeFunc (fun ustate newChildren newBaseType -> InterimSequence ((getAsSequence newBaseType), newChildren) , ustate) - //20 chTypeFunc + //20 chTypeFunc (fun ustate newChildren newBaseType -> InterimChoice ((getAsChoice newBaseType), newChildren), ustate) - //21 sequenceChildFunc + //21 sequenceChildFunc createChildInfo //22 alwaysAbsentFunc @@ -386,105 +386,105 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT (fun s -> Asn1Optionality.Optional) //25 defaultFunc - (fun s (newValue) -> + (fun s (newValue) -> Asn1Optionality.Default newValue) //26 choiceChildFunc createChoiceChildInfo - //27 refValueFunc - (fun _ -> 0) + //27 refValueFunc + (fun _ -> 0) //28 enumValueFunc - (fun us asn1ValName ts vs v nmItem childValue -> + (fun us asn1ValName ts vs v nmItem childValue -> let ret = EnumValue {EnumValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=nmItem.Value; childValue=childValue} s_aux ret us) //29 intValFunc - (fun us asn1ValName ts vs v bi childValue -> + (fun us asn1ValName ts vs v bi childValue -> let ret = IntegerValue {IntegerValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=bi.Value; childValue=childValue} s_aux ret us) //30 realValFunc - (fun us asn1ValName ts vs v bi childValue -> + (fun us asn1ValName ts vs v bi childValue -> let ret = RealValue {RealValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=bi.Value; childValue=childValue} s_aux ret us) - //31 ia5StringValFunc - (fun us asn1ValName ts vs v str childValue-> + //31 ia5StringValFunc + (fun us asn1ValName ts vs v str childValue-> let ret = StringValue {StringValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=str.Value; childValue=childValue} s_aux ret us) - //32 numStringValFunc - (fun us asn1ValName ts vs v str childValue-> + //32 numStringValFunc + (fun us asn1ValName ts vs v str childValue-> let ret = StringValue {StringValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=str.Value; childValue=childValue} s_aux ret us) - //33 boolValFunc - (fun us asn1ValName ts vs v b childValue -> + //33 boolValFunc + (fun us asn1ValName ts vs v b childValue -> let ret = BooleanValue {BooleanValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=b.Value; childValue=childValue} s_aux ret us) //34 octetStringValueFunc - (fun us asn1ValName ts vs v bytes childValue-> + (fun us asn1ValName ts vs v bytes childValue-> let ret = OctetStringValue {OctetStringValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=bytes |> List.map(fun b->b.Value); childValue=childValue} s_aux ret us) //createValue us asn1ValName ts vs (OctetStringValue (bytes |> List.map(fun b->b.Value))) ) //35 bitStringValueFunc - (fun us asn1ValName ts vs v b childValue -> + (fun us asn1ValName ts vs v b childValue -> let ret = BitStringValue {BitStringValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=b.Value; childValue=childValue} s_aux ret us) //36 nullValueFunc - (fun us asn1ValName ts vs v childValue -> + (fun us asn1ValName ts vs v childValue -> let ret = NullValue {NullValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=(); childValue=childValue} s_aux ret us) //37 seqOfValueFunc s t v actType newVals - (fun us asn1ValName ts vs v newVals childValue -> + (fun us asn1ValName ts vs v newVals childValue -> let ret = SeqOfValue {SeqOfValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=newVals; childValue=childValue} s_aux ret us) - //38 seqValueFunc - (fun us asn1ValName ts vs v newVals childValue -> + //38 seqValueFunc + (fun us asn1ValName ts vs v newVals childValue -> let newVals = newVals |> List.map (fun (nm, (v)) -> {NamedValue.name=nm.Value;Value=v}) let ret = SeqValue {SeqValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value=newVals; childValue=childValue} s_aux ret us) //39 chValueFunc s t v actType name newValue - (fun us asn1ValName ts vs v name newChValue childValue -> + (fun us asn1ValName ts vs v name newChValue childValue -> let ret = ChValue {ChValue.litOrRef=l_aux asn1ValName; id=ReferenceToValue (ts, vs); refToType=ReferenceToType ts; Value={NamedValue.name=name.Value;Value=newChValue}; childValue=childValue} s_aux ret us) - //40 singleValueContraintFunc s t checContent actType newValue - (fun us ts t checContent newValue-> - Some (AnySingleValueContraint newValue), us) + //40 singleValueConstraintFunc s t checContent actType newValue + (fun us ts t checContent newValue-> + Some (AnySingleValueConstraint newValue), us) - //41 rangeContraintFunc s t checContent actType newValue1 newValue2 b1 b2 - (fun us ts t checContent (newValue1) (newValue2) b1 b2 -> - Some (AnyRangeContraint(newValue1, newValue2, b1, b2)), us) + //41 rangeConstraintFunc s t checContent actType newValue1 newValue2 b1 b2 + (fun us ts t checContent (newValue1) (newValue2) b1 b2 -> + Some (AnyRangeConstraint(newValue1, newValue2, b1, b2)), us) - //42 rangeContraint_val_MAXFunc s t checContent actType newValue b - (fun us ts t checContent (newValue) b -> - Some (AnyRangeContraint_val_MAX (newValue,b)), us) + //42 rangeConstraint_val_MAXFunc s t checContent actType newValue b + (fun us ts t checContent (newValue) b -> + Some (AnyRangeConstraint_val_MAX (newValue,b)), us) - //43 rangeContraint_MIN_valFunc s t checContent actType newValue b - (fun us ts t checContent (newValue) b -> - Some (AnyRangeContraint_MIN_val(newValue,b)), us ) + //43 rangeConstraint_MIN_valFunc s t checContent actType newValue b + (fun us ts t checContent (newValue) b -> + Some (AnyRangeConstraint_MIN_val(newValue,b)), us ) - //44 rangeContraint_MIN_MAXFunc s t checContent actType + //44 rangeConstraint_MIN_MAXFunc s t checContent actType (fun us ts t checContent -> None, us) //45 typeInclConstraintFunc s t actType (md,tas) - (fun us ts t otherCon -> + (fun us ts t otherCon -> match otherCon with | Some x -> x, us | None -> None, us ) //46 unionConstraintFunc s t actType nc1 nc2 - (fun us ts t x1 x2 virtualCon -> + (fun us ts t x1 x2 virtualCon -> match x1, x2 with | Some (nc1), Some (nc2) -> Some (AnyUnionConstraint (nc1, nc2, virtualCon)), us | Some (nc1), None -> None, us @@ -492,7 +492,7 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT | None, None -> None, us) //47 intersectionConstraintFunc s t actType nc1 nc2 - (fun us ts t x1 x2 -> + (fun us ts t x1 x2 -> match x1, x2 with | Some (nc1), Some (nc2) -> Some (AnyIntersectionConstraint (nc1,nc2)), us | Some (nc1), None -> Some (nc1), us @@ -500,13 +500,13 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT | None, None -> None, us) //48 allExceptConstraintFunc s t actType nc - (fun us ts t x1 -> + (fun us ts t x1 -> match x1 with | Some (nc1) -> Some (AnyAllExceptConstraint nc1), us | None -> raise(SemanticError(t.Location, (sprintf "EXCEPT constraint makes type to allow no values. Consider changing the EXCET part"))) ) //49 exceptConstraintFunc s t actType nc1 nc2 - (fun us ts t x1 x2 -> + (fun us ts t x1 x2 -> match x1, x2 with | Some (nc1), Some (nc2) -> Some (AnyExceptConstraint(nc1,nc2)), us | Some (nc1), None -> raise(SemanticError(t.Location, (sprintf "EXCEPT constraint makes type to allow no values. Consider changing the EXCET part"))) @@ -518,18 +518,18 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT (fun us ts t x1 -> x1 |> Option.map (fun (nc) -> AnyRootConstraint nc), us ) //51 rootConstraint2Func s t actType nc1 nc2 - (fun us ts t x1 x2 -> + (fun us ts t x1 x2 -> match x1, x2 with | Some (nc1), Some (nc2) -> Some (AnyRootConstraint2 (nc1,nc2)), us | Some (nc1), None -> None, us | None, Some (nc2) -> None, us | None, None -> None, us) - - //52 sizeContraint - (fun us ts t x1 -> x1 |> Option.map (fun (nc) -> AnySizeContraint nc), us ) - - //53 alphabetContraint - (fun us ts t x1 -> x1 |> Option.map (fun (nc) -> AnyAlphabetContraint nc), us ) + + //52 sizeConstraint + (fun us ts t x1 -> x1 |> Option.map (fun (nc) -> AnySizeConstraint nc), us ) + + //53 alphabetConstraint + (fun us ts t x1 -> x1 |> Option.map (fun (nc) -> AnyAlphabetConstraint nc), us ) //54 withComponentConstraint ts t (fun us ts t -> None, us) @@ -541,44 +541,44 @@ let createValidationAst (lang:ProgrammingLanguage) (app:Ast.AstRoot) (*(acn:AcnT (fun _ -> [], InterimInteger None) //57 getSequenceOfTypeChild - (fun us newTypeKind -> + (fun us newTypeKind -> match newTypeKind with - | InterimSequenceOf (_,sq) -> + | InterimSequenceOf (_,sq) -> //let retType = us.anonymousTypes |> Seq.find(fun at -> at.id = sq.childTypeRef) let (ReferenceToType referenceToType) = sq.id - (referenceToType, Asn1typeToInterimType sq) + (referenceToType, Asn1typeToInterimType sq) | _ -> raise(BugErrorException(sprintf "Expecting SequenceOf, found %A" newTypeKind))) //58 getChoiceTypeChild (fun us newTypeKind chName -> match newTypeKind with - | InterimChoice (_,children) -> + | InterimChoice (_,children) -> match children |> List.tryFind (fun c -> c.Name = chName.Value) with - | Some ch -> + | Some ch -> let (ReferenceToType referenceToType) = ch.chType.id //let retType = us.anonymousTypes |> Seq.find(fun at -> at.id = (ReferenceToType referenceToType)) - (referenceToType, Asn1typeToInterimType ch.chType) + (referenceToType, Asn1typeToInterimType ch.chType) | None -> raise(SemanticError(chName.Location, (sprintf "CHOICE type has no alternative with name '%s'" chName.Value))) | _ -> raise(BugErrorException(sprintf "Expecting Choice, found %A" newTypeKind)) ) - + //59 getSequenceTypeChild (fun us newTypeKind chName -> match newTypeKind with - | InterimSequence (_,children) -> + | InterimSequence (_,children) -> match children |> List.tryFind (fun c -> c.Name = chName.Value) with - | Some ch -> + | Some ch -> let (ReferenceToType referenceToType) = ch.chType.id //let retType = us.anonymousTypes |> Seq.find(fun at -> at.id = (ReferenceToType referenceToType)) - (referenceToType, Asn1typeToInterimType ch.chType) + (referenceToType, Asn1typeToInterimType ch.chType) | None -> raise(SemanticError(chName.Location, (sprintf "SEQUENCE type has no alternative with name '%s'" chName.Value))) | _ -> raise(BugErrorException(sprintf "Expecting SEQUENCE, found %A" newTypeKind)) ) //60 getTypeKind (fun newT -> Asn1typeToInterimType newT) - (fun us s -> - let newTypeId = ReferenceToType s + (fun us s -> + let newTypeId = ReferenceToType s match tryGetType us newTypeId with | Some t -> Some(t,us) | None -> None ) diff --git a/BackendAst/BackendAst.fs b/BackendAst/BackendAst.fs index e37966bec..36033c21f 100644 --- a/BackendAst/BackendAst.fs +++ b/BackendAst/BackendAst.fs @@ -24,9 +24,9 @@ type LOCAL_VARIABLE = | LEN2 -type PathToRoot = +type PathToRoot = PathToRoot of string list -type AccessPath = +type AccessPath = | AccessPath of string (* @@ -37,13 +37,13 @@ type CharComparisonBoolExp = | AlphaOr of CharComparisonBoolExp*CharComparisonBoolExp | AlphaAnd of CharComparisonBoolExp*CharComparisonBoolExp | AlphaNot of CharComparisonBoolExp - | AlphaEq of AccessPath*char - | AlphaGreaterThan of AccessPath*char - | AlphaGreaterThanOrEq of AccessPath*char - | AlphaLessThan of AccessPath*char - | AlphaLessThanOrEq of AccessPath*char - | AlphaStringContainsChar of AccessPath*string - + | AlphaEq of AccessPath*char + | AlphaGreaterThan of AccessPath*char + | AlphaGreaterThanOrEq of AccessPath*char + | AlphaLessThan of AccessPath*char + | AlphaLessThanOrEq of AccessPath*char + | AlphaStringContainsChar of AccessPath*string + type AlphabetCheckFunc = { @@ -58,7 +58,7 @@ type UnnamedVariableDeclaration = typereference : string*string value : string //needs to defined } - + type BackendPrimaryNumericExpression = | IntegerLiteral of BigInteger*string //int value, prefix e.g L, UL etc @@ -66,7 +66,7 @@ type BackendPrimaryNumericExpression = | ReferenceToRangeVas of (string*string) (* -A BackendPrimaryExpression is an expression in the target language (C or Ada) +A BackendPrimaryExpression is an expression in the target language (C or Ada) It is either a constant (literal) or an identifier *) type BackendPrimaryExpression = @@ -76,9 +76,9 @@ type BackendPrimaryExpression = | EnumeratedTypeLiteral of string | BooleanLiteral of bool | ReferenceToVas of (string*string) - | NullTypeLiteral + | NullTypeLiteral + - type BackendBooleanExpression = | OrConstraintExp of BackendBooleanExpression*BackendBooleanExpression @@ -90,7 +90,7 @@ type BackendBooleanExpression = | LessThanExp of AccessPath*BackendPrimaryNumericExpression | LessThanOrEqExp of AccessPath*BackendPrimaryNumericExpression | CallAlphaFunc of AccessPath*AlphabetCheckFunc - | FixSizeBitStringEq of AccessPath*UnnamedVariableDeclaration + | FixSizeBitStringEq of AccessPath*UnnamedVariableDeclaration | VarSizeBitStringEq of AccessPath*UnnamedVariableDeclaration | FixSizeOctStringEq of AccessPath*UnnamedVariableDeclaration | VarSizeOctStringEq of AccessPath*UnnamedVariableDeclaration @@ -100,10 +100,10 @@ type TypeIsValidFuncBody = | SequenceIsValidFuncBody of SeqeunceComponentCheckBody list | SequenceOfIsValidFuncBody of SeqeunceOfCheck | BaseTypeIsValidFuncBody of BaseTypeIsValidFuncBody -with +with member this.hasValidateFunc = false -and SeqeunceComponentCheckBody = +and SeqeunceComponentCheckBody = | CheckComponent of PathToRoot*TypeIsValidFuncBody | CheckOptionalComponent of PathToRoot*TypeIsValidFuncBody | CheckComponentIsPresent of PathToRoot*AlwaysPresentOrAbsentCheck @@ -112,7 +112,7 @@ and SeqeunceComponentCheckBody = and AlwaysPresentOrAbsentCheck = { childExitsPath : string errorCode : string -} +} and SeqeunceOfCheck = { path:PathToRoot @@ -124,7 +124,7 @@ and SeqeunceOfCheck = { } and BaseTypeIsValidFuncBody = { - t:ConstraintType + t:ConstraintType path:PathToRoot alphaFuncName : string //= ToC ((path |> Seq.skip 1).StrJoin("_").Replace("#","elem")) errCodeName : string option //GetTypeConstraintsErrorCode t.Type.Constraints path r @@ -134,24 +134,24 @@ and BaseTypeIsValidFuncBody = { type TasIsConstraintValid = { funcName :string //sContent : TypeIsValidFuncBody -} with - member - this.LocalVars : LOCAL_VARIABLE list = +} with + member + this.LocalVars : LOCAL_VARIABLE list = [] - member - this.AlphaCheckFunctions : AlphabetCheckFunc list = + member + this.AlphaCheckFunctions : AlphabetCheckFunc list = [] type TasIsEqual = { funcName :string -} +} -type TasInititalize = { +type TasInitialize = { funcName :string } (* -type EncodingPrototype = +type EncodingPrototype = | BER_EncPrototype of string*string | BER_DecPrototype of string*string | XER_EncPrototype of string*string @@ -224,24 +224,24 @@ type TasDefition = { errorCodes : string list isConstraintValidFnc : TasIsConstraintValid isEqualFnc : TasIsEqual - inititalizeFnc : TasInititalize + initializeFnc : TasInitialize } type DefinitionsFile = { fileName : string fileNameNoExtUpper : string tases : TasDefition list - //vases - //protos + //vases + //protos //enumAndChoiceUtils } -let TypeItemsCount (t:Asn1Type) (r:AstRoot)= +let TypeItemsCount (t:Asn1Type) (r:AstRoot)= match (GetTypeUperRange t.Kind t.Constraints r) with |Concrete(_, max) -> max |_ -> raise(BugErrorException "SEQUENCE OF or OCTET STRING etc has no constraints") -let rec TypeCArrayItemsCount (t:Asn1Type) (r:AstRoot)= +let rec TypeCArrayItemsCount (t:Asn1Type) (r:AstRoot)= match t.Kind with | BitString(_) -> BigInteger(System.Math.Ceiling(float(TypeItemsCount t r)/8.0)) | IA5String | NumericString -> (TypeItemsCount t r) + 1I @@ -252,13 +252,13 @@ let rec TypeCArrayItemsCount (t:Asn1Type) (r:AstRoot)= |_ -> raise(BugErrorException "TypeCArrayItemsCount called for a non sizeable type") -let TypeArrayPostfix (t:Asn1Type) (r:AstRoot)= +let TypeArrayPostfix (t:Asn1Type) (r:AstRoot)= match t.Kind with | IA5String | NumericString -> "[" + (TypeCArrayItemsCount t r).ToString() + "]" - | ReferenceType(refCon, _, _) -> "" + | ReferenceType(refCon, _, _) -> "" | _ -> "" -let rec TypeStar (t:Asn1Type) (r:AstRoot)= +let rec TypeStar (t:Asn1Type) (r:AstRoot)= match t.Kind with | IA5String | NumericString -> "" | ReferenceType(_) -> TypeStar (Ast.GetActualType t r) r @@ -270,4 +270,4 @@ let TypeLongName (p:list) = let keyAsStr = p.Tail ToC (keyAsStr.StrJoin("_").Replace("#","elem")) - + diff --git a/BackendAst/BackendAst.fsproj b/BackendAst/BackendAst.fsproj index e781a1537..d866ad752 100644 --- a/BackendAst/BackendAst.fsproj +++ b/BackendAst/BackendAst.fsproj @@ -1,5 +1,4 @@ - - + net7.0 true @@ -17,11 +16,11 @@ + + - - @@ -34,18 +33,16 @@ - - - - - - - - - - - - + + + + + + + + + + ..\Antlr\antlr313\antlr.runtime.dll @@ -59,9 +56,7 @@ ..\Antlr\antlr313\StringTemplate.dll - - - - - - + + + + \ No newline at end of file diff --git a/BackendAst/BastAddAcnInsertFields.fs b/BackendAst/BastAddAcnInsertFields.fs index 9ecde1994..fa2f33c76 100644 --- a/BackendAst/BastAddAcnInsertFields.fs +++ b/BackendAst/BastAddAcnInsertFields.fs @@ -38,8 +38,8 @@ let mapBTypeToBType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac SequenceOf //sequence - (fun o newChild us -> {ChildInfo.Name = o.Name; chType = newChild; Optionality = o.Optionality; acnInsertetField = o.acnInsertetField; Comments = o.Comments; Location = o.Location}, us) - (fun children o newBase us -> + (fun o newChild us -> {ChildInfo.Name = o.Name; chType = newChild; Optionality = o.Optionality; acnInsertedField = o.acnInsertedField; Comments = o.Comments; Location = o.Location}, us) + (fun children o newBase us -> let acnAbsPath = o.id.AcnAbsPath let acnChildren = acn.Types |> Seq.filter(fun x -> x.TypeID.Length-1=acnAbsPath.Length && (x.TypeID|>Seq.take acnAbsPath.Length|>Seq.toList)=acnAbsPath) |> Seq.toList let newChildren = @@ -55,22 +55,22 @@ let mapBTypeToBType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac let newTypeId = o.id.getSeqChildId acnChildName yield { ChildInfo.Name = acnChildName - chType = + chType = match acnChild.ImpMode with | AcnTypes.RecordField -> raise(BugErrorException "Child exists in ASN.1") | AcnTypes.AcnTypeImplMode.LocalVariable(asn1Type) | AcnTypes.FunctionParameter(asn1Type) -> match asn1Type with - | AcnTypes.Integer -> + | AcnTypes.Integer -> Integer {Integer.id= newTypeId; tasInfo = None; Location = acnChild.Location; cons=[]; withcons=[]; baseType=None; uperMaxSizeInBits=0; uperMinSizeInBits=0;uperRange=uPER2.Full} - | AcnTypes.Boolean -> + | AcnTypes.Boolean -> Boolean {Boolean.id= newTypeId; tasInfo = None; Location = acnChild.Location; cons=[]; withcons=[]; baseType=None; uperMaxSizeInBits=0; uperMinSizeInBits=0} - | AcnTypes.NullType -> + | AcnTypes.NullType -> NullType {NullType.id= newTypeId; tasInfo = None; Location = acnChild.Location; baseType=None; uperMaxSizeInBits=0; uperMinSizeInBits=0} - | AcnTypes.RefTypeCon(md,ts) -> + | AcnTypes.RefTypeCon(md,ts) -> match r.TypeAssignments |> List.tryFind(fun x -> x.id.beginsWith md.Value ts.Value) with | Some t -> t | None -> raise(SemanticError(ts.Location, sprintf "Unknown referenced type %s.%s " md.Value ts.Value)) - acnInsertetField = true + acnInsertedField = true Optionality = None Comments = acnChild.Comments |> Seq.toList Location = acnChild.Location @@ -82,7 +82,7 @@ let mapBTypeToBType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac Sequence //Choice - (fun o newChild us -> {ChildInfo.Name = o.Name; chType = newChild; Optionality = o.Optionality; Comments = o.Comments; acnInsertetField=false; Location = o.Location}, us) + (fun o newChild us -> {ChildInfo.Name = o.Name; chType = newChild; Optionality = o.Optionality; Comments = o.Comments; acnInsertedField=false; Location = o.Location}, us) (fun children o newBase us -> {Choice.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; children = children; cons=o.cons; withcons = o.withcons; baseType = newBase; Location = o.Location}, us) Choice @@ -95,12 +95,12 @@ let foldMap = GenericFold2.foldMap let doWork (r:BAst.AstRoot) (acn:AcnTypes.AcnAst) : AstRoot= let initialState = {State.currentTypes = []} let acnTypes = acn.Types |> List.map(fun t -> t.TypeID, t) |> Map.ofList - let newTypes,_ = + let newTypes,_ = r.TypeAssignments |> foldMap (fun cs t -> let newType, newState = mapBTypeToBType r t acn acnTypes cs newType, {newState with currentTypes = newState.currentTypes@[newType]} - ) initialState + ) initialState { AstRoot.Files = r.Files args = r.args diff --git a/BackendAst/CAst.fs b/BackendAst/CAst.fs index 375df1503..c5d83a5a2 100644 --- a/BackendAst/CAst.fs +++ b/BackendAst/CAst.fs @@ -8,7 +8,7 @@ open FsUtils open Constraints open uPER2 -type AcnAligment = +type AcnAlignment = | NextByte | NextWord | NextDWord @@ -49,16 +49,16 @@ type Integer = { withcons : IntegerTypeConstraint list uperRange : uperRange baseType : Integer option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : IntEncodingClass } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -67,7 +67,7 @@ with type EnumAcnEncodingClass = | EncodeIndexes of IntEncodingClass - | EncodeValues of IntEncodingClass + | EncodeValues of IntEncodingClass type Enumerated = { @@ -80,15 +80,15 @@ type Enumerated = { cons : EnumConstraint list withcons : EnumConstraint list baseType : Enumerated option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option enumEncodingClass : EnumAcnEncodingClass } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -102,7 +102,7 @@ type RealEncodingClass = | Real_IEEE754_64_little_endian type Real = { - //bast inherrited properties + //bast inherited properties id : ReferenceToType tasInfo : BAst.TypeAssignmentInfo option uperMaxSizeInBits : int @@ -111,21 +111,21 @@ type Real = { withcons : RealTypeConstraint list uperRange : uperRange baseType : Real option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : RealEncodingClass } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons -type BolleanAcnEncodingClass = { +type BooleanAcnEncodingClass = { truePattern : byte list falsePattern : byte list patternSizeInBits : int @@ -140,15 +140,15 @@ type Boolean = { cons : BoolConstraint list withcons : BoolConstraint list baseType : Boolean option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option - acnEncodingClass : BolleanAcnEncodingClass + alignment : AcnAlignment option + acnEncodingClass : BooleanAcnEncodingClass } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -166,12 +166,12 @@ type NullType = { uperMaxSizeInBits : int uperMinSizeInBits : int baseType : NullType option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : NullAcnEncodingClass } @@ -182,9 +182,9 @@ type NullType = { type StringAcnEncodingClass = | Acn_Enc_String_Ascii_FixSize of int //int = the size of the fixed ascii string - | Acn_Enc_String_Ascii_Null_Teminated of byte //byte = the null character + | Acn_Enc_String_Ascii_Null_Terminated of byte //byte = the null character | Acn_Enc_String_Ascii_External_Field_Determinant //the determinant is exists withinh acnLinks - | Acn_Enc_String_Ascii_Internal_Field_Determinant of int //int = size in bits of length determinant. This case is like uPER except that the ASCII value (8 bits) of the character is encoded and also no fragmentation + | Acn_Enc_String_Ascii_Internal_Field_Determinant of int //int = size in bits of length determinant. This case is like uPER except that the ASCII value (8 bits) of the character is encoded and also no fragmentation | Acn_Enc_String_CharIndex_FixSize of int //int = the size of the fixed string | Acn_Enc_String_CharIndex_External_Field_Determinant //external field | Acn_Enc_String_CharIndex_Internal_Field_Determinant of int //int = size in bits of length determinant : this case is almost like uPER (except of fragmentation) @@ -203,27 +203,27 @@ type StringType = { maxSize : int charSet : char array baseType : StringType option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : StringAcnEncodingClass //acnArguments : IntArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons - - + + type SizeableAcnEncodingClass = - | FixedSize of int // Fix size, size is equal to minSize which is equal to maxSize + | FixedSize of int // Fix size, size is equal to minSize which is equal to maxSize | AutoSize // like uPER but without fragmentation | ExternalField // the external field is written in the links section @@ -237,16 +237,16 @@ type OctetString = { minSize : int maxSize : int baseType : OctetString option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : SizeableAcnEncodingClass //acnArguments : IntArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -263,16 +263,16 @@ type BitString = { minSize : int maxSize : int baseType : BitString option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : SizeableAcnEncodingClass //acnArguments : IntArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -290,32 +290,32 @@ type SequenceOf = { minSize : int maxSize : int baseType : SequenceOf option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option acnEncodingClass : SizeableAcnEncodingClass //acnArguments : GenericArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons -and OptionalalityEncodingClass = +and OptionalityEncodingClass = | OptionLikeUper - | OptionExtField + | OptionExtField and Optional = { defaultValue : Asn1GenericValue option - ancEncodingClass : OptionalalityEncodingClass + ancEncodingClass : OptionalityEncodingClass } -and Asn1Optionality = +and Asn1Optionality = | AlwaysAbsent | AlwaysPresent | Optional of Optional @@ -325,7 +325,7 @@ and SeqChildInfo = { name :string chType :Asn1Type optionality :Asn1Optionality option - acnInsertetField :bool + acnInsertedField :bool comments :string list c_name : string } @@ -340,15 +340,15 @@ and Sequence = { cons : SequenceConstraint list withcons : SequenceConstraint list baseType : Sequence option - Location : SrcLoc + Location : SrcLoc //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int - alignment : AcnAligment option + alignment : AcnAlignment option //acnArguments : GenericArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -357,8 +357,8 @@ with and ChoiceAcnEncClass = - | EmbededChoiceIndexLikeUper - | EnumDeterminant + | EmbeddedChoiceIndexLikeUper + | EnumDeterminant | PresentWhenOnChildren and ChChildInfo = { @@ -366,7 +366,7 @@ and ChChildInfo = { presentWhenName :string // the name of the corresponding enum that indicates that specific child is present chType :Asn1Type comments :string list - presenseIsHandleByExtField :bool + presenceIsHandleByExtField :bool c_name : string } @@ -380,16 +380,16 @@ and Choice = { cons : ChoiceConstraint list withcons : ChoiceConstraint list baseType : Choice option - Location : SrcLoc + Location : SrcLoc choiceIDForNone : string //cast new properties acnMaxSizeInBits : int acnMinSizeInBits : int acnEncodingClass : ChoiceAcnEncClass - alignment : AcnAligment option + alignment : AcnAlignment option //acnArguments : GenericArgument list } -with +with member this.Cons = this.cons member this.WithCons = this.withcons member this.AllCons = this.cons@this.withcons @@ -438,17 +438,17 @@ with member this.baseType = match this with - | Integer t -> t.baseType |> Option.map Integer - | Real t -> t.baseType |> Option.map Real - | IA5String t -> t.baseType |> Option.map IA5String - | OctetString t -> t.baseType |> Option.map OctetString - | NullType t -> t.baseType |> Option.map NullType - | BitString t -> t.baseType |> Option.map BitString - | Boolean t -> t.baseType |> Option.map Boolean - | Enumerated t -> t.baseType |> Option.map Enumerated - | SequenceOf t -> t.baseType |> Option.map SequenceOf - | Sequence t -> t.baseType |> Option.map Sequence - | Choice t -> t.baseType |> Option.map Choice + | Integer t -> t.baseType |> Option.map Integer + | Real t -> t.baseType |> Option.map Real + | IA5String t -> t.baseType |> Option.map IA5String + | OctetString t -> t.baseType |> Option.map OctetString + | NullType t -> t.baseType |> Option.map NullType + | BitString t -> t.baseType |> Option.map BitString + | Boolean t -> t.baseType |> Option.map Boolean + | Enumerated t -> t.baseType |> Option.map Enumerated + | SequenceOf t -> t.baseType |> Option.map SequenceOf + | Sequence t -> t.baseType |> Option.map Sequence + | Choice t -> t.baseType |> Option.map Choice member this.uperMaxSizeInBits = match this with | Integer t -> t.uperMaxSizeInBits @@ -503,7 +503,7 @@ with | Sequence t -> t.acnMaxSizeInBits | Choice t -> t.acnMaxSizeInBits - member this.asn1Name = + member this.asn1Name = match this.id with | ReferenceToType((GenericFold2.MD _)::(GenericFold2.TA tasName)::[]) -> Some tasName | _ -> None @@ -549,42 +549,42 @@ let seqUPEROptionalChildren children = let seqAcnOptionalChildren children = children |> List.filter(fun c -> match c.optionality with Some (Optional _) -> true | _ -> false) let seqAcnOptionalChildrenHandledLikeuPER children= - children |> - List.filter(fun c -> - match c.optionality with - | Some (Optional o) -> + children |> + List.filter(fun c -> + match c.optionality with + | Some (Optional o) -> match o.ancEncodingClass with | OptionLikeUper -> true | OptionExtField -> false | _ -> false) -type AcnLinkKind = +type AcnLinkKind = | SizeDeterminant // points to an integer type that acts as a size determinant to a SEQUENCE OF, BIT STRINT, OCTET STRING etc | RefTypeArgument of string // string is the param name - | PresenceBool // points to a SEQEUNCE or Choice child - | PresenceInt of BigInteger // points to a SEQEUNCE or Choice child + | PresenceBool // points to a SEQUENCE or Choice child + | PresenceInt of BigInteger // points to a SEQUENCE or Choice child | PresenceStr of string - | ChoiceDeteterminant // points to Enumerated type acting as CHOICE determinant. + | ChoiceDeterminant // points to Enumerated type acting as CHOICE determinant. with - override x.ToString() = + override x.ToString() = match x with | SizeDeterminant -> "size" | RefTypeArgument argName -> sprintf "RefArg<%s>" argName | PresenceBool -> "present-when-bool" | PresenceInt vl -> sprintf "present-when-int %A" vl | PresenceStr stVal -> sprintf "present-when-str %s" stVal - | ChoiceDeteterminant -> "choice-determinant" + | ChoiceDeterminant -> "choice-determinant" type AcnLink = { decType : Asn1Type determinant : ReferenceToType linkType : AcnLinkKind } -with - override x.ToString() = +with + override x.ToString() = let decType = x.decType.id.ToString() - let determnant = x.determinant.ToString() - sprintf "%s %s %s" decType (x.linkType.ToString() ) determnant + let determinant = x.determinant.ToString() + sprintf "%s %s %s" decType (x.linkType.ToString() ) determinant type AcnParameter = { ModName : string @@ -593,11 +593,10 @@ type AcnParameter = { Asn1Type : AcnTypes.AcnAsn1Type Location : SrcLoc } -with +with member this.c_name = ToC this.Name -//type AstRoot = AstRootTemplate type AstRoot = { Files: list args:CommandLineSettings diff --git a/BackendAst/CAstAcnEncodingClasses.fs b/BackendAst/CAstAcnEncodingClasses.fs index bb8624e0f..5af2e5328 100644 --- a/BackendAst/CAstAcnEncodingClasses.fs +++ b/BackendAst/CAstAcnEncodingClasses.fs @@ -25,14 +25,14 @@ let rec GetNullEncodingValue (acnProps: AcnTypes.AcnProperty list) = | hd::_ -> Some hd.Value | [] -> None -let rec GetEndianess (acnProps: AcnTypes.AcnProperty list) = +let rec GetEndianness (acnProps: AcnTypes.AcnProperty list) = match acnProps |> List.choose(fun x -> match x with AcnTypes.Endianness(a) -> Some a | _ -> None ) with | hd::_ -> hd | [] -> AcnTypes.endianness.BigEndianness let rec isEnumEncodingValues (acnProps: AcnTypes.AcnProperty list) = - acnProps |> List.exists(fun x -> match x with AcnTypes.EncodeValues -> true | _ -> false ) + acnProps |> List.exists(fun x -> match x with AcnTypes.EncodeValues -> true | _ -> false ) let GetEncodingProperty (acnProps: AcnTypes.AcnProperty list) = match acnProps |> List.choose(fun x -> match x with AcnTypes.Encoding(a) -> Some a | _ -> None ) with @@ -53,12 +53,12 @@ let sizeToPriv (constants:AcnTypes.AcnConstant list) sizeProperty = | AcnTypes.sizeProperty.NullTerminated b -> SP_NullTerminated b let GetSizeProperty (constants:AcnTypes.AcnConstant list) (acnProps: AcnTypes.AcnProperty list) = - match acnProps |> List.choose(fun x -> match x with AcnTypes.SizeProperty(a) -> Some a | _ -> None ) with + match acnProps |> List.choose(fun x -> match x with AcnTypes.SizeProperty(a) -> Some a | _ -> None ) with | hd::_ -> (sizeToPriv constants hd ) | [] -> raise(BugErrorException "mandatory property missing") -let getAcnProps (acnTypes:Map) (typeId:ReferenceToType) = +let getAcnProps (acnTypes:Map) (typeId:ReferenceToType) = let acnKey = typeId.AcnAbsPath match acnTypes.TryFind acnKey with | None -> [] @@ -67,38 +67,38 @@ let getAcnProps (acnTypes:Map) (typeId:Refere let GetAlignment (acnProps: AcnTypes.AcnProperty list) = - match acnProps |> List.choose(fun x -> match x with AcnTypes.Aligment(al) -> Some al | _ -> None ) with + match acnProps |> List.choose(fun x -> match x with AcnTypes.Alignment(al) -> Some al | _ -> None ) with | (AcnTypes.NextByte)::_ -> Some NextByte, 8 | (AcnTypes.NextWord)::_ -> Some NextWord, 16 | (AcnTypes.NextDWord)::_ -> Some NextDWord, 32 | [] -> None, 0 -//The banner was generated by the followin url +//The banner was generated by the following url //http://patorjk.com/software/taag/#p=display&h=2&v=1&f=Banner&t=Integer (* - ### - # # # ##### ###### #### ###### ##### - # ## # # # # # # # # - # # # # # ##### # ##### # # - # # # # # # # ### # ##### - # # ## # # # # # # # - ### # # # ###### #### ###### # # + ### + # # # ##### ###### #### ###### ##### + # ## # # # # # # # # + # # # # # ##### # ##### # # + # # # # # # # ### # ##### + # # ## # # # # # # # + ### # # # ###### #### ###### # # *) let GetIntEncodingClass_private (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (aid:ReferenceToType) uperMinSizeInBits uperMaxSizeInBits isUnsigned= let acnProps = getAcnProps acnTypes aid let alignment, alignmentSize = GetAlignment acnProps - let encClass, minSizeInBits, maxSizeInBits = - // if the mandatory property size is missing => the type will be encoded like uPER - match acnProps |> List.exists(fun x -> match x with AcnTypes.SizeProperty(_) -> true | _ -> false ) with + let encClass, minSizeInBits, maxSizeInBits = + // if the mandatory property size is missing => the type will be encoded like uPER + match acnProps |> List.exists(fun x -> match x with AcnTypes.SizeProperty(_) -> true | _ -> false ) with | false -> Integer_uPER, uperMinSizeInBits, uperMaxSizeInBits - | true -> - let endianess = GetEndianess acnProps + | true -> + let endianness = GetEndianness acnProps let encProp = (GetEncodingProperty acnProps).Value let sizeProp = GetSizeProperty acn.Constants acnProps let bUINT = isUnsigned - match encProp, sizeProp, endianess with + match encProp, sizeProp, endianness with | AcnTypes.PosInt, SP_Fixed(8) , AcnTypes.BigEndianness -> PositiveInteger_ConstSize_8, 8, 8 | AcnTypes.PosInt, SP_Fixed(16), AcnTypes.BigEndianness -> PositiveInteger_ConstSize_big_endian_16, 16, 16 | AcnTypes.PosInt, SP_Fixed(16), AcnTypes.LittleEndianness -> PositiveInteger_ConstSize_little_endian_16, 16, 16 @@ -118,13 +118,13 @@ let GetIntEncodingClass_private (acn:AcnTypes.AcnAst) (acnTypes:Map TwosComplement_ConstSize_little_endian_64, 64, 64 | AcnTypes.TwosComplement, SP_Fixed(fxVal) , AcnTypes.BigEndianness -> TwosComplement_ConstSize fxVal, fxVal, fxVal | AcnTypes.TwosComplement, SP_NullTerminated _, _ -> raise(SemanticError(errLoc, "Acn properties twos-complement and null-terminated are mutually exclusive")) - | AcnTypes.Ascii, SP_Fixed(fxVal) , AcnTypes.BigEndianness -> + | AcnTypes.Ascii, SP_Fixed(fxVal) , AcnTypes.BigEndianness -> match bUINT with | true -> ASCII_UINT_ConstSize fxVal, fxVal, fxVal | false -> ASCII_ConstSize fxVal, fxVal, fxVal | AcnTypes.BCD, SP_Fixed(fxVal) , AcnTypes.BigEndianness -> BCD_ConstSize fxVal, fxVal, fxVal | AcnTypes.BCD, SP_NullTerminated b, AcnTypes.BigEndianness -> BCD_VarSize_NullTerminated b, 4, 19*4 - | AcnTypes.Ascii, SP_NullTerminated b, AcnTypes.BigEndianness -> + | AcnTypes.Ascii, SP_NullTerminated b, AcnTypes.BigEndianness -> match bUINT with | true -> ASCII_UINT_VarSize_NullTerminated b, 8, 8+8+18*8 | false -> ASCII_VarSize_NullTerminated b, 8, 8+8+18*8 @@ -142,10 +142,10 @@ let GetIntEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.Enumerated) = let acnProps = getAcnProps acnTypes a.id match isEnumEncodingValues acnProps with - | false -> + | false -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetIntEncodingClass_private acn acnTypes errLoc a.id a.uperMinSizeInBits a.uperMaxSizeInBits true EncodeIndexes encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits - | true -> + | true -> let minVal = a.items |> List.map(fun x -> x.Value) |> List.min let maxVal = a.items |> List.map(fun x -> x.Value) |> List.max let uperSizeForValues = int (GetNumberOfBitsForNonNegativeInteger(maxVal-minVal)) @@ -154,38 +154,38 @@ let GetEnumeratedEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.Real) = let acnProps = getAcnProps acnTypes a.id let alignment, alignmentSize = GetAlignment acnProps - let encClass, minSizeInBits, maxSizeInBits = - match acnProps |> List.exists(fun x -> match x with AcnTypes.Encoding(_) -> true | _ -> false ) with + let encClass, minSizeInBits, maxSizeInBits = + match acnProps |> List.exists(fun x -> match x with AcnTypes.Encoding(_) -> true | _ -> false ) with | false -> Real_uPER, a.uperMinSizeInBits, a.uperMaxSizeInBits | true -> let enc = (GetEncodingProperty acnProps).Value - let endianess = GetEndianess acnProps - match enc, endianess with + let endianness = GetEndianness acnProps + match enc, endianness with | AcnTypes.IEEE754_32, AcnTypes.BigEndianness -> Real_IEEE754_32_big_endian, 32, 32 | AcnTypes.IEEE754_64, AcnTypes.BigEndianness -> Real_IEEE754_64_big_endian, 64, 64 | AcnTypes.IEEE754_32, AcnTypes.LittleEndianness -> Real_IEEE754_32_little_endian, 32, 32 | AcnTypes.IEEE754_64, AcnTypes.LittleEndianness -> Real_IEEE754_64_little_endian, 64, 64 | _,_ -> raise(BugErrorException "Invalid combination") - encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize + encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize (* ███╗ ██╗██╗ ██╗██╗ ██╗ ████████╗██╗ ██╗██████╗ ███████╗ ████╗ ██║██║ ██║██║ ██║ ╚══██╔══╝╚██╗ ██╔╝██╔══██╗██╔════╝ -██╔██╗ ██║██║ ██║██║ ██║ ██║ ╚████╔╝ ██████╔╝█████╗ -██║╚██╗██║██║ ██║██║ ██║ ██║ ╚██╔╝ ██╔═══╝ ██╔══╝ +██╔██╗ ██║██║ ██║██║ ██║ ██║ ╚████╔╝ ██████╔╝█████╗ +██║╚██╗██║██║ ██║██║ ██║ ██║ ╚██╔╝ ██╔═══╝ ██╔══╝ ██║ ╚████║╚██████╔╝███████╗███████╗██║ ██║ ██║ ███████╗ ╚═╝ ╚═══╝ ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ *) @@ -193,57 +193,57 @@ let GetRealEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.NullType) = let acnProps = getAcnProps acnTypes a.id let alignment, alignmentSize = GetAlignment acnProps - let encClass, minSizeInBits, maxSizeInBits = + let encClass, minSizeInBits, maxSizeInBits = match GetNullEncodingValue acnProps with - | Some(s) -> + | Some(s) -> let arrBytes = bitStringValueToByteArray (s.AsLoc) |> Seq.toList {NullAcnEncodingClass.byteMask = arrBytes; patternSizeInBits = s.Length}, s.Length, s.Length | None -> {NullAcnEncodingClass.byteMask = []; patternSizeInBits = 0}, 0, 0 - encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize + encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize let GetBooleanTypeEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.Boolean) = let acnProps = getAcnProps acnTypes a.id let alignment, alignmentSize = GetAlignment acnProps - let encClass, minSizeInBits, maxSizeInBits = + let encClass, minSizeInBits, maxSizeInBits = match GetBooleanEncoding acnProps with - | AcnTypes.TrueValue(bitVal) -> + | AcnTypes.TrueValue(bitVal) -> let arrBytes = bitStringValueToByteArray bitVal |> Seq.toList - let encClass = {BolleanAcnEncodingClass.truePattern = arrBytes; falsePattern = (arrBytes |> List.map (~~~));patternSizeInBits = bitVal.Value.Length;encodingValueIsTrue = true} + let encClass = {BooleanAcnEncodingClass.truePattern = arrBytes; falsePattern = (arrBytes |> List.map (~~~));patternSizeInBits = bitVal.Value.Length;encodingValueIsTrue = true} encClass, bitVal.Value.Length, bitVal.Value.Length - | AcnTypes.FalseValue(bitVal) -> + | AcnTypes.FalseValue(bitVal) -> let arrBytes = bitStringValueToByteArray bitVal |> Seq.toList - let encClass = {BolleanAcnEncodingClass.truePattern = (arrBytes |> List.map (~~~)); falsePattern = arrBytes;patternSizeInBits = bitVal.Value.Length;encodingValueIsTrue = false} + let encClass = {BooleanAcnEncodingClass.truePattern = (arrBytes |> List.map (~~~)); falsePattern = arrBytes;patternSizeInBits = bitVal.Value.Length;encodingValueIsTrue = false} encClass, bitVal.Value.Length, bitVal.Value.Length - encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize + encClass, alignment, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize (* - ### # ####### ##### - # # # # # # ##### ##### # # # #### - # # # # # # # # # ## # # # - # # # ###### ##### # # # # # # # # - # ####### # # # ##### # # # # # ### - # # # # # # # # # # # # ## # # - ### # # ##### ##### # # # # # # #### + ### # ####### ##### + # # # # # # ##### ##### # # # #### + # # # # # # # # # ## # # # + # # # ###### ##### # # # # # # # # + # ####### # # # ##### # # # # # ### + # # # # # # # # # # # # ## # # + ### # # ##### ##### # # # # # # #### *) type PrivateSizeableEncodingClass = | PrivateFixedSize of int - | PrivateAutoSize - | PrivateExternalField + | PrivateAutoSize + | PrivateExternalField | PrivateNullTerminated of byte let getPrivateSizeableEncodingClass (acnTypes:Map) (acn:AcnTypes.AcnAst) (id:ReferenceToType) (acnParams: AcnParameter list) (us:State)= let acnProps = getAcnProps acnTypes id - match acnProps |> List.choose(fun x -> match x with AcnTypes.SizeProperty(a) -> Some a | _ -> None ) with - | hd::_ -> + match acnProps |> List.choose(fun x -> match x with AcnTypes.SizeProperty(a) -> Some a | _ -> None ) with + | hd::_ -> match hd with | AcnTypes.sizeProperty.Fixed(c) -> PrivateFixedSize (int (AcnTypes.EvaluateConstant acn.Constants c)), us | AcnTypes.sizeProperty.NullTerminated b -> PrivateNullTerminated b, us - | [] -> + | [] -> match acn.References |> Seq.tryFind(fun x -> x.TypeID = id.AcnAbsPath && x.Kind = AcnTypes.SizeDeterminant) with - | Some(r) -> PrivateExternalField, us + | Some(r) -> PrivateExternalField, us | None -> PrivateAutoSize, us let GetStringEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.StringType) (acnParams: AcnParameter list) (us:State) = @@ -264,26 +264,26 @@ let GetStringEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map 8 | false -> GetNumberOfBitsForNonNegativeInt (alphaSet.Length - 1) - let encClass, minSizeInBits, maxSizeInBits = + let encClass, minSizeInBits, maxSizeInBits = match bAsciiEncoding, bAsn1FixedSize, sizeClass with | true, true, PrivateAutoSize -> Acn_Enc_String_Ascii_FixSize asn1Max, asn1Max*charSizeInBits, asn1Max*charSizeInBits - | true, true, PrivateNullTerminated b -> + | true, true, PrivateNullTerminated b -> match allowedBytes.Contains b && (not (b=0uy && alphaSet.Length = 128))with | true -> raise(SemanticError(errLoc, "The termination-pattern defines a character which belongs to the allowed values of the ASN.1 type. Use another value in the termination-pattern or apply different constraints in the ASN.1 type.")) - | false -> Acn_Enc_String_Ascii_Null_Teminated b, (asn1Max+1)*charSizeInBits, (asn1Max+1)*charSizeInBits + | false -> Acn_Enc_String_Ascii_Null_Terminated b, (asn1Max+1)*charSizeInBits, (asn1Max+1)*charSizeInBits | true, true, PrivateFixedSize(nItems) when nItems = asn1Max -> Acn_Enc_String_Ascii_FixSize asn1Max, asn1Max*charSizeInBits, asn1Max*charSizeInBits | true, true, PrivateFixedSize(nItems) -> raise(BugErrorException(sprintf "size property value should be set to %A" asn1Max)) | true, true, PrivateExternalField -> Acn_Enc_String_Ascii_External_Field_Determinant , asn1Max*charSizeInBits, asn1Max*charSizeInBits | true, false, PrivateAutoSize -> Acn_Enc_String_Ascii_Internal_Field_Determinant lengthDeterminantSize, lengthDeterminantSize + asn1Min*charSizeInBits, lengthDeterminantSize + asn1Max*charSizeInBits - | true, false, PrivateNullTerminated b -> + | true, false, PrivateNullTerminated b -> match allowedBytes.Contains b && (not (b=0uy && alphaSet.Length = 128))with | true -> raise(SemanticError(errLoc, "The termination-pattern defines a character which belongs to the allowed values of the ASN.1 type. Use another value in the termination-pattern or apply different constraints in the ASN.1 type.")) - | false -> Acn_Enc_String_Ascii_Null_Teminated b, (asn1Max+1)*charSizeInBits, (asn1Max+1)*charSizeInBits + | false -> Acn_Enc_String_Ascii_Null_Terminated b, (asn1Max+1)*charSizeInBits, (asn1Max+1)*charSizeInBits | true, false, PrivateFixedSize(nItems) -> raise(BugErrorException(sprintf "The size constraints of the ASN.1 allows variable items (%A .. %A). Therefore, you should either remove the size property (in which case the size determinant will be encoded automatically exactly like uPER), or use a an Integer field as size determinant" asn1Min asn1Max)) | true, false, PrivateExternalField -> Acn_Enc_String_Ascii_External_Field_Determinant , asn1Max*charSizeInBits, asn1Max*charSizeInBits - | false, true, PrivateAutoSize -> Acn_Enc_String_CharIndex_FixSize asn1Max, asn1Max*charSizeInBits, asn1Max*charSizeInBits + | false, true, PrivateAutoSize -> Acn_Enc_String_CharIndex_FixSize asn1Max, asn1Max*charSizeInBits, asn1Max*charSizeInBits | false, true, PrivateNullTerminated _ -> raise(BugErrorException(sprintf "when a string type has the acn property 'size null-terminated' it must also have the acn property 'encoding ASCII'" )) | false, true, PrivateFixedSize(nItems) when nItems = asn1Max -> Acn_Enc_String_CharIndex_FixSize asn1Max, asn1Max*charSizeInBits, asn1Max*charSizeInBits | false, true, PrivateFixedSize(nItems) -> raise(BugErrorException(sprintf "size property value should be set to %A" asn1Max)) @@ -299,12 +299,12 @@ let GetStringEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (id:ReferenceToType) asn1Min asn1Max internalMinSize internalMaxSize (acnParams: AcnParameter list) (us:State) = @@ -312,7 +312,7 @@ let GetOctetBitSeqofEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map FixedSize c | PrivateFixedSize c -> @@ -323,7 +323,7 @@ let GetOctetBitSeqofEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map s*internalMinSize, s*internalMaxSize - | AutoSize -> + | AutoSize -> let det = GetNumberOfBitsForNonNegativeInt(asn1Max-asn1Min) det + asn1Min*internalMinSize, det + asn1Max*internalMaxSize | ExternalField -> asn1Min*internalMinSize, asn1Max*internalMaxSize @@ -339,12 +339,12 @@ let GetSequenceOfEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (chType: Asn1Type) (oldOptionality:BAst.Asn1Optionality option) (acnParams: AcnParameter list) (us:State) = @@ -357,52 +357,52 @@ let GetSeqChildOptionality (acn:AcnTypes.AcnAst) (acnTypes:Map None, us | Some(BAst.AlwaysAbsent) -> Some(AlwaysAbsent), us | Some(BAst.AlwaysPresent) -> Some(AlwaysPresent), us - | Some(BAst.Optional) + | Some(BAst.Optional) | Some(BAst.Default _) -> match acn.References |> Seq.tryFind(fun x -> x.TypeID = chType.id.AcnAbsPath && x.Kind = AcnTypes.PresenceBool) with | None -> Some (Optional {Optional.defaultValue = defValue; ancEncodingClass = OptionLikeUper}), us - | Some(r) -> Some (Optional {Optional.defaultValue = defValue; ancEncodingClass = OptionExtField}), us - + | Some(r) -> Some (Optional {Optional.defaultValue = defValue; ancEncodingClass = OptionExtField}), us + (* - ██████╗██╗ ██╗ ██████╗ ██╗ ██████╗███████╗ ██████╗██╗ ██╗██╗██╗ ██████╗ + ██████╗██╗ ██╗ ██████╗ ██╗ ██████╗███████╗ ██████╗██╗ ██╗██╗██╗ ██████╗ ██╔════╝██║ ██║██╔═══██╗██║██╔════╝██╔════╝ ██╔════╝██║ ██║██║██║ ██╔══██╗ ██║ ███████║██║ ██║██║██║ █████╗ ██║ ███████║██║██║ ██║ ██║ ██║ ██╔══██║██║ ██║██║██║ ██╔══╝ ██║ ██╔══██║██║██║ ██║ ██║ ╚██████╗██║ ██║╚██████╔╝██║╚██████╗███████╗ ╚██████╗██║ ██║██║███████╗██████╔╝ - ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝╚══════╝╚═════╝ + ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝╚══════╝╚═════╝ *) let getChildLinks (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (chType: Asn1Type) (acnParams: AcnParameter list) (us:State) = - let newLinks = - acn.References |> + let newLinks = + acn.References |> List.filter(fun x -> x.TypeID = chType.id.AcnAbsPath) |> - List.filter(fun r -> + List.filter(fun r -> match r.Kind with | AcnTypes.SizeDeterminant -> false | AcnTypes.RefTypeArgument _ -> false - | AcnTypes.ChoiceDeteterminant -> false + | AcnTypes.ChoiceDeterminant -> false | AcnTypes.PresenceBool -> true | AcnTypes.PresenceInt intVal -> true | AcnTypes.PresenceStr strVal -> true) - let presenseIsHandleByExtField = not newLinks.IsEmpty - presenseIsHandleByExtField , us + let presenceIsHandleByExtField = not newLinks.IsEmpty + presenceIsHandleByExtField , us let GetChoiceEncodingClass (acn:AcnTypes.AcnAst) (acnTypes:Map) errLoc (a:BAst.Choice) (children:ChChildInfo list) (acnParams: AcnParameter list) (us:State) = let acnProps = getAcnProps acnTypes a.id let alignment, alignmentSize = GetAlignment acnProps - let encClass, nus, indexSize = - match acn.References |> Seq.tryFind(fun x -> x.TypeID = a.id.AcnAbsPath && x.Kind = AcnTypes.ChoiceDeteterminant) with - | Some(r) -> - match children |> Seq.exists(fun c -> c.presenseIsHandleByExtField) with - | true -> raise(SemanticError(errLoc, "ACN property 'determinant' can not be applied when children have their own presense conditions")) + let encClass, nus, indexSize = + match acn.References |> Seq.tryFind(fun x -> x.TypeID = a.id.AcnAbsPath && x.Kind = AcnTypes.ChoiceDeterminant) with + | Some(r) -> + match children |> Seq.exists(fun c -> c.presenceIsHandleByExtField) with + | true -> raise(SemanticError(errLoc, "ACN property 'determinant' can not be applied when children have their own presence conditions")) | false -> () EnumDeterminant, us, 0 - | None -> - match children |> Seq.exists(fun c -> c.presenseIsHandleByExtField) with + | None -> + match children |> Seq.exists(fun c -> c.presenceIsHandleByExtField) with | true -> PresentWhenOnChildren, us, 0 - | false -> + | false -> let indexSize = int (GetNumberOfBitsForNonNegativeInteger(BigInteger(Seq.length children))) - EmbededChoiceIndexLikeUper, us, indexSize + EmbeddedChoiceIndexLikeUper, us, indexSize let acnMaxSizeInBits = alignmentSize + indexSize + (children |> List.map(fun c -> c.chType.acnMaxSizeInBits) |> List.sum) let acnMinSizeInBits = alignmentSize + indexSize + (children |> List.map(fun c -> c.chType.acnMinSizeInBits) |> List.sum) diff --git a/BackendAst/CAstConstruction.fs b/BackendAst/CAstConstruction.fs index 4fd90124e..eaa829501 100644 --- a/BackendAst/CAstConstruction.fs +++ b/BackendAst/CAstConstruction.fs @@ -7,67 +7,67 @@ open CAstAcnEncodingClasses let mapBTypeToCType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (acnTypes:Map) (acnParameters: AcnParameter list) (initialSate:State) = - + let getAcnParams (tid:ReferenceToType) = tid.BelongingTypeAssignment |> Option.map(fun ts -> acnParameters |> List.filter(fun x -> x.ModName = ts.moduName && x.TasName = ts.tasName)) |> Option.toList |> List.collect id - - + + BAstFold.foldAsn1Type t initialSate - (fun o newBase us -> + (fun o newBase us -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetIntEncodingClass acn acnTypes o.Location o let ret= {Integer.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; uperRange=o.uperRange; baseType = newBase; Location = o.Location; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; acnEncodingClass = encClass; alignment = alignment} ret, {us with currentTypes = (Integer ret)::us.currentTypes}) Integer - (fun o newBase us -> + (fun o newBase us -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetRealEncodingClass acn acnTypes o.Location o let ret = {Real.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; uperRange=o.uperRange; baseType = newBase; Location = o.Location; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; acnEncodingClass = encClass; alignment= alignment} ret, {us with currentTypes = (Real ret)::us.currentTypes}) Real - (fun o newBase us -> + (fun o newBase us -> let acnParams = getAcnParams o.id let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits, nus = GetStringEncodingClass acn acnTypes o.Location o acnParams us - let ret = {StringType.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; minSize = o.minSize; maxSize = o.maxSize; charSet = o.charSet; baseType = newBase; Location = o.Location; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; acnEncodingClass = encClass; alignment=alignment} + let ret = {StringType.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; minSize = o.minSize; maxSize = o.maxSize; charSet = o.charSet; baseType = newBase; Location = o.Location; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; acnEncodingClass = encClass; alignment=alignment} ret, {nus with currentTypes = (IA5String ret)::nus.currentTypes} ) IA5String - (fun o newBase us -> + (fun o newBase us -> let acnParams = getAcnParams o.id let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits, nus = GetOctetStringEncodingClass acn acnTypes o.Location o acnParams us let ret = {OctetString.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; minSize = o.minSize; maxSize = o.maxSize; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; acnEncodingClass = encClass; alignment=alignment} ret, {nus with currentTypes = (OctetString ret)::nus.currentTypes}) OctetString - (fun o newBase us -> + (fun o newBase us -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetNullTypeEncodingClass acn acnTypes o.Location o let ret = {NullType.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; acnEncodingClass = encClass; alignment = alignment} ret, {us with currentTypes = (NullType ret)::us.currentTypes}) NullType - (fun o newBase us -> + (fun o newBase us -> let acnParams = getAcnParams o.id let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits, nus = GetBitStringEncodingClass acn acnTypes o.Location o acnParams us let ret = {BitString.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; minSize = o.minSize; maxSize = o.maxSize; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; acnEncodingClass = encClass; alignment = alignment} ret, {nus with currentTypes = (BitString ret)::nus.currentTypes}) BitString - (fun o newBase us -> + (fun o newBase us -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetBooleanTypeEncodingClass acn acnTypes o.Location o let ret = {Boolean.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; acnEncodingClass = encClass; alignment = alignment} ret, {us with currentTypes = (Boolean ret)::us.currentTypes}) Boolean - (fun o newBase us -> + (fun o newBase us -> let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits = GetEnumeratedEncodingClass acn acnTypes o.Location o let ret = {Enumerated.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; userDefinedValues = o.userDefinedValues; items = o.items; cons=o.cons; withcons = o.withcons; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; enumEncodingClass = encClass; alignment = alignment} ret, {us with currentTypes = (Enumerated ret)::us.currentTypes}) Enumerated - (fun childType o newBase us -> + (fun childType o newBase us -> let acnParams = getAcnParams o.id let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits, nus = GetSequenceOfEncodingClass acn acnTypes o.Location o childType.acnMinSizeInBits childType.acnMaxSizeInBits acnParams us let ret = {SequenceOf.id = o.id; tasInfo = o.tasInfo; childType = childType; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; cons=o.cons; withcons = o.withcons; minSize = o.minSize; maxSize = o.maxSize; baseType = newBase; Location = o.Location; acnMaxSizeInBits = 0; acnMinSizeInBits = 0; acnEncodingClass = encClass; alignment = alignment} @@ -75,11 +75,11 @@ let mapBTypeToCType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac SequenceOf //sequence - (fun o newChild us -> + (fun o newChild us -> let acnParams = getAcnParams newChild.id let newOptionality, nus = GetSeqChildOptionality acn acnTypes o.Location newChild o.Optionality (acnParams: AcnParameter list) (us:State) - {SeqChildInfo.name = o.Name; chType = newChild; optionality = newOptionality; acnInsertetField = o.acnInsertetField; comments = o.Comments; c_name = ToC o.Name}, nus) - (fun children o newBase us -> + {SeqChildInfo.name = o.Name; chType = newChild; optionality = newOptionality; acnInsertedField = o.acnInsertedField; comments = o.Comments; c_name = ToC o.Name}, nus) + (fun children o newBase us -> let acnProps = getAcnProps acnTypes o.id let alignment, alignmentSize = GetAlignment acnProps let bitMaskSize = seqAcnOptionalChildrenHandledLikeuPER children |> Seq.length @@ -91,11 +91,11 @@ let mapBTypeToCType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac Sequence //Choice - (fun o newChild us -> + (fun o newChild us -> let acnParams = getAcnParams newChild.id - let presenseIsHandleByExtField, nus = getChildLinks acn acnTypes o.Location newChild acnParams us - {ChChildInfo.name = o.Name; chType = newChild; comments = o.Comments; presenseIsHandleByExtField=presenseIsHandleByExtField; presentWhenName = (ToC o.Name) + "_PRESENT"; c_name = ToC o.Name}, nus) - (fun children o newBase us -> + let presenceIsHandleByExtField, nus = getChildLinks acn acnTypes o.Location newChild acnParams us + {ChChildInfo.name = o.Name; chType = newChild; comments = o.Comments; presenceIsHandleByExtField=presenceIsHandleByExtField; presentWhenName = (ToC o.Name) + "_PRESENT"; c_name = ToC o.Name}, nus) + (fun children o newBase us -> let acnParams = getAcnParams o.id let encClass, alignment, acnMinSizeInBits, acnMaxSizeInBits, nus = GetChoiceEncodingClass acn acnTypes o.Location o children acnParams us let choiceIDForNone = ToC (o.id.AcnAbsPath.Tail.StrJoin("_").Replace("#","elem")) + "_NONE" @@ -103,7 +103,7 @@ let mapBTypeToCType (r:BAst.AstRoot) (t:BAst.Asn1Type) (acn:AcnTypes.AcnAst) (ac let ret = {Choice.id = o.id; tasInfo = o.tasInfo; uperMaxSizeInBits= o.uperMaxSizeInBits; uperMinSizeInBits=o.uperMinSizeInBits; children = children; cons=o.cons; withcons = o.withcons; baseType = newBase; Location = o.Location; choiceIDForNone = choiceIDForNone; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; acnEncodingClass = encClass; alignment = alignment} ret, {us with currentTypes = (Choice ret)::us.currentTypes}) Choice - + let foldMap = GenericFold2.foldMap @@ -112,9 +112,9 @@ let foldMap = GenericFold2.foldMap let mapAcnPathToReferenceToType (newTypeAssignments:Asn1Type list) (absPath : AcnTypes.AbsPath) = let rec createFromType (t:Asn1Type) (acnRestPath:string list) = - match acnRestPath with + match acnRestPath with | [] -> t.id - | childName::rest -> + | childName::rest -> match t with | Sequence sq -> match sq.children |> Seq.tryFind (fun x -> x.name = childName) with @@ -135,44 +135,44 @@ let mapAcnPathToReferenceToType (newTypeAssignments:Asn1Type list) (absPath : Ac match newTypeAssignments |> Seq.tryFind(fun x -> x.id = tas) with | None -> raise(BugErrorException(sprintf "invalid path %s." (absPath |> Seq.StrJoin ".") )) | Some t -> createFromType t rest - + let mapBAstToCast (r:BAst.AstRoot) (acn:AcnTypes.AcnAst) : AstRoot= let initialState = {State.currentTypes = []} let acnConstants = acn.Constants let acnParameters = acn.Parameters |> List.map(fun p -> {ModName = p.ModName;TasName = p.TasName; Name = p.Name; Asn1Type = p.Asn1Type;Location=p.Location}) let acnTypes = acn.Types |> List.map(fun t -> t.TypeID, t) |> Map.ofList - let newTypeAssignments, finalState = + let newTypeAssignments, finalState = r.TypeAssignments |> foldMap (fun cs t -> let newType, newState = mapBTypeToCType r t acn acnTypes acnParameters cs newType, {newState with currentTypes = newState.currentTypes@[newType]} - ) initialState + ) initialState let newTypes = finalState.currentTypes let newTypesMap = newTypes |> List.map(fun t -> t.id, t) |> Map.ofList - let acnLinks = + let acnLinks = acn.References |> List.map(fun l -> let decTypeId = mapAcnPathToReferenceToType newTypeAssignments l.TypeID let acnParams = acnParameters |> List.filter(fun x -> x.ModName = l.TypeID.Head && x.TasName = l.TypeID.Tail.Head) - let decType = + let decType = match newTypesMap.TryFind decTypeId with | Some t -> t | None -> raise(SemanticError (l.Location, sprintf "Invalid Reference '%s'" (l.TypeID.ToString()) )) - + let determinantId = let parentId = decTypeId.parentTypeId - let determinantId childRelPath = + let determinantId childRelPath = let determinantId = parentId |> Option.map (fun x -> x.appendLongChildId childRelPath) match determinantId with | None -> raise(SemanticError (l.Location, sprintf "Invalid Reference '%s'" (l.LongRef.ToString()) )) | Some determinantId -> determinantId - let rec determinantId2 (parentId: ReferenceToType option) (firstPartOfLongPath:string) (restPartOfLongPath:string list) = + let rec determinantId2 (parentId: ReferenceToType option) (firstPartOfLongPath:string) (restPartOfLongPath:string list) = //parentId |> Option.map (fun x -> x.appendLongChildId childRelPath) match parentId with | None -> raise(SemanticError (l.Location, sprintf "Invalid Reference '%s'" (l.LongRef.ToString()) )) - | Some parentId -> + | Some parentId -> match newTypesMap.TryFind parentId with | None -> raise(SemanticError (l.Location, sprintf "Invalid Reference '%s'" (l.LongRef.ToString()) )) | Some parSq -> @@ -180,18 +180,18 @@ let mapBAstToCast (r:BAst.AstRoot) (acn:AcnTypes.AcnAst) : AstRoot= | Sequence seq -> match seq.children |> Seq.tryFind(fun c -> c.name = firstPartOfLongPath) with | Some child -> parentId.appendLongChildId (firstPartOfLongPath::restPartOfLongPath) - | None -> + | None -> // no children found => Try my parents scope determinantId2 (seq.id.parentTypeId) firstPartOfLongPath restPartOfLongPath | _ -> raise(SemanticError (l.Location, sprintf "Invalid Reference '%s'" (l.LongRef.ToString()) )) - + match l.LongRef with | [] -> raise(SemanticError (l.Location,"Invalid Reference (empty path)" )) | fldName::[] -> match acnParams |> Seq.tryFind(fun p -> p.Name = fldName) with - | Some p -> + | Some p -> match decTypeId.BelongingTypeAssignment with | Some tasId -> tasId.id.getParamId p.Name | None -> raise(SemanticError (l.Location,"Invalid type id" )) @@ -204,7 +204,7 @@ let mapBAstToCast (r:BAst.AstRoot) (acn:AcnTypes.AcnAst) : AstRoot= | AcnTypes.PresenceBool -> {AcnLink.decType = decType; determinant = determinantId ; linkType = PresenceBool} | AcnTypes.PresenceInt intCon -> {AcnLink.decType = decType; determinant = determinantId ; linkType = PresenceInt (AcnTypes.EvaluateConstant acnConstants intCon)} | AcnTypes.PresenceStr strCon -> {AcnLink.decType = decType; determinant = determinantId ; linkType = PresenceStr strCon} - | AcnTypes.ChoiceDeteterminant -> {AcnLink.decType = decType; determinant = determinantId ; linkType = ChoiceDeteterminant}) + | AcnTypes.ChoiceDeterminant -> {AcnLink.decType = decType; determinant = determinantId ; linkType = ChoiceDeterminant}) { AstRoot.Files = r.Files diff --git a/BackendAst/Constraints.fs b/BackendAst/Constraints.fs index 46f8b6216..81fe2e866 100644 --- a/BackendAst/Constraints.fs +++ b/BackendAst/Constraints.fs @@ -39,8 +39,8 @@ with |Ada -> isvalid_a.ExpAnd e1 e2 member this.ExpAndMulti expList = match this with - |C -> isvalid_c.ExpAndMulit expList - |Ada -> isvalid_a.ExpAndMulit expList + |C -> isvalid_c.ExpAndMulti expList + |Ada -> isvalid_a.ExpAndMulti expList member this.ExpNot e = match this with |C -> isvalid_c.ExpNot e @@ -88,7 +88,7 @@ type FuncParamType = | VALUE of string | POINTER of string | FIXARRAY of string - with + with member this.toPointer (l:ProgrammingLanguage) = POINTER (this.getPointer l) member this.getPointer (l:ProgrammingLanguage) = @@ -120,7 +120,7 @@ type FuncParamType = | C, VALUE x -> "." | C, POINTER x -> "->" | C, FIXARRAY x -> "" - + member this.getStar (l:ProgrammingLanguage) = match l, this with | Ada, VALUE x -> "" @@ -131,30 +131,30 @@ type FuncParamType = | C, FIXARRAY x -> "" member this.getArrayItem (l:ProgrammingLanguage) (idx:string) (childTypeIsString: bool) = match l with - | Ada -> + | Ada -> let newPath = sprintf "%s.Data(%s)" this.p idx if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - | C -> + | C -> let newPath = sprintf "%s%sarr[%s]" this.p (this.getAcces l) idx if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) member this.getSeqChild (l:ProgrammingLanguage) (childName:string) (childTypeIsString: bool) = match l with - | Ada -> + | Ada -> let newPath = sprintf "%s.%s" this.p childName if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - | C -> + | C -> let newPath = sprintf "%s%s%s" this.p (this.getAcces l) childName if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) member this.getChChild (l:ProgrammingLanguage) (childName:string) (childTypeIsString: bool) = match l with - | Ada -> + | Ada -> let newPath = sprintf "%s.%s" this.p childName if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - | C -> + | C -> let newPath = sprintf "%s%su.%s" this.p (this.getAcces l) childName if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - + type Asn1TypeName = { @@ -162,9 +162,9 @@ type Asn1TypeName = { tasName : string } with - member this.id = + member this.id = ReferenceToType((GenericFold2.MD this.moduName)::(GenericFold2.TA this.tasName)::[]) - + and Asn1ValueName = { moduName : string @@ -173,36 +173,36 @@ and Asn1ValueName = { -and ReferenceToType = +and ReferenceToType = | ReferenceToType of GenericFold2.ScopeNode list with override this.ToString() = match this with | ReferenceToType path -> path |> Seq.StrJoin "." - member this.ToScopeNodeList = + member this.ToScopeNodeList = match this with - | ReferenceToType path -> path + | ReferenceToType path -> path member this.ModName = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path with | (GenericFold2.MD modName)::_ -> modName | _ -> raise(BugErrorException "Did not find module at the begining of the scope path") - member this.Asn1TypeName = + member this.Asn1TypeName = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path with | (GenericFold2.MD mdName)::(GenericFold2.TA tasName)::[] -> Some ({Asn1TypeName.moduName = mdName; tasName=tasName}) | _ -> None - member this.BelongingTypeAssignment = + member this.BelongingTypeAssignment = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path with | (GenericFold2.MD mdName)::(GenericFold2.TA tasName)::_ -> Some ({Asn1TypeName.moduName = mdName; tasName=tasName}) | _ -> None member this.AcnAbsPath = match this with - | ReferenceToType path -> path |> List.map (fun i -> i.StrValue) + | ReferenceToType path -> path |> List.map (fun i -> i.StrValue) member this.getSeqChildId (childName:string) = match this with | ReferenceToType path -> ReferenceToType (path@[GenericFold2.SEQ_CHILD childName]) @@ -220,31 +220,31 @@ and ReferenceToType = member this.appendLongChildId (childRelativePath:string list) = match this with - | ReferenceToType path -> - let newTail = - childRelativePath |> + | ReferenceToType path -> + let newTail = + childRelativePath |> List.map(fun s ->GenericFold2.SEQ_CHILD s) ReferenceToType (path@newTail) - member this.beginsWith (md:string) (ts:string)= + member this.beginsWith (md:string) (ts:string)= match this with | ReferenceToType((GenericFold2.MD mdName)::(GenericFold2.TA tasName)::[]) -> mdName = md && tasName = ts | _ -> false member this.lastItem = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path |> List.rev |> List.head with | GenericFold2.SEQ_CHILD name -> name | GenericFold2.CH_CHILD name -> name | _ -> raise (BugErrorException "error in lastitem") member this.parentTypeId = match this with - | ReferenceToType path -> + | ReferenceToType path -> let pathPar = path |> List.rev |> List.tail |> List.rev match pathPar with - | [] + | [] | _::[] -> None | _ -> Some (ReferenceToType pathPar) - member this.SeqeuenceOfLevel = + member this.SequenceOfLevel = match this with | ReferenceToType path -> path |> List.filter(fun n -> match n with GenericFold2.SQF -> true | _ -> false) |> Seq.length static member createFromModAndTasName (modName : string) ((tasName : string))= @@ -253,15 +253,15 @@ and ReferenceToType = //static member createFromAcnAbsPath (absPath : AcnTypes.AbsPath) = // let tas = ReferenceToType((GenericFold2.MD absPath.Head)::(GenericFold2.TA absPath.Tail.Head)::[]) // tas.appendLongChildId(absPath.Tail.Tail) - - - -type ReferenceToValue = + + + +type ReferenceToValue = | ReferenceToValue of (GenericFold2.ScopeNode list)*(GenericFold2.VarScopNode list) with member this.ModName = match this with - | ReferenceToValue (path,_) -> + | ReferenceToValue (path,_) -> match path with | (GenericFold2.MD modName)::_ -> modName | _ -> raise(BugErrorException "Did not find module at the begining of the scope path") @@ -295,8 +295,8 @@ type Asn1ValueTemplate<'v> = { id : ReferenceToValue litOrRef : LiteralOrReference refToType : ReferenceToType - - //childValue is true if the value is contained within another value (one of SEQUENCE, CHOICE, SEQUENCE OF) .e.g. + + //childValue is true if the value is contained within another value (one of SEQUENCE, CHOICE, SEQUENCE OF) .e.g. // MySeq ::= {a INTEGER, b INTEGER} //mySeqValue MySeq ::= {a 10, b 20} //In mySeqValue childValue is false, while in value a 10 is true. @@ -323,19 +323,19 @@ and NamedValue = { } and Asn1GenericValue = - | IntegerValue of IntegerValue - | RealValue of RealValue - | StringValue of StringValue - | BooleanValue of BooleanValue - | BitStringValue of BitStringValue + | IntegerValue of IntegerValue + | RealValue of RealValue + | StringValue of StringValue + | BooleanValue of BooleanValue + | BitStringValue of BitStringValue | OctetStringValue of OctetStringValue - | EnumValue of EnumValue - | SeqOfValue of SeqOfValue - | SeqValue of SeqValue - | ChValue of ChValue + | EnumValue of EnumValue + | SeqOfValue of SeqOfValue + | SeqValue of SeqValue + | ChValue of ChValue | NullValue of NullValue -with - member this.id = +with + member this.id = match this with | IntegerValue v -> v.id | RealValue v -> v.id @@ -348,7 +348,7 @@ with | SeqValue v -> v.id | ChValue v -> v.id | NullValue v -> v.id - member this.refToType = + member this.refToType = match this with | IntegerValue v -> v.refToType | RealValue v -> v.refToType @@ -362,7 +362,7 @@ with | ChValue v -> v.refToType | NullValue v -> v.refToType - member this.childValue = + member this.childValue = match this with | IntegerValue v -> v.childValue | RealValue v -> v.childValue @@ -382,7 +382,7 @@ with member this.getBackendName (l:ProgrammingLanguage) = match this.id with | ReferenceToValue (typePath,(GenericFold2.VA2 vasName)::[]) -> ToC vasName - | ReferenceToValue (typePath, vasPath) -> + | ReferenceToValue (typePath, vasPath) -> let longName = (typePath.Tail |> List.map (fun i -> i.StrValue))@ (vasPath |> List.map (fun i -> i.StrValue)) |> Seq.StrJoin "_" ToC2(longName.Replace("#","elem").L1) @@ -413,13 +413,13 @@ type AstRootTemplate<'ASN1TYPE> = { (* These constraints are interim. *) -type Asn1AnyConstraint = - | AnySingleValueContraint of Asn1GenericValue - | AnyRangeContraint of Asn1GenericValue*Asn1GenericValue*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | AnyRangeContraint_val_MAX of Asn1GenericValue*bool //min, InclusiveMin(=true) - | AnyRangeContraint_MIN_val of Asn1GenericValue*bool //max, InclusiveMax(=true) - | AnySizeContraint of Asn1AnyConstraint - | AnyAlphabetContraint of Asn1AnyConstraint +type Asn1AnyConstraint = + | AnySingleValueConstraint of Asn1GenericValue + | AnyRangeConstraint of Asn1GenericValue*Asn1GenericValue*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | AnyRangeConstraint_val_MAX of Asn1GenericValue*bool //min, InclusiveMin(=true) + | AnyRangeConstraint_MIN_val of Asn1GenericValue*bool //max, InclusiveMax(=true) + | AnySizeConstraint of Asn1AnyConstraint + | AnyAlphabetConstraint of Asn1AnyConstraint | AnyUnionConstraint of Asn1AnyConstraint*Asn1AnyConstraint*bool //left,righ, virtual constraint | AnyIntersectionConstraint of Asn1AnyConstraint*Asn1AnyConstraint | AnyAllExceptConstraint of Asn1AnyConstraint @@ -437,7 +437,7 @@ type GenericConstraint<'v> = | RootConstraint2 of GenericConstraint<'v>*GenericConstraint<'v> | SingleValueConstraint of 'v*LiteralOrReference -type RangeTypeConstraint<'v1,'v2> = +type RangeTypeConstraint<'v1,'v2> = | RangeUnionConstraint of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2>*bool //left,righ, virtual constraint | RangeIntersectionConstraint of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeAllExceptConstraint of RangeTypeConstraint<'v1,'v2> @@ -445,18 +445,18 @@ type RangeTypeConstraint<'v1,'v2> = | RangeRootConstraint of RangeTypeConstraint<'v1,'v2> | RangeRootConstraint2 of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeSingleValueConstraint of 'v2*LiteralOrReference - | RangeContraint of ('v1*LiteralOrReference) *('v1*LiteralOrReference)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | RangeContraint_val_MAX of ('v1*LiteralOrReference) *bool //min, InclusiveMin(=true) - | RangeContraint_MIN_val of ('v1*LiteralOrReference) *bool //max, InclusiveMax(=true) + | RangeConstraint of ('v1*LiteralOrReference) *('v1*LiteralOrReference)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | RangeConstraint_val_MAX of ('v1*LiteralOrReference) *bool //min, InclusiveMin(=true) + | RangeConstraint_MIN_val of ('v1*LiteralOrReference) *bool //max, InclusiveMax(=true) type IntegerTypeConstraint = RangeTypeConstraint type PosIntTypeConstraint = RangeTypeConstraint type CharTypeConstraint = RangeTypeConstraint - + type RealTypeConstraint = RangeTypeConstraint -type SizableTypeConstraint<'v> = +type SizableTypeConstraint<'v> = | SizeUnionConstraint of SizableTypeConstraint<'v>*SizableTypeConstraint<'v>*bool //left,righ, virtual constraint | SizeIntersectionConstraint of SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeAllExceptConstraint of SizableTypeConstraint<'v> @@ -464,9 +464,9 @@ type SizableTypeConstraint<'v> = | SizeRootConstraint of SizableTypeConstraint<'v> | SizeRootConstraint2 of SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeSingleValueConstraint of 'v*LiteralOrReference - | SizeContraint of PosIntTypeConstraint + | SizeConstraint of PosIntTypeConstraint -type IA5StringConstraint = +type IA5StringConstraint = | StrUnionConstraint of IA5StringConstraint*IA5StringConstraint*bool //left,righ, virtual constraint | StrIntersectionConstraint of IA5StringConstraint*IA5StringConstraint | StrAllExceptConstraint of IA5StringConstraint @@ -474,8 +474,8 @@ type IA5StringConstraint = | StrRootConstraint of IA5StringConstraint | StrRootConstraint2 of IA5StringConstraint*IA5StringConstraint | StrSingleValueConstraint of string*LiteralOrReference - | StrSizeContraint of PosIntTypeConstraint - | AlphabetContraint of CharTypeConstraint + | StrSizeConstraint of PosIntTypeConstraint + | AlphabetConstraint of CharTypeConstraint type OctetStringConstraint = SizableTypeConstraint type BitStringConstraint = SizableTypeConstraint @@ -488,30 +488,30 @@ type SequenceConstraint = GenericConstraint type ChoiceConstraint = GenericConstraint -let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - (c:GenericConstraint<'v>) +let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + (c:GenericConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:GenericConstraint<'v>) (s0:'UserState) = match c with - | UnionConstraint(c1,c2,b) -> + | UnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | IntersectionConstraint(c1,c2) -> + | IntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | AllExceptConstraint(c1) -> + | AllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | ExceptConstraint(c1,c2) -> + | ExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | RootConstraint(c1) -> + | RootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | RootConstraint2(c1,c2) -> + | RootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 @@ -519,175 +519,175 @@ let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc ro loopRecursiveConstraint c s -let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc rangeFunc range_val_max_func range_min_val_func - (c:RangeTypeConstraint<'v,'vr>) + (c:RangeTypeConstraint<'v,'vr>) (s:'UserState) = let rec loopRecursiveConstraint (c:RangeTypeConstraint<'v,'vr>) (s0:'UserState) = match c with - | RangeUnionConstraint(c1,c2,b) -> + | RangeUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | RangeIntersectionConstraint(c1,c2) -> + | RangeIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | RangeAllExceptConstraint(c1) -> + | RangeAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | RangeExceptConstraint(c1,c2) -> + | RangeExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | RangeRootConstraint(c1) -> + | RangeRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | RangeRootConstraint2(c1,c2) -> + | RangeRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | RangeSingleValueConstraint (v, rv) -> singleValueFunc v rv s0 - | RangeContraint((v1,rv1), (v2,rv2), b1,b2) -> rangeFunc v1 v2 b1 b2 s - | RangeContraint_val_MAX ((v,rv), b) -> range_val_max_func v b s - | RangeContraint_MIN_val ((v,rv), b) -> range_min_val_func v b s + | RangeConstraint((v1,rv1), (v2,rv2), b1,b2) -> rangeFunc v1 v2 b1 b2 s + | RangeConstraint_val_MAX ((v,rv), b) -> range_val_max_func v b s + | RangeConstraint_MIN_val ((v,rv), b) -> range_min_val_func v b s loopRecursiveConstraint c s -let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc +let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func - (c:SizableTypeConstraint<'v>) + (c:SizableTypeConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SizableTypeConstraint<'v>) (s0:'UserState) = match c with - | SizeUnionConstraint(c1,c2,b) -> + | SizeUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | SizeIntersectionConstraint(c1,c2) -> + | SizeIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | SizeAllExceptConstraint(c1) -> + | SizeAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | SizeExceptConstraint(c1,c2) -> + | SizeExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | SizeRootConstraint(c1) -> + | SizeRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | SizeRootConstraint2(c1,c2) -> + | SizeRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | SizeSingleValueConstraint (v, rv) -> singleValueFunc v rv s0 - | SizeContraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s + | SizeConstraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s loopRecursiveConstraint c s -let foldSizableTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldSizableTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc foldRangeTypeConstraint - (c:SizableTypeConstraint<'v>) + (c:SizableTypeConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SizableTypeConstraint<'v>) (s0:'UserState) = match c with - | SizeUnionConstraint(c1,c2,b) -> + | SizeUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | SizeIntersectionConstraint(c1,c2) -> + | SizeIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | SizeAllExceptConstraint(c1) -> + | SizeAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | SizeExceptConstraint(c1,c2) -> + | SizeExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | SizeRootConstraint(c1) -> + | SizeRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | SizeRootConstraint2(c1,c2) -> + | SizeRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | SizeSingleValueConstraint (v, rv) -> singleValueFunc v rv s0 - | SizeContraint intCon -> foldRangeTypeConstraint intCon s0 + | SizeConstraint intCon -> foldRangeTypeConstraint intCon s0 loopRecursiveConstraint c s -let foldStringTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldStringTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func - aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func - (c:IA5StringConstraint) + aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func + (c:IA5StringConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:IA5StringConstraint) (s0:'UserState) = match c with - | StrUnionConstraint(c1,c2,b) -> + | StrUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | StrIntersectionConstraint(c1,c2) -> + | StrIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | StrAllExceptConstraint(c1) -> + | StrAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | StrExceptConstraint(c1,c2) -> + | StrExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | StrRootConstraint(c1) -> + | StrRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | StrRootConstraint2(c1,c2) -> + | StrRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | StrSingleValueConstraint (v, rv) -> singleValueFunc v rv s0 - | StrSizeContraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s - | AlphabetContraint alphaCon -> foldRangeTypeConstraint aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func alphaCon s + | StrSizeConstraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s + | AlphabetConstraint alphaCon -> foldRangeTypeConstraint aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func alphaCon s loopRecursiveConstraint c s -let foldStringTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldStringTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc foldRangeSizeConstraint foldRangeAlphaConstraint - (c:IA5StringConstraint) + (c:IA5StringConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:IA5StringConstraint) (s0:'UserState) = match c with - | StrUnionConstraint(c1,c2,b) -> + | StrUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | StrIntersectionConstraint(c1,c2) -> + | StrIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | StrAllExceptConstraint(c1) -> + | StrAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | StrExceptConstraint(c1,c2) -> + | StrExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | StrRootConstraint(c1) -> + | StrRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | StrRootConstraint2(c1,c2) -> + | StrRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | StrSingleValueConstraint (v, rv) -> singleValueFunc v rv s0 - | StrSizeContraint intCon -> foldRangeSizeConstraint intCon s - | AlphabetContraint alphaCon -> foldRangeAlphaConstraint alphaCon s + | StrSizeConstraint intCon -> foldRangeSizeConstraint intCon s + | AlphabetConstraint alphaCon -> foldRangeAlphaConstraint alphaCon s loopRecursiveConstraint c s - -// Calcualate uPER range + +// Calculate uPER range diff --git a/BackendAst/ConstraintsMapping.fs b/BackendAst/ConstraintsMapping.fs index acc05d8b6..ad48cb35c 100644 --- a/BackendAst/ConstraintsMapping.fs +++ b/BackendAst/ConstraintsMapping.fs @@ -6,33 +6,33 @@ open FsUtils -let foldBConstraint - singleValueContraintFunc - rangeContraintFunc - rangeContraint_val_MAXFunc - rangeContraint_MIN_valFunc - sizeContraintFunc - alphabetContraintFunc - unionConstraintFunc +let foldBConstraint + singleValueConstraintFunc + rangeConstraintFunc + rangeConstraint_val_MAXFunc + rangeConstraint_MIN_valFunc + sizeConstraintFunc + alphabetConstraintFunc + unionConstraintFunc intersectionConstraintFunc - allExceptConstraintFunc - exceptConstraintFunc - rootConstraintFunc - rootConstraint2Func + allExceptConstraintFunc + exceptConstraintFunc + rootConstraintFunc + rootConstraint2Func (c:Asn1AnyConstraint) = match c with - | AnySingleValueContraint rv -> singleValueContraintFunc rv - | AnyRangeContraint (rv1,rv2,b1,b2) -> rangeContraintFunc rv1 rv2 b1 b2 - | AnyRangeContraint_val_MAX (rv,b) -> rangeContraint_val_MAXFunc rv b - | AnyRangeContraint_MIN_val (rv,b) -> rangeContraint_MIN_valFunc rv b - | AnySizeContraint c -> sizeContraintFunc c - | AnyAlphabetContraint c -> alphabetContraintFunc c - | AnyUnionConstraint (c1,c2,b) -> unionConstraintFunc c1 c2 b - | AnyIntersectionConstraint (c1,c2) -> intersectionConstraintFunc c1 c2 - | AnyAllExceptConstraint c -> allExceptConstraintFunc c - | AnyExceptConstraint (c1,c2) -> exceptConstraintFunc c1 c2 - | AnyRootConstraint c1 -> rootConstraintFunc c1 - | AnyRootConstraint2 (c1,c2) -> rootConstraint2Func c1 c2 + | AnySingleValueConstraint rv -> singleValueConstraintFunc rv + | AnyRangeConstraint (rv1,rv2,b1,b2) -> rangeConstraintFunc rv1 rv2 b1 b2 + | AnyRangeConstraint_val_MAX (rv,b) -> rangeConstraint_val_MAXFunc rv b + | AnyRangeConstraint_MIN_val (rv,b) -> rangeConstraint_MIN_valFunc rv b + | AnySizeConstraint c -> sizeConstraintFunc c + | AnyAlphabetConstraint c -> alphabetConstraintFunc c + | AnyUnionConstraint (c1,c2,b) -> unionConstraintFunc c1 c2 b + | AnyIntersectionConstraint (c1,c2) -> intersectionConstraintFunc c1 c2 + | AnyAllExceptConstraint c -> allExceptConstraintFunc c + | AnyExceptConstraint (c1,c2) -> exceptConstraintFunc c1 c2 + | AnyRootConstraint c1 -> rootConstraintFunc c1 + | AnyRootConstraint2 (c1,c2) -> rootConstraint2Func c1 c2 @@ -100,143 +100,143 @@ let chValueGetter (v:Asn1GenericValue) = let rec getRecursiveTypeConstraint valueGetter (c:Asn1AnyConstraint) = foldBConstraint - (fun rv -> SingleValueConstraint (valueGetter rv )) + (fun rv -> SingleValueConstraint (valueGetter rv )) (fun rv1 rv2 b1 b2 -> raise(BugErrorException "range constraint is not expected here")) (fun rv b -> raise(BugErrorException "range constraint is not expected here")) (fun rv b -> raise(BugErrorException "range constraint is not expected here")) - (fun c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun c1 c2 b -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - UnionConstraint (c1,c2,b)) - (fun c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - IntersectionConstraint (c1,c2)) - (fun c -> - let c = getRecursiveTypeConstraint valueGetter c - AllExceptConstraint c) - (fun c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - ExceptConstraint (c1,c2)) - (fun c -> - let c = getRecursiveTypeConstraint valueGetter c - RootConstraint c) - (fun c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - RootConstraint2 (c1,c2)) + (fun c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun c1 c2 b -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + UnionConstraint (c1,c2,b)) + (fun c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + IntersectionConstraint (c1,c2)) + (fun c -> + let c = getRecursiveTypeConstraint valueGetter c + AllExceptConstraint c) + (fun c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + ExceptConstraint (c1,c2)) + (fun c -> + let c = getRecursiveTypeConstraint valueGetter c + RootConstraint c) + (fun c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + RootConstraint2 (c1,c2)) c let rec getRangeTypeConstraint valueGetter valueGetter2 (c:Asn1AnyConstraint) = - foldBConstraint - (fun rv -> RangeSingleValueConstraint (valueGetter2 rv )) - (fun rv1 rv2 b1 b2 -> RangeContraint (valueGetter rv1 ,valueGetter rv2, b1,b2) ) - (fun rv b -> RangeContraint_val_MAX (valueGetter rv, b)) - (fun rv b -> RangeContraint_MIN_val (valueGetter rv, b)) - (fun c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun c1 c2 b -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeUnionConstraint (c1,c2,b)) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeIntersectionConstraint (c1,c2)) - (fun c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c - RangeAllExceptConstraint c) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + foldBConstraint + (fun rv -> RangeSingleValueConstraint (valueGetter2 rv )) + (fun rv1 rv2 b1 b2 -> RangeConstraint (valueGetter rv1 ,valueGetter rv2, b1,b2) ) + (fun rv b -> RangeConstraint_val_MAX (valueGetter rv, b)) + (fun rv b -> RangeConstraint_MIN_val (valueGetter rv, b)) + (fun c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun c1 c2 b -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeUnionConstraint (c1,c2,b)) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeIntersectionConstraint (c1,c2)) + (fun c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c + RangeAllExceptConstraint c) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 RangeExceptConstraint (c1,c2)) - (fun c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c + (fun c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c RangeRootConstraint c) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeRootConstraint2 (c1,c2)) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeRootConstraint2 (c1,c2)) c let rec getSizeTypeConstraint valueGetter (c:Asn1AnyConstraint) = - foldBConstraint - (fun rv -> SizeSingleValueConstraint (valueGetter rv)) + foldBConstraint + (fun rv -> SizeSingleValueConstraint (valueGetter rv)) (fun rv1 rv2 b1 b2 -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) - (fun c -> + (fun c -> let posIntCon = getRangeTypeConstraint posIntValGetter posIntValGetter c - SizeContraint posIntCon) - (fun c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun c1 c2 b -> + SizeConstraint posIntCon) + (fun c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun c1 c2 b -> let c1 = getSizeTypeConstraint valueGetter c1 - let c2 = getSizeTypeConstraint valueGetter c2 - SizeUnionConstraint (c1,c2,b)) - (fun c1 c2 -> + let c2 = getSizeTypeConstraint valueGetter c2 + SizeUnionConstraint (c1,c2,b)) + (fun c1 c2 -> let c1 = getSizeTypeConstraint valueGetter c1 let c2 = getSizeTypeConstraint valueGetter c2 - SizeIntersectionConstraint (c1,c2)) - (fun c -> - let c = getSizeTypeConstraint valueGetter c - SizeAllExceptConstraint c) - (fun c1 c2 -> + SizeIntersectionConstraint (c1,c2)) + (fun c -> + let c = getSizeTypeConstraint valueGetter c + SizeAllExceptConstraint c) + (fun c1 c2 -> let c1 = getSizeTypeConstraint valueGetter c1 let c2 = getSizeTypeConstraint valueGetter c2 SizeExceptConstraint (c1,c2)) - (fun c -> - let c = getSizeTypeConstraint valueGetter c + (fun c -> + let c = getSizeTypeConstraint valueGetter c SizeRootConstraint c) - (fun c1 c2 -> + (fun c1 c2 -> let c1 = getSizeTypeConstraint valueGetter c1 let c2 = getSizeTypeConstraint valueGetter c2 - SizeRootConstraint2 (c1,c2)) + SizeRootConstraint2 (c1,c2)) c let rec getStringTypeConstraint valueGetter (c:Asn1AnyConstraint) = - foldBConstraint - (fun rv -> StrSingleValueConstraint (valueGetter rv)) + foldBConstraint + (fun rv -> StrSingleValueConstraint (valueGetter rv)) (fun rv1 rv2 b1 b2 -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) - (fun c -> + (fun c -> let posIntCon = getRangeTypeConstraint posIntValGetter posIntValGetter c - StrSizeContraint posIntCon) - (fun c -> + StrSizeConstraint posIntCon) + (fun c -> let charCons = getRangeTypeConstraint charGetter strGetter c - AlphabetContraint charCons) - (fun c1 c2 b -> + AlphabetConstraint charCons) + (fun c1 c2 b -> let c1 = getStringTypeConstraint valueGetter c1 let c2 = getStringTypeConstraint valueGetter c2 - StrUnionConstraint (c1,c2,b)) - (fun c1 c2 -> + StrUnionConstraint (c1,c2,b)) + (fun c1 c2 -> let c1 = getStringTypeConstraint valueGetter c1 let c2 = getStringTypeConstraint valueGetter c2 - StrIntersectionConstraint (c1,c2)) - (fun c -> + StrIntersectionConstraint (c1,c2)) + (fun c -> let c = getStringTypeConstraint valueGetter c - StrAllExceptConstraint c) - (fun c1 c2 -> + StrAllExceptConstraint c) + (fun c1 c2 -> let c1 = getStringTypeConstraint valueGetter c1 let c2 = getStringTypeConstraint valueGetter c2 StrExceptConstraint (c1,c2)) - (fun c -> + (fun c -> let c = getStringTypeConstraint valueGetter c StrRootConstraint c) - (fun c1 c2 -> + (fun c1 c2 -> let c1 = getStringTypeConstraint valueGetter c1 let c2 = getStringTypeConstraint valueGetter c2 - StrRootConstraint2 (c1,c2)) + StrRootConstraint2 (c1,c2)) c -let getIntegerTypeConstraint = getRangeTypeConstraint getValueAsBigInteger getValueAsBigInteger +let getIntegerTypeConstraint = getRangeTypeConstraint getValueAsBigInteger getValueAsBigInteger let getRealTypeConstraint = getRangeTypeConstraint getValueAsDouble getValueAsDouble let getIA5StringConstraint = getStringTypeConstraint strGetter let getOctetStringConstraint = getSizeTypeConstraint octGetter diff --git a/BackendAst/CustomStgExport.fs b/BackendAst/CustomStgExport.fs index 4ad9abfd5..fd9e16f08 100644 --- a/BackendAst/CustomStgExport.fs +++ b/BackendAst/CustomStgExport.fs @@ -42,16 +42,16 @@ let internal PrintCustomAsn1Value_aux (bPrintAsAttr:bool) (v: Asn1Value) stgFile match v.kind with |IntegerValue(v) -> gen.Print_IntegerValue v stgFileName |RealValue(v) -> gen.Print_RealValue v stgFileName - |StringValue(v,_) -> -// match bPrintAsAttr with -// | true -> + |StringValue(v,_) -> +// match bPrintAsAttr with +// | true -> // //printfn "%s\n" v // let retVal = v.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'") // //printfn "%s\n" retVal // match bChildVal with // | true -> """ + retVal + """ // | false -> retVal -// | false -> +// | false -> let strVal = CommonTypes.StringValue2String v gen.Print_StringValue strVal stgFileName |EnumValue enmv -> gen.Print_RefValue enmv stgFileName //gen.Print_EnmValueValue enmv stgFileName @@ -64,12 +64,13 @@ let internal PrintCustomAsn1Value_aux (bPrintAsAttr:bool) (v: Asn1Value) stgFile |ChValue(nmv) -> gen.Print_ChValue nmv.name (PrintValue true nmv.Value) stgFileName |NullValue _ -> gen.Print_NullValue() stgFileName |ObjOrRelObjIdValue v -> gen.Print_ObjectIdentifierValue((v.Values |> List.map fst)) stgFileName + |other -> raise (BugErrorException $"Unsupported kind for PrintValue {other}") PrintValue false v let PrintCustomAsn1Value (vas: ValueAssignment) stgFileName = PrintCustomAsn1Value_aux false vas.Value stgFileName -//let rec printAsn1ValueAsXmlAttribute (v: Asn1Value) stgFileName = +//let rec printAsn1ValueAsXmlAttribute (v: Asn1Value) stgFileName = // PrintCustomAsn1Value_aux true v stgFileName let PrintContract (r:AstRoot) (stgFileName:string) (asn1Name:string) (backendName:string) (t:Asn1Type)= @@ -85,12 +86,13 @@ let PrintContract (r:AstRoot) (stgFileName:string) (asn1Name:string) (backendNam | AcnChild c -> null gen.TypePatternSequence asn1Name backendName (seqInfo.children |> Seq.map emitChild) stgFileName | ReferenceType(_) -> null + | other -> raise (BugErrorException $"Unsupported kind for PrintPattern {other}") let rec PrintExpression (t:Asn1Type) (pattern:string) = match t.Kind with | Integer intInfo -> handTypeWithMinMax pattern intInfo.baseInfo.uperRange gen.ContractExprMinMax stgFileName | Real realInfo -> handTypeWithMinMax_real pattern realInfo.baseInfo.uperRange gen.ContractExprMinMax stgFileName | OctetString info -> handTypeWithMinMax pattern (CommonTypes.Concrete (info.baseInfo.minSize, info.baseInfo.maxSize)) gen.ContractExprSize stgFileName - | IA5String info -> handTypeWithMinMax pattern (CommonTypes.Concrete (info.baseInfo.minSize, info.baseInfo.maxSize)) gen.ContractExprSize stgFileName + | IA5String info -> handTypeWithMinMax pattern (CommonTypes.Concrete (info.baseInfo.minSize, info.baseInfo.maxSize)) gen.ContractExprSize stgFileName | BitString info -> handTypeWithMinMax pattern (CommonTypes.Concrete (info.baseInfo.minSize, info.baseInfo.maxSize)) gen.ContractExprSize stgFileName | ObjectIdentifier _ | Boolean _ @@ -108,6 +110,7 @@ let PrintContract (r:AstRoot) (stgFileName:string) (asn1Name:string) (backendNam let sMin, sMax = info.baseInfo.minSize.ToString(), info.baseInfo.maxSize.ToString() gen.ContractExprSize pattern sMin sMax (sMin = sMax) stgFileName | ReferenceType(_) -> null + | other -> raise (BugErrorException $"Unsupported kind for PrintExpression {other}") let pattern = PrintPattern () let expression = PrintExpression t pattern gen.Contract pattern (if String.length(expression) > 0 then expression else null) stgFileName @@ -115,13 +118,13 @@ let PrintContract (r:AstRoot) (stgFileName:string) (asn1Name:string) (backendNam let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRecursion:bool) (t:Asn1Type) : string = let printChildTypeAsReferencedType (t:Asn1Type) = - match t.typeDefintionOrReference, t.inheritInfo, t.Kind with - | ReferenceToExistingDefinition _, None, Integer _ - | ReferenceToExistingDefinition _, None, Real _ - | ReferenceToExistingDefinition _, None, Boolean _ + match t.typeDefinitionOrReference, t.inheritInfo, t.Kind with + | ReferenceToExistingDefinition _, None, Integer _ + | ReferenceToExistingDefinition _, None, Real _ + | ReferenceToExistingDefinition _, None, Boolean _ | ReferenceToExistingDefinition _, None, NullType _ -> PrintType r f stgFileName modName deepRecursion t | _ -> - let uperRange = + let uperRange = match (t.ActualType).Kind with | Integer i -> Some (GetMinMax i.baseInfo.uperRange) | BitString i -> Some (i.baseInfo.minSize.ToString(), i.baseInfo.maxSize.ToString()) @@ -129,25 +132,25 @@ let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRec | IA5String i -> Some (i.baseInfo.minSize.ToString(), i.baseInfo.maxSize.ToString()) | SequenceOf i -> Some (i.baseInfo.minSize.ToString(), i.baseInfo.maxSize.ToString()) | Real i -> Some (GetMinMax i.baseInfo.uperRange) - | Boolean _ | NullType _ | Choice _ | Enumerated _ | Sequence _ | ReferenceType _ | ObjectIdentifier _ -> None + | Boolean _ | NullType _ | Choice _ | Enumerated _ | Sequence _ | ReferenceType _ | ObjectIdentifier _ | TimeType _ -> None let sModName= - match t.typeDefintionOrReference with - | ReferenceToExistingDefinition refEx -> - match refEx.programUnit with + match t.typeDefinitionOrReference with + | ReferenceToExistingDefinition refEx -> + match refEx.programUnit with | Some x -> x.Replace("_","-") | None -> null | TypeDefinition td -> null - let asn1Name = t.typeDefintionOrReference.getAsn1Name r.args.TypePrefix + let asn1Name = t.typeDefinitionOrReference.getAsn1Name r.args.TypePrefix let sCModName = if sModName <> null then (ToC sModName) else null let sResolvedType = None - let refTypeContent = + let refTypeContent = match uperRange with | Some(sMin, sMax) -> gen.RefTypeMinMax sMin sMax asn1Name sModName (ToC asn1Name) (*typedefName*) sCModName (sMin = sMax) sResolvedType stgFileName | None -> gen.RefType asn1Name sModName (ToC asn1Name) (*typedefName*) sCModName sResolvedType stgFileName - let cName = t.FT_TypeDefintion.[C].typeName - let scalaName = t.FT_TypeDefintion.[Scala].typeName - let adaName = t.FT_TypeDefintion.[Ada].typeName + let cName = t.FT_TypeDefinition.[C].typeName + let scalaName = t.FT_TypeDefinition.[Scala].typeName + let adaName = t.FT_TypeDefinition.[Ada].typeName gen.TypeGeneric (BigInteger t.Location.srcLine) (BigInteger t.Location.charPos) f.FileName refTypeContent (t.acnDecFunction.IsSome && t.acnDecFunction.Value.funcName.IsSome) cName scalaName adaName stgFileName let PrintTypeAux (t:Asn1Type) = @@ -172,13 +175,13 @@ let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRec match deepRecursion with |true -> PrintType r f stgFileName modName deepRecursion c.chType |false -> printChildTypeAsReferencedType c.chType - gen.ChoiceChild c.Name.Value (ToC (c.getBackendName C)) (ToC (c.getBackendName Scala)) (ToC (c.getBackendName Ada)) (BigInteger c.Name.Location.srcLine) (BigInteger c.Name.Location.charPos) childTypeExp (c.presentWhenName (Some c.chType.typeDefintionOrReference) C) bRemovedChild stgFileName + gen.ChoiceChild c.Name.Value (ToC (c.getBackendName C)) (ToC (c.getBackendName Scala)) (ToC (c.getBackendName Ada)) (BigInteger c.Name.Location.srcLine) (BigInteger c.Name.Location.charPos) childTypeExp (c.presentWhenName (Some c.chType.typeDefinitionOrReference) C) bRemovedChild stgFileName gen.ChoiceType (chInfo.children |> Seq.map emitChild) stgFileName | Sequence(seqInfo) -> let emitChild (c:SeqChildInfo) = match c with - | Asn1Child c -> + | Asn1Child c -> let childTypeExp = match deepRecursion with |true -> PrintType r f stgFileName modName deepRecursion c.Type @@ -190,12 +193,12 @@ let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRec | Some (Asn1AcnAst.AlwaysPresent) -> true, false | Some (Asn1AcnAst.Optional _) -> false, false match c.Optionality with - | Some(Asn1AcnAst.Optional(optVal)) when optVal.defaultValue.IsSome -> + | Some(Asn1AcnAst.Optional(optVal)) when optVal.defaultValue.IsSome -> let defValueAsAsn1Value = DAstAsn1.printAsn1Value optVal.defaultValue.Value let defValueAsAsn1Value = match defValueAsAsn1Value.StartsWith("\"") && defValueAsAsn1Value.EndsWith("\"") with | false -> defValueAsAsn1Value - | true -> + | true -> defValueAsAsn1Value.Substring(1,defValueAsAsn1Value.Length-2) gen.SequenceChild c.Name.Value (ToC (c.getBackendName C)) (ToC (c.getBackendName Scala)) (ToC (c.getBackendName Ada)) true defValueAsAsn1Value (BigInteger c.Name.Location.srcLine) (BigInteger c.Name.Location.charPos) childTypeExp bAlwaysPresent bAlwaysAbsent stgFileName //gen.SequenceChild c.Name.Value (ToC c.Name.Value) true (printAsn1ValueAsXmlAttribute (DAstUtilFunctions.mapValue optVal.defaultValue.Value) stgFileName) (BigInteger c.Name.Location.srcLine) (BigInteger c.Name.Location.charPos) childTypeExp stgFileName @@ -215,7 +218,7 @@ let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRec let sMin, sMax = info.baseInfo.minSize.ToString(), info.baseInfo.maxSize.ToString() gen.SequenceOfType sMin sMax childTypeExp (sMin=sMax) stgFileName | ReferenceType info -> - let uperRange = + let uperRange = match (t.ActualType).Kind with | Integer i -> Some (GetMinMax i.baseInfo.uperRange) | BitString i -> Some (i.baseInfo.minSize.ToString(), i.baseInfo.maxSize.ToString()) @@ -230,26 +233,27 @@ let rec PrintType (r:AstRoot) (f:Asn1File) (stgFileName:string) modName (deepRec match uperRange with | Some(sMin, sMax) -> gen.RefTypeMinMax sMin sMax info.baseInfo.tasName.Value sModName (ToC info.baseInfo.tasName.Value) sCModName (sMin=sMax) (Some resolvedType) stgFileName | None -> gen.RefType info.baseInfo.tasName.Value sModName (ToC info.baseInfo.tasName.Value) sCModName (Some resolvedType) stgFileName - let cName = t.FT_TypeDefintion.[C].typeName - let scalaName = t.FT_TypeDefintion.[Scala].typeName - let adaName = t.FT_TypeDefintion.[Ada].typeName - gen.TypeGeneric (BigInteger t.Location.srcLine) (BigInteger t.Location.charPos) f.FileName (PrintTypeAux t) (t.acnDecFunction.IsSome && t.acnDecFunction.Value.funcName.IsSome) cName scalaName adaName stgFileName + | other -> raise (BugErrorException $"Unsupported kind for PrintTypeAux {other}") + let cName = t.FT_TypeDefinition.[C].typeName + let scalaName = t.FT_TypeDefinition.[Scala].typeName + let adaName = t.FT_TypeDefinition.[Ada].typeName + gen.TypeGeneric (BigInteger t.Location.srcLine) (BigInteger t.Location.charPos) f.FileName (PrintTypeAux t) (t.acnDecFunction.IsSome && t.acnDecFunction.Value.funcName.IsSome) cName scalaName adaName stgFileName let exportFile (r:AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (stgFileName:string) (outFileName:string) = - let AssigOp (t: Asn1Type) = + let AssignOp (t: Asn1Type) = match t.Kind with - | Sequence(_) -> gen.AssigOpSpecialType () stgFileName - | _ -> gen.AssigOpNormalType () stgFileName + | Sequence(_) -> gen.AssignOpSpecialType () stgFileName + | _ -> gen.AssignOpNormalType () stgFileName - let typesMap = - r.Files |> + let typesMap = + r.Files |> List.collect(fun f -> f.Modules) |> List.collect(fun m -> - m.TypeAssignments |> List.map(fun tas -> tas.AsTypeAssignmentInfo m.Name.Value, tas) + m.TypeAssignments |> List.map(fun tas -> tas.AsTypeAssignmentInfo m.Name.Value, tas) ) |> Map.ofList let PrintVas (f:Asn1File) (vas: ValueAssignment) modName = @@ -261,13 +265,13 @@ let exportFile (r:AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (stgFi | false -> GetMySelfAndChildren t let PrintTas (f:Asn1File) (tas:TypeAssignment) modName = let innerTypeDef = - getInnerTypes tas.Type |> - List.choose(fun t -> - match t.typeDefintionOrReference with + getInnerTypes tas.Type |> + List.choose(fun t -> + match t.typeDefinitionOrReference with | ReferenceToExistingDefinition _ -> None - | TypeDefinition td -> - let asn1Name = t.typeDefintionOrReference.getAsn1Name r.args.TypePrefix - let ret = gen.TasXml asn1Name t.Location.srcLine.AsBigInt t.Location.charPos.AsBigInt (PrintType r f stgFileName modName deepRecursion t ) (ToC asn1Name) (*td.typedefName*) (AssigOp t) (PrintContract r stgFileName asn1Name td.typedefName t) (t.id <> tas.Type.id) stgFileName + | TypeDefinition td -> + let asn1Name = t.typeDefinitionOrReference.getAsn1Name r.args.TypePrefix + let ret = gen.TasXml asn1Name t.Location.srcLine.AsBigInt t.Location.charPos.AsBigInt (PrintType r f stgFileName modName deepRecursion t ) (ToC asn1Name) (*td.typedefName*) (AssignOp t) (PrintContract r stgFileName asn1Name td.typedefName t) (t.id <> tas.Type.id) stgFileName Some ret) |> Seq.StrJoin "\n" innerTypeDef let PrintModule (f:Asn1File) (m:Asn1Module) = @@ -275,23 +279,23 @@ let exportFile (r:AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (stgFi gen.ImportedMod im.Name.Value (ToC im.Name.Value) (im.Types |> Seq.map(fun x -> x.Value)) (im.Values |> Seq.map(fun x -> x.Value)) stgFileName let exportedTypes = m.ExportedTypes |> - List.collect(fun n -> + List.collect(fun n -> match m.TypeAssignments |> Seq.tryFind(fun z -> z.Name.Value = n) with | Some tas -> getInnerTypes tas.Type |> - List.choose(fun t -> - match t.typeDefintionOrReference with + List.choose(fun t -> + match t.typeDefinitionOrReference with | ReferenceToExistingDefinition _ -> None - | TypeDefinition td -> Some (t.typeDefintionOrReference.getAsn1Name r.args.TypePrefix)) + | TypeDefinition td -> Some (t.typeDefinitionOrReference.getAsn1Name r.args.TypePrefix)) | None -> []) - - let moduTypes = m.TypeAssignments |> List.map(fun x -> x.Type) - let importedTypes = + + let moduleTypes = m.TypeAssignments |> List.map(fun x -> x.Type) + let importedTypes = m.Imports |> - Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value})) |> - Seq.distinct |> Seq.toList - let sortedTypes = DAstProgramUnit.sortTypes moduTypes importedTypes |> List.filter(fun z -> z.modName = m.Name.Value) |> List.map(fun ref -> typesMap.[ref]) + Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value})) |> + Seq.distinct |> Seq.toList + let sortedTypes = DAstProgramUnit.sortTypes moduleTypes importedTypes |> List.filter(fun z -> z.modName = m.Name.Value) |> List.map(fun ref -> typesMap.[ref]) gen.ModuleXml m.Name.Value (ToC m.Name.Value) (m.Imports |> Seq.map PrintImpModule) exportedTypes m.ExportedVars (sortedTypes |> Seq.map (fun t -> PrintTas f t m.Name.Value)) (m.ValueAssignments |> Seq.map (fun t -> PrintVas f t m.Name.Value)) stgFileName @@ -299,12 +303,12 @@ let exportFile (r:AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (stgFi gen.FileXml f.FileName (f.Modules |> Seq.map (PrintModule f)) stgFileName let allTypes = - r.Files |> + r.Files |> List.collect(fun f -> f.Modules) |> List.collect(fun m -> - m.TypeAssignments |> List.map(fun tas -> tas.Type) + m.TypeAssignments |> List.map(fun tas -> tas.Type) ) - let globalSortedTypes = DAstProgramUnit.sortTypes allTypes [] + let globalSortedTypes = DAstProgramUnit.sortTypes allTypes [] let arrsSortedTypeAssignmentRefs = globalSortedTypes |> List.map(fun a -> gen.TypeAssignmentReference a.modName a.tasName stgFileName) let content = gen.RootXml (r.Files |> Seq.map PrintFile) arrsSortedTypeAssignmentRefs stgFileName File.WriteAllText(outFileName, content.Replace("\r","")) diff --git a/BackendAst/DAstACN.fs b/BackendAst/DAstACN.fs index 02874d8e1..f1ff46e57 100644 --- a/BackendAst/DAstACN.fs +++ b/BackendAst/DAstACN.fs @@ -21,7 +21,7 @@ let callBaseTypeFunc (lm:LanguageMacros) = lm.uper.call_base_type_func let sparkAnnotations (lm:LanguageMacros) = lm.acn.sparkAnnotations -let THREE_DOTS = {IcdRow.fieldName = ""; comments = []; sPresent="";sType= IcdPlainType ""; sConstraint=None; minLengtInBits = 0I; maxLengtInBits=0I;sUnits=None; rowType = IcdRowType.ThreeDOTs; idxOffset = None} +let THREE_DOTS = {IcdRow.fieldName = ""; comments = []; sPresent="";sType= IcdPlainType ""; sConstraint=None; minLengthInBits = 0I; maxLengthInBits=0I;sUnits=None; rowType = IcdRowType.ThreeDOTs; idxOffset = None} let getAcnDeterminantName (id : ReferenceToType) = match id with @@ -33,29 +33,22 @@ let getAcnDeterminantName (id : ReferenceToType) = ToC2(longName.Replace("#","elem")) -let getDeterminantTypeDefinitionBodyWithinSeq (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (det:Determinant) = +let getDeterminantTypeDefinitionBodyWithinSeq (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (det:Determinant) = let createPrmAcnInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) = - let Declare_Integer = lm.typeDef.Declare_Integer + let Declare_Integer = lm.typeDef.Declare_Integer Declare_Integer () let createAcnInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (a:Asn1AcnAst.AcnInteger) = let intClass = getAcnIntegerClass r.args a - let stgMacro = DAstTypeDefinition.getIntererTypeByClass lm intClass + let stgMacro = DAstTypeDefinition.getIntegerTypeByClass lm intClass stgMacro () - (* - let Declare_Integer = lm.typeDef.Declare_Integer - let Declare_PosInteger = lm.typeDef.Declare_PosInteger - match a.isUnsigned with - | true -> Declare_PosInteger () - | false -> Declare_Integer () - *) - + let createAcnBoolean (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) = - lm.typeDef.Declare_Boolean () + lm.typeDef.Declare_Boolean () let createAcnNull (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) = lm.typeDef.Declare_Null () - + let getTypeDefinitionName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (id : ReferenceToType) = let longName = id.AcnAbsPath.Tail |> Seq.StrJoin "_" ToC2(r.args.TypePrefix + longName.Replace("#","elem")) @@ -71,129 +64,103 @@ let getDeterminantTypeDefinitionBodyWithinSeq (r:Asn1AcnAst.AstRoot) (lm:Languag | AcnParameterDeterminant prm -> match prm.asn1Type with - | AcnGenericTypes.AcnPrmInteger _ -> createPrmAcnInteger r lm + | AcnGenericTypes.AcnPrmInteger _ -> createPrmAcnInteger r lm | AcnGenericTypes.AcnPrmBoolean _ -> createAcnBoolean r lm | AcnGenericTypes.AcnPrmNullType _ -> createAcnNull r lm - | AcnGenericTypes.AcnPrmRefType (md,ts) -> + | AcnGenericTypes.AcnPrmRefType (md,ts) -> getTypeDefinitionName r lm (ReferenceToType [MD md.Value; TA ts.Value]) -let getDeterminant_macro (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (det:Determinant) pri_macro str_macro = +let getDeterminant_macro (det:Determinant) pri_macro str_macro = match det with - | AcnChildDeterminant ch -> + | AcnChildDeterminant ch -> match ch.Type with - | Asn1AcnAst.AcnInteger a -> pri_macro - | Asn1AcnAst.AcnNullType _ -> pri_macro - | Asn1AcnAst.AcnBoolean _ -> pri_macro - | Asn1AcnAst.AcnReferenceToEnumerated a -> pri_macro - | Asn1AcnAst.AcnReferenceToIA5String a -> str_macro + | Asn1AcnAst.AcnReferenceToIA5String _ -> str_macro + | _ -> pri_macro + | AcnParameterDeterminant prm -> pri_macro - | AcnParameterDeterminant prm -> - match prm.asn1Type with - |AcnGenericTypes.AcnPrmInteger _ -> pri_macro - |AcnGenericTypes.AcnPrmBoolean _ -> pri_macro - |AcnGenericTypes.AcnPrmNullType _ -> pri_macro - |AcnGenericTypes.AcnPrmRefType (md,ts) -> pri_macro - -let getDeterminantTypeUpdateMacro (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (det:Determinant) = +let getDeterminantTypeUpdateMacro (lm:LanguageMacros) (det:Determinant) = let MultiAcnUpdate_get_first_init_value_pri = lm.acn.MultiAcnUpdate_get_first_init_value_pri let MultiAcnUpdate_get_first_init_value_str = lm.acn.MultiAcnUpdate_get_first_init_value_str - getDeterminant_macro r lm det MultiAcnUpdate_get_first_init_value_pri MultiAcnUpdate_get_first_init_value_str + getDeterminant_macro det MultiAcnUpdate_get_first_init_value_pri MultiAcnUpdate_get_first_init_value_str -let getDeterminantTypeCheckEqual (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (det:Determinant) = +let getDeterminantTypeCheckEqual (lm:LanguageMacros) (det:Determinant) = let multiAcnUpdate_checkEqual_pri = lm.acn.MultiAcnUpdate_checkEqual_pri let multiAcnUpdate_checkEqual_str = lm.acn.MultiAcnUpdate_checkEqual_str - getDeterminant_macro r lm det multiAcnUpdate_checkEqual_pri multiAcnUpdate_checkEqual_str - (* - match det with - | AcnChildDeterminant ch -> - match ch.Type with - | Asn1AcnAst.AcnInteger a -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnNullType _ -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnBoolean _ -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnReferenceToEnumerated a -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnReferenceToIA5String a -> multiAcnUpdate_checkEqual_str - - | AcnParameterDeterminant prm -> - match prm.asn1Type with - | Asn1AcnAst.AcnPrmInteger _ -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnPrmBoolean _ -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnPrmNullType _ -> multiAcnUpdate_checkEqual_pri - | Asn1AcnAst.AcnPrmRefType (md,ts) -> multiAcnUpdate_checkEqual_pri - *) + getDeterminant_macro det multiAcnUpdate_checkEqual_pri multiAcnUpdate_checkEqual_str -let handleSavePostion (funcBody:State-> ErroCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) savePosition c_name (typeId:ReferenceToType) (lm:LanguageMacros) (codec:CommonTypes.Codec) prms p = +let handleSavePosition (funcBody:State-> ErrorCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) savePosition c_name (typeId:ReferenceToType) (lm:LanguageMacros) (codec:CommonTypes.Codec) prms p = match savePosition with | false -> funcBody - | true -> + | true -> let newFuncBody st errCode prms p = - let content, ns1a = funcBody st errCode prms p - let sequence_save_bitstream = lm.acn.sequence_save_bitstream - let lvName = sprintf "bitStreamPositions_%d" (typeId.SeqeuenceOfLevel + 1) + let content, ns1a = funcBody st errCode prms p + let sequence_save_bitstream = lm.acn.sequence_save_bitstream + let lvName = sprintf "bitStreamPositions_%d" (typeId.SequenceOfLevel + 1) let savePositionStatement = sequence_save_bitstream lvName c_name codec - let newContent = + let newContent = match content with - | Some bodyResult -> + | Some bodyResult -> let funcBodyStr = sprintf "%s\n%s" savePositionStatement bodyResult.funcBody Some {bodyResult with funcBody = funcBodyStr} | None -> - let funcBodyStr = savePositionStatement - Some {funcBody = funcBodyStr; errCodes =[]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false} + let funcBodyStr = savePositionStatement + Some {funcBody = funcBodyStr; errCodes =[]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false; resultExpr = None} newContent, ns1a newFuncBody -let handleAlignemntForAsn1Types (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (acnAligment : AcnAligment option ) (funcBody:State-> ErroCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) = - let alignToNext = lm.acn.alignToNext - match acnAligment with +let handleAlignmentForAsn1Types (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (acnAlignment: AcnAlignment option ) (funcBody:State-> ErrorCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) = + let alignToNext = lm.acn.alignToNext + match acnAlignment with | None -> funcBody - | Some al -> - let alStr, nAligmVal = + | Some al -> + let alStr, nAlignmentVal = match al with - | AcnGenericTypes.NextByte -> + | AcnGenericTypes.NextByte -> match ST.lang with | Scala -> "Byte", 8I | _ -> "NextByte", 8I - | AcnGenericTypes.NextWord -> + | AcnGenericTypes.NextWord -> match ST.lang with | Scala -> "Short", 16I | _ -> "NextWord", 16I - | AcnGenericTypes.NextDWord -> + | AcnGenericTypes.NextDWord -> match ST.lang with | Scala -> "Int", 32I | _ -> "NextDWord", 32I let newFuncBody st errCode prms p = - let content, ns1a = funcBody st errCode prms p - let newContent = + let content, ns1a = funcBody st errCode prms p + let newContent = match content with - | Some bodyResult -> - let funcBodyStr = alignToNext bodyResult.funcBody alStr nAligmVal codec + | Some bodyResult -> + let funcBodyStr = alignToNext bodyResult.funcBody alStr nAlignmentVal codec Some {bodyResult with funcBody = funcBodyStr} | None -> - let funcBodyStr = alignToNext "" alStr nAligmVal codec - Some {funcBody = funcBodyStr; errCodes =[errCode]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false} + let funcBodyStr = alignToNext "" alStr nAlignmentVal codec + Some {funcBody = funcBodyStr; errCodes =[errCode]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false; resultExpr = None} newContent, ns1a newFuncBody -let handleAlignemntForAcnTypes (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (acnAligment : AcnAligment option ) (funcBody:CommonTypes.Codec -> ((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> (AcnFuncBodyResult option)) = +let handleAlignmentForAcnTypes (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (acnAlignment : AcnAlignment option ) (funcBody:CommonTypes.Codec -> ((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> (AcnFuncBodyResult option)) = let alignToNext = lm.acn.alignToNext - match acnAligment with + match acnAlignment with | None -> funcBody - | Some al -> - let alStr, nAligmVal = + | Some al -> + let alStr, nAlignmentVal = match al with | AcnGenericTypes.NextByte -> "NextByte", 8I | AcnGenericTypes.NextWord -> "NextWord", 16I | AcnGenericTypes.NextDWord -> "NextDWord", 32I let newFuncBody (codec:CommonTypes.Codec) prms p = - let content = funcBody codec prms p - let newContent = + let content = funcBody codec prms p + let newContent = match content with - | Some bodyResult -> - let funcBodyStr = alignToNext bodyResult.funcBody alStr nAligmVal codec + | Some bodyResult -> + let funcBodyStr = alignToNext bodyResult.funcBody alStr nAlignmentVal codec Some {bodyResult with funcBody = funcBodyStr} | None -> - let funcBodyStr = alignToNext "" alStr nAligmVal codec - Some {funcBody = funcBodyStr; errCodes =[]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false} + let funcBodyStr = alignToNext "" alStr nAlignmentVal codec + Some {funcBody = funcBodyStr; errCodes =[]; localVariables = []; bValIsUnReferenced= true; bBsIsUnReferenced=false; resultExpr = None} newContent newFuncBody @@ -201,31 +168,24 @@ type IcdArgAux = { canBeEmbedded : bool baseAsn1Kind : string rowsFunc : string->string->string list ->IcdRow list - //compositeChildren : IcdTypeAss list commentsForTas : string list scope : string name : string option } -//createIcdAux r t.id icdAux td typeDefinition nMinBytesInACN nMaxBytesInACN -let createIcdAux (r:Asn1AcnAst.AstRoot) (id:ReferenceToType) (icdAux:IcdArgAux) hash (td:FE_TypeDefinition) (typeDefinition:TypeDefintionOrReference) nMinBytesInACN nMaxBytesInACN= - let typeDefinitionName0 = - match typeDefinition with - | ReferenceToExistingDefinition refToExist -> refToExist.typedefName - | TypeDefinition tdDef -> tdDef.typedefName - +let createIcdAux (r:Asn1AcnAst.AstRoot) (id:ReferenceToType) (icdAux:IcdArgAux) hash (td:FE_TypeDefinition) (typeDefinition:TypeDefinitionOrReference) nMinBytesInACN nMaxBytesInACN= let typeAss = { IcdTypeAss.linkId = id tasInfo = id.tasInfo - asn1Link = None; - acnLink = None; - name = + asn1Link = None; + acnLink = None; + name = match icdAux.name with | Some n -> n - | None -> td.asn1Name //typeDefinitionName0; - kind = icdAux.baseAsn1Kind; - comments = - let asn1Comments = + | None -> td.asn1Name + kind = icdAux.baseAsn1Kind; + comments = + let asn1Comments = match id.tasInfo with | None -> [] | Some tasInfo -> @@ -236,10 +196,9 @@ let createIcdAux (r:Asn1AcnAst.AstRoot) (id:ReferenceToType) (icdAux:IcdArgAux) | None -> [] | Some ts -> ts.Comments |> Seq.toList asn1Comments@icdAux.commentsForTas - rows = icdAux.rowsFunc "" "" []; - //compositeChildren = icdAux.compositeChildren - minLengtInBytes = nMinBytesInACN; - maxLengtInBytes = nMaxBytesInACN + rows = icdAux.rowsFunc "" "" []; + minLengthInBytes = nMinBytesInACN; + maxLengthInBytes = nMaxBytesInACN hash = hash } {IcdAux.canBeEmbedded = icdAux.canBeEmbedded; createRowsFunc= icdAux.rowsFunc; typeAss=typeAss} @@ -248,25 +207,25 @@ let md5 = System.Security.Cryptography.MD5.Create() let calcIcdTypeAssHash (codec:CommonTypes.Codec) bPrint (t1:IcdTypeAss) = let rec calcIcdTypeAssHash_aux (t1:IcdTypeAss) = - let rws = - t1.rows |> - Seq.map(fun r -> sprintf "%A%A%A%A%A%A%A%A%A%A" r.idxOffset r.fieldName r.comments r.sPresent r.sType r.sConstraint r.minLengtInBits r.maxLengtInBits r.sUnits r.rowType) |> + let rws = + t1.rows |> + Seq.map(fun r -> sprintf "%A%A%A%A%A%A%A%A%A%A" r.idxOffset r.fieldName r.comments r.sPresent r.sType r.sConstraint r.minLengthInBits r.maxLengthInBits r.sUnits r.rowType) |> Seq.StrJoin "" - //let ch = t1.compositeChildren |> Seq.map calcIcdTypeAssHash_aux |> Seq.StrJoin "" - let aa = sprintf"%A%A%A%A%A%A%A%A%A" t1.acnLink t1.asn1Link t1.name t1.kind t1.comments t1.minLengtInBytes t1.maxLengtInBytes (rws) ("") + let aa = sprintf"%A%A%A%A%A%A%A%A%A" t1.acnLink t1.asn1Link t1.name t1.kind t1.comments t1.minLengthInBytes t1.maxLengthInBytes (rws) ("") let bytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes aa) Convert.ToHexString bytes - - let aa = calcIcdTypeAssHash_aux t1 - aa - -let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (funcBody:State-> ErroCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) isTestVaseValid (icdAux:IcdArgAux) soSparkAnnotations (us:State) = - if t.id.AsString = "PUS-C.TC.apidf" then - printfn "Debug" - let td = lm.lg.getTypeDefinition t.FT_TypeDefintion - let funcNameAndtasInfo = + + calcIcdTypeAssHash_aux t1 + +let adaptArgument = DAstUPer.adaptArgument + +let joinedOrAsIdentifier = DAstUPer.joinedOrAsIdentifier + +let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (funcBody:State-> ErrorCode->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State)) isTestVaseValid (icdAux:IcdArgAux) soSparkAnnotations (us:State) = + let td = lm.lg.getTypeDefinition t.FT_TypeDefinition + let funcNameAndtasInfo = match t.acnParameters with - | [] -> + | [] -> match t.id.tasInfo with | None -> None | Some _ -> Some (td.typeName + "_ACN" + codec.suffix) @@ -281,30 +240,29 @@ let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: let EmitTypeAssignment_def_err_code = lm.acn.EmitTypeAssignment_def_err_code let funcBodyAsSeqComp st prms p c_name : ((AcnFuncBodyResult option)*State) = - let funcBody = handleSavePostion funcBody t.SaveBitStreamPosition c_name t.id lm codec prms p - let ret = handleAlignemntForAsn1Types r lm codec t.acnAligment funcBody - ret st errCode prms p - + let funcBody = handleSavePosition funcBody t.SaveBitStreamPosition c_name t.id lm codec prms p + let ret = handleAlignmentForAsn1Types r lm codec t.acnAlignment funcBody + ret st errCode prms p - let funcBody = handleAlignemntForAsn1Types r lm codec t.acnAligment funcBody + let funcBody = handleAlignmentForAsn1Types r lm codec t.acnAlignment funcBody let p : CallerScope = lm.lg.getParamType t codec let topLevAcc = lm.lg.getAccess p.arg - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let isValidFuncName = match isValidFunc with None -> None | Some f -> f.funcName - let sInitilialExp = "" - let func, funcDef,ns2 = + let sInitialExp = "" + let func, funcDef,ns2 = match funcNameAndtasInfo with | None -> None, None, ns - | Some funcName -> - let content, ns1a = funcBody ns errCode [] p - let bodyResult_funcBody, errCodes, bodyResult_localVariables, bBsIsUnreferenced, bVarNameIsUnreferenced = - match content with - | None -> - let emtyStatement = lm.lg.emtyStatement - emtyStatement, [], [], true, isValidFuncName.IsNone - | Some bodyResult -> + | Some funcName -> + let content, ns1a = funcBody ns errCode [] p + let bodyResult_funcBody, errCodes, bodyResult_localVariables, bBsIsUnreferenced, bVarNameIsUnreferenced = + match content with + | None -> + let emptyStatement = lm.lg.emptyStatement + emptyStatement, [], [], true, isValidFuncName.IsNone + | Some bodyResult -> bodyResult.funcBody, bodyResult.errCodes, bodyResult.localVariables, bodyResult.bBsIsUnReferenced, bodyResult.bValIsUnReferenced let handleAcnParameter (p:AcnGenericTypes.AcnParameter) = @@ -315,11 +273,11 @@ let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: | AcnGenericTypes.AcnPrmInteger loc -> emitPrm p.c_name intType | AcnGenericTypes.AcnPrmBoolean loc -> emitPrm p.c_name boolType | AcnGenericTypes.AcnPrmNullType loc -> raise(SemanticError (loc, "Invalid type for parameter")) - | AcnGenericTypes.AcnPrmRefType(md,ts) -> + | AcnGenericTypes.AcnPrmRefType(md,ts) -> let prmTypeName = match lm.lg.hasModules with | false -> ToC2(r.args.TypePrefix + ts.Value) - | true -> + | true -> match md.Value = t.id.ModName with | true -> ToC2(r.args.TypePrefix + ts.Value) | false -> (ToC2 md.Value) + "." + ToC2(r.args.TypePrefix + ts.Value) @@ -328,30 +286,29 @@ let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: let lvars = bodyResult_localVariables |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct let prms = t.acnParameters |> List.map handleAcnParameter let prmNames = t.acnParameters |> List.map (fun p -> p.c_name) - let func = Some(EmitTypeAssignment_primitive varName sStar funcName isValidFuncName (typeDefinition.longTypedefName2 lm.lg.hasModules) lvars bodyResult_funcBody soSparkAnnotations sInitilialExp prms prmNames (t.acnMaxSizeInBits = 0I) bBsIsUnreferenced bVarNameIsUnreferenced soInitFuncName codec) - - //let errCodes = bodyResult.errCodes + let func = Some(EmitTypeAssignment_primitive varName sStar funcName isValidFuncName (typeDefinition.longTypedefName2 lm.lg.hasModules) lvars bodyResult_funcBody soSparkAnnotations sInitialExp prms prmNames (t.acnMaxSizeInBits = 0I) bBsIsUnreferenced bVarNameIsUnreferenced soInitFuncName codec) + let errCodStr = errCodes |> List.map(fun x -> EmitTypeAssignment_def_err_code x.errCodeName (BigInteger x.errCodeValue) x.comment) |> List.distinct let funcDef = Some(EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) errCodStr (t.acnMaxSizeInBits = 0I) nMaxBytesInACN ( t.acnMaxSizeInBits) prms soSparkAnnotations codec) func, funcDef,ns1a - - let icdAux, ns3 = + + let icdAux, ns3 = match codec with | Encode -> - let tr = createIcdAux r t.id icdAux "" td typeDefinition nMinBytesInACN nMaxBytesInACN + let tr = createIcdAux r t.id icdAux "" td typeDefinition nMinBytesInACN nMaxBytesInACN let icdHash = calcIcdTypeAssHash codec true tr.typeAss let trTypeAssWithHash = {tr.typeAss with hash = icdHash} let tr = {tr with typeAss = trTypeAssWithHash} - let ns3 = + let ns3 = match ns2.icdHashes.TryFind icdHash with | None -> {ns2 with icdHashes = ns2.icdHashes.Add(icdHash, [tr.typeAss])} | Some exList -> {ns2 with icdHashes = ns2.icdHashes.Add(icdHash, tr.typeAss::exList)} Some tr, ns3 | Decode -> None, ns2 - let ret = + let ret = { - AcnFunction.funcName = funcNameAndtasInfo - func = func + AcnFunction.funcName = funcNameAndtasInfo + func = func funcDef = funcDef funcBody = (fun us acnArgs p -> funcBody us errCode acnArgs p ) funcBodyAsSeqComp = funcBodyAsSeqComp @@ -361,43 +318,43 @@ let private createAcnFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: ret, ns3 -let private createAcnIntegerFunctionInternal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (uperRange : BigIntegerUperRange) (intClass:Asn1AcnAst.IntegerClass) acnEncodingClass (uperfuncBody : ErroCode -> CallerScope -> (UPERFuncBodyResult option)) (soMF:string option, soMFM:string option) : (ErroCode -> ((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> (AcnFuncBodyResult option)) = - let PositiveInteger_ConstSize_8 = lm.acn.PositiveInteger_ConstSize_8 - let PositiveInteger_ConstSize_big_endian_16 = lm.acn.PositiveInteger_ConstSize_big_endian_16 - let PositiveInteger_ConstSize_little_endian_16 = lm.acn.PositiveInteger_ConstSize_little_endian_16 - let PositiveInteger_ConstSize_big_endian_32 = lm.acn.PositiveInteger_ConstSize_big_endian_32 - let PositiveInteger_ConstSize_little_endian_32 = lm.acn.PositiveInteger_ConstSize_little_endian_32 - let PositiveInteger_ConstSize_big_endian_64 = lm.acn.PositiveInteger_ConstSize_big_endian_64 - let PositiveInteger_ConstSize_little_endian_64 = lm.acn.PositiveInteger_ConstSize_little_endian_64 - let PositiveInteger_ConstSize = lm.acn.PositiveInteger_ConstSize - let TwosComplement_ConstSize_8 = lm.acn.TwosComplement_ConstSize_8 - let TwosComplement_ConstSize_big_endian_16 = lm.acn.TwosComplement_ConstSize_big_endian_16 - let TwosComplement_ConstSize_little_endian_16 = lm.acn.TwosComplement_ConstSize_little_endian_16 - let TwosComplement_ConstSize_big_endian_32 = lm.acn.TwosComplement_ConstSize_big_endian_32 - let TwosComplement_ConstSize_little_endian_32 = lm.acn.TwosComplement_ConstSize_little_endian_32 - let TwosComplement_ConstSize_big_endian_64 = lm.acn.TwosComplement_ConstSize_big_endian_64 - let TwosComplement_ConstSize_little_endian_64 = lm.acn.TwosComplement_ConstSize_little_endian_64 - let TwosComplement_ConstSize = lm.acn.TwosComplement_ConstSize - let ASCII_ConstSize = lm.acn.ASCII_ConstSize - let ASCII_VarSize_NullTerminated = lm.acn.ASCII_VarSize_NullTerminated +let private createAcnIntegerFunctionInternal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (uperRange : BigIntegerUperRange) (intClass:Asn1AcnAst.IntegerClass) acnEncodingClass (uperfuncBody : ErrorCode -> CallerScope -> (UPERFuncBodyResult option)) (soMF:string option, soMFM:string option) : (ErrorCode -> ((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> (AcnFuncBodyResult option)) = + let PositiveInteger_ConstSize_8 = lm.acn.PositiveInteger_ConstSize_8 + let PositiveInteger_ConstSize_big_endian_16 = lm.acn.PositiveInteger_ConstSize_big_endian_16 + let PositiveInteger_ConstSize_little_endian_16 = lm.acn.PositiveInteger_ConstSize_little_endian_16 + let PositiveInteger_ConstSize_big_endian_32 = lm.acn.PositiveInteger_ConstSize_big_endian_32 + let PositiveInteger_ConstSize_little_endian_32 = lm.acn.PositiveInteger_ConstSize_little_endian_32 + let PositiveInteger_ConstSize_big_endian_64 = lm.acn.PositiveInteger_ConstSize_big_endian_64 + let PositiveInteger_ConstSize_little_endian_64 = lm.acn.PositiveInteger_ConstSize_little_endian_64 + let PositiveInteger_ConstSize = lm.acn.PositiveInteger_ConstSize + let TwosComplement_ConstSize_8 = lm.acn.TwosComplement_ConstSize_8 + let TwosComplement_ConstSize_big_endian_16 = lm.acn.TwosComplement_ConstSize_big_endian_16 + let TwosComplement_ConstSize_little_endian_16 = lm.acn.TwosComplement_ConstSize_little_endian_16 + let TwosComplement_ConstSize_big_endian_32 = lm.acn.TwosComplement_ConstSize_big_endian_32 + let TwosComplement_ConstSize_little_endian_32 = lm.acn.TwosComplement_ConstSize_little_endian_32 + let TwosComplement_ConstSize_big_endian_64 = lm.acn.TwosComplement_ConstSize_big_endian_64 + let TwosComplement_ConstSize_little_endian_64 = lm.acn.TwosComplement_ConstSize_little_endian_64 + let TwosComplement_ConstSize = lm.acn.TwosComplement_ConstSize + let ASCII_ConstSize = lm.acn.ASCII_ConstSize + let ASCII_VarSize_NullTerminated = lm.acn.ASCII_VarSize_NullTerminated //+++ todo write ada stg macros for ASCII_UINT_ConstSize, ASCII_UINT_VarSize_NullTerminated - let ASCII_UINT_ConstSize = lm.acn.ASCII_UINT_ConstSize - let ASCII_UINT_VarSize_NullTerminated = lm.acn.ASCII_UINT_VarSize_NullTerminated - let BCD_ConstSize = lm.acn.BCD_ConstSize - let BCD_VarSize_NullTerminated = lm.acn.BCD_VarSize_NullTerminated + let ASCII_UINT_ConstSize = lm.acn.ASCII_UINT_ConstSize + let ASCII_UINT_VarSize_NullTerminated = lm.acn.ASCII_UINT_VarSize_NullTerminated + let BCD_ConstSize = lm.acn.BCD_ConstSize + let BCD_VarSize_NullTerminated = lm.acn.BCD_VarSize_NullTerminated //let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) //let errCodeValue = us.currErrCode - //let errCode = {ErroCode.errCodeName = errCodeName; errCodeValue = errCodeValue} - let nUperMin, nUperMax = + //let errCode = {ErrorCode.errCodeName = errCodeName; errCodeValue = errCodeValue} + let nUperMin, nUperMax = match uperRange with | Concrete(a,b) -> a,b | NegInf(b) -> r.args.SIntMin, b | PosInf(a) -> a, r.args.IntMax (a>=0I) | Full -> r.args.SIntMin, r.args.SIntMax - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let uIntActualMax (nBits:int) = let a = 2I**nBits - 1I min a nUperMax @@ -407,11 +364,11 @@ let private createAcnIntegerFunctionInternal (r:Asn1AcnAst.AstRoot) (lm:Language let sIntActualMax (nBits:int) = let a = 2I**(nBits-1) - 1I min a nUperMax - let sSsuffix = DAstUPer.getIntDecFuncSuffix intClass + let sSsuffix = DAstUPer.getIntDecFuncSuffix intClass let castPp encFuncBits = DAstUPer.castPp r lm codec pp intClass encFuncBits let word_size_in_bits = (int r.args.integerSizeInBytes)*8 - //let soMF = match - let funcBodyContent = + //let soMF = match + let funcBodyContent = match acnEncodingClass with |Asn1AcnAst.Integer_uPER -> uperfuncBody errCode p |> Option.map(fun x -> x.funcBody, x.errCodes, x.bValIsUnReferenced, x.bBsIsUnReferenced) |Asn1AcnAst.PositiveInteger_ConstSize_8 -> Some(PositiveInteger_ConstSize_8 (castPp 8) sSsuffix errCode.errCodeName soMF soMFM (max 0I nUperMin) (uIntActualMax 8) codec, [errCode], false, false) @@ -422,7 +379,7 @@ let private createAcnIntegerFunctionInternal (r:Asn1AcnAst.AstRoot) (lm:Language |Asn1AcnAst.PositiveInteger_ConstSize_big_endian_64 -> Some(PositiveInteger_ConstSize_big_endian_64 (castPp 64) sSsuffix errCode.errCodeName soMF soMFM (max 0I nUperMin) (uIntActualMax 64) codec, [errCode], false, false) |Asn1AcnAst.PositiveInteger_ConstSize_little_endian_64 -> Some(PositiveInteger_ConstSize_little_endian_64 (castPp 64) sSsuffix errCode.errCodeName soMF soMFM (max 0I nUperMin) (uIntActualMax 64) codec, [errCode], false, false) |Asn1AcnAst.PositiveInteger_ConstSize bitSize -> Some(PositiveInteger_ConstSize (castPp word_size_in_bits) sSsuffix errCode.errCodeName ( bitSize) soMF soMFM (max 0I nUperMin) (uIntActualMax (int bitSize)) codec, [errCode], false, false) - + |Asn1AcnAst.TwosComplement_ConstSize_8 -> Some(TwosComplement_ConstSize_8 (castPp 8) sSsuffix errCode.errCodeName soMF soMFM (sIntActualMin 8) (sIntActualMax 8) codec, [errCode], false, false) |Asn1AcnAst.TwosComplement_ConstSize_big_endian_16 -> Some(TwosComplement_ConstSize_big_endian_16 (castPp 16) sSsuffix errCode.errCodeName soMF soMFM (sIntActualMin 16) (sIntActualMax 16) codec, [errCode], false, false) |Asn1AcnAst.TwosComplement_ConstSize_little_endian_16 -> Some(TwosComplement_ConstSize_little_endian_16 (castPp 16) sSsuffix errCode.errCodeName soMF soMFM (sIntActualMin 16) (sIntActualMax 16) codec, [errCode], false, false) @@ -440,12 +397,11 @@ let private createAcnIntegerFunctionInternal (r:Asn1AcnAst.AstRoot) (lm:Language |Asn1AcnAst.BCD_VarSize_NullTerminated nullBytes -> Some(BCD_VarSize_NullTerminated (castPp word_size_in_bits) sSsuffix errCode.errCodeName soMF soMFM nUperMin nUperMax codec, [errCode], false, false) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes, bValIsUnReferenced, bBsIsUnReferenced ) -> - Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= bValIsUnReferenced; bBsIsUnReferenced=bBsIsUnReferenced}) - //let funcBody = (funcBody errCode) + | Some (funcBodyContent,errCodes, bValIsUnReferenced, bBsIsUnReferenced ) -> + Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= bValIsUnReferenced; bBsIsUnReferenced=bBsIsUnReferenced; resultExpr = resultExpr}) funcBody -let getMappingFunctionModule (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (soMapFuncName:string option) = +let getMappingFunctionModule (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (soMapFuncName:string option) = match lm.lg.hasModules with | false -> None | true -> @@ -461,12 +417,12 @@ let createAcnIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:C let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None - let uperFuncBody (errCode) (p:CallerScope) = + let uperFuncBody (errCode) (p:CallerScope) = DAstUPer.getIntfuncBodyByCons r lm codec t.uperRange t.Location (getAcnIntegerClass r.args t) (t.cons) (t.cons@t.withcons) errCode p - let soMapFunMod, soMapFunc = - match t.acnProperties.mappingFunction with - | Some (MappingFunction (soMapFunMod, mapFncName)) -> - let soMapFunMod, soMapFunc = soMapFunMod, Some mapFncName.Value + let soMapFunMod, soMapFunc = + match t.acnProperties.mappingFunction with + | Some (MappingFunction (soMapFunMod, mapFncName)) -> + let soMapFunMod, soMapFunc = soMapFunMod, Some mapFncName.Value match soMapFunMod with | None -> getMappingFunctionModule r lm soMapFunc, soMapFunc | Some soMapFunMod -> Some soMapFunMod.Value, soMapFunc @@ -475,85 +431,81 @@ let createAcnIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:C (funcBody errCode), ns -let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = - let soMapFunMod, soMapFunc = - match o.acnProperties.mappingFunction with - | Some (MappingFunction (soMapFunMod, mapFncName)) -> - let soMapFunMod, soMapFunc = soMapFunMod, Some mapFncName.Value +let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = + let soMapFunMod, soMapFunc = + match o.acnProperties.mappingFunction with + | Some (MappingFunction (soMapFunMod, mapFncName)) -> + let soMapFunMod, soMapFunc = soMapFunMod, Some mapFncName.Value match soMapFunMod with | None -> getMappingFunctionModule r lm soMapFunc, soMapFunc | Some soMapFunMod -> Some soMapFunMod.Value, soMapFunc | None -> None, None let funcBody = createAcnIntegerFunctionInternal r lm codec o.uperRange o.intClass o.acnEncodingClass uperFunc.funcBody_e (soMapFunc, soMapFunMod) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - - let sAsn1Constraints = - let sTmpCons = o.AllCons |> List.map (DastValidate2.printRangeConAsAsn1 (fun z -> z.ToString())) |> Seq.StrJoin "" + + let sAsn1Constraints = + let sTmpCons = o.AllCons |> List.map (DastValidate2.printRangeConAsAsn1 (fun z -> z.ToString())) |> Seq.StrJoin "" match sTmpCons.Trim() with | "" -> None | _ -> Some sTmpCons - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=sAsn1Constraints; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=sAsn1Constraints; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us let createAcnChildIcdFunction (ch:AcnChild) = - let icd fieldName comments = - let sType, minSize, maxSize = + let icd fieldName comments = + let sType, minSize, maxSize = match ch.Type with | Asn1AcnAst.AcnInteger a -> "INTEGER", a.acnMinSizeInBits, a.acnMaxSizeInBits | Asn1AcnAst.AcnBoolean a -> "BOOLEAN", a.acnMinSizeInBits, a.acnMaxSizeInBits | Asn1AcnAst.AcnNullType a -> "NULL", a.acnMinSizeInBits, a.acnMaxSizeInBits | Asn1AcnAst.AcnReferenceToEnumerated a -> a.tasName.Value, a.enumerated.acnMinSizeInBits, a.enumerated.acnMaxSizeInBits | Asn1AcnAst.AcnReferenceToIA5String a -> a.tasName.Value, a.str.acnMinSizeInBits, a.str.acnMaxSizeInBits - {IcdRow.fieldName = fieldName; comments = comments; sPresent="always";sType=(IcdPlainType sType); sConstraint=None; minLengtInBits = minSize ;maxLengtInBits=maxSize;sUnits=None; rowType = IcdRowType.FieldRow; idxOffset = None} + {IcdRow.fieldName = fieldName; comments = comments; sPresent="always";sType=(IcdPlainType sType); sConstraint=None; minLengthInBits = minSize ;maxLengthInBits=maxSize;sUnits=None; rowType = IcdRowType.FieldRow; idxOffset = None} icd -let createEnumComn (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefintionOrReference ) (typeDefinitionName:string) = +let createEnumCommon (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefinitionOrReference ) (typeDefinitionName:string) = let EnumeratedEncValues = lm.acn.EnumeratedEncValues let Enumerated_item = lm.acn.Enumerated_item let IntFullyConstraintPos = lm.uper.IntFullyConstraintPos let min = o.items |> List.map(fun x -> x.acnEncodeValue) |> Seq.min let max = o.items |> List.map(fun x -> x.acnEncodeValue) |> Seq.max - //let intVal = "intVal" - let sFirstItemName = lm.lg.getNamedItemBackendName (Some defOrRef) o.items.Head + let sFirstItemName = lm.lg.getNamedItemBackendName (Some defOrRef) o.items.Head let uperRange = (Concrete (min,max)) let intTypeClass = getIntEncodingClassByUperRange r.args uperRange - let rtlIntType = (DAstTypeDefinition.getIntererTypeByClass lm intTypeClass)() - let localVar, intVal = - let varName = "intVal" - let initExp = - match ST.lang with - | ProgrammingLanguage.Scala -> Some("0L") - | _ -> None - GenericLocalVariable {GenericLocalVariable.name = varName; varType= rtlIntType; arrSize= None; isStatic = false; initExp=initExp }, varName - //match min >= 0I with - //| true -> Asn1UIntLocalVariable ("uIntVal",None), "uIntVal" - //| false -> Asn1SIntLocalVariable ("intVal",None), "intVal" - let pVal = {CallerScope.modName = typeId.ModName; arg = VALUE intVal} - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let td = (lm.lg.getEnmTypeDefintion o.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) - let intFuncBody = - let uperInt (errCode:ErroCode) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + let rtlIntType = (DAstTypeDefinition.getIntegerTypeByClass lm intTypeClass)() + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let td = (lm.lg.getEnumTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) + let localVar, intVal = + let varName = $"intVal_{ToC p.arg.asIdentifier}" + let lv = + match lm.lg.decodingKind with + | Copy -> [] + | InPlace -> [GenericLocalVariable {GenericLocalVariable.name = varName; varType= rtlIntType; arrSize= None; isStatic = false; initExp=None}] + lv, varName + let pVal = {CallerScope.modName = typeId.ModName; arg = Selection.valueEmptyPath intVal} + let intFuncBody = + let uperInt (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let castPp = DAstUPer.castPp r lm codec pp intTypeClass - let sSsuffix = DAstUPer.getIntDecFuncSuffix intTypeClass + let sSsuffix = DAstUPer.getIntDecFuncSuffix intTypeClass let word_size_in_bits = (int r.args.integerSizeInBytes)*8 let funcBody = IntFullyConstraintPos (castPp word_size_in_bits) min max (GetNumberOfBitsForNonNegativeInteger (max-min)) sSsuffix errCode.errCodeName codec - Some({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables= []; bValIsUnReferenced=false; bBsIsUnReferenced=false}) + Some({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables= []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) createAcnIntegerFunctionInternal r lm codec (Concrete (min,max)) intTypeClass o.acnEncodingClass uperInt (None, None) - let funcBodyContent = + let funcBodyContent = match intFuncBody errCode acnArgs pVal with - | None -> None - | Some(intAcnFuncBdResult) -> - let arrItems = o.items |> List.map(fun it -> + | None -> None + | Some intAcnFuncBdResult -> + let arrItems = o.items |> List.map(fun it -> let enumClassName = extractEnumClassName "" it.scala_name it.Name.Value Enumerated_item (lm.lg.getValue p.arg) (lm.lg.getNamedItemBackendName (Some defOrRef) it ) enumClassName it.acnEncodeValue intVal codec) - Some (EnumeratedEncValues (lm.lg.getValue p.arg) td arrItems intAcnFuncBdResult.funcBody errCode.errCodeName sFirstItemName intVal codec, intAcnFuncBdResult.errCodes, localVar::intAcnFuncBdResult.localVariables) + Some (EnumeratedEncValues (lm.lg.getValue p.arg) td arrItems intAcnFuncBdResult.funcBody errCode.errCodeName sFirstItemName intVal codec, intAcnFuncBdResult.resultExpr, intAcnFuncBdResult.errCodes, localVar@intAcnFuncBdResult.localVariables) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | Some (funcBodyContent, resultExpr, errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) funcBody let enumComment stgFileName (o:Asn1AcnAst.Enumerated) = @@ -562,37 +514,37 @@ let enumComment stgFileName (o:Asn1AcnAst.Enumerated) = match comment.Trim() with | "" -> icd_uper.EmitEnumItem stgFileName n.Name.Value n.definitionValue | _ -> icd_uper.EmitEnumItemWithComment stgFileName n.Name.Value n.definitionValue comment - let itemsHtml = - o.items |> - List.filter(fun z -> + let itemsHtml = + o.items |> + List.filter(fun z -> let v = z.Name.Value Asn1Fold.isValidValueGeneric o.AllCons (=) v ) |> - List.map EmitItem + List.map EmitItem icd_uper.EmitEnumInternalContents stgFileName itemsHtml -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefintionOrReference) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefinitionOrReference) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = let typeDefinitionName = defOrRef.longTypedefName2 lm.lg.hasModules //getTypeDefinitionName t.id.tasInfo typeDefinition - let funcBody = createEnumComn r lm codec t.id o defOrRef typeDefinitionName + let funcBody = createEnumCommon r lm codec t.id o defOrRef typeDefinitionName let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent (comments:string list) = + let icdFnc fieldName sPresent (comments:string list) = let newComments = comments@[enumComment icdStgFileName o] - [{IcdRow.fieldName = fieldName; comments = newComments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + [{IcdRow.fieldName = fieldName; comments = newComments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None;} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us -let createAcnEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (t:Asn1AcnAst.AcnReferenceToEnumerated) (defOrRef:TypeDefintionOrReference) (us:State) = +let createAcnEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (t:Asn1AcnAst.AcnReferenceToEnumerated) (defOrRef:TypeDefinitionOrReference) (us:State) = let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None - let td = lm.lg.getTypeDefinition (t.getType r).FT_TypeDefintion + let td = lm.lg.getTypeDefinition (t.getType r).FT_TypeDefinition let typeDefinitionName = td.typeName - let funcBody = createEnumComn r lm codec typeId t.enumerated defOrRef typeDefinitionName + let funcBody = createEnumCommon r lm codec typeId t.enumerated defOrRef typeDefinitionName (funcBody errCode), ns -let createRealrFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = +let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = let Real_32_big_endian = lm.acn.Real_32_big_endian let Real_64_big_endian = lm.acn.Real_64_big_endian let Real_32_little_endian = lm.acn.Real_32_little_endian @@ -604,12 +556,12 @@ let createRealrFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Common | ASN1SCC_FP32 -> "_fp32" | ASN1SCC_FP64 -> "" - - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let castPp = DAstUPer.castRPp lm codec (o.getClass r.args) pp - let funcBodyContent = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p + let castPp = DAstUPer.castRPp lm codec (o.getClass r.args) pp + + let funcBodyContent = match o.acnEncodingClass with | Real_IEEE754_32_big_endian -> Some (Real_32_big_endian castPp sSuffix errCode.errCodeName codec, [errCode]) | Real_IEEE754_64_big_endian -> Some (Real_64_big_endian pp errCode.errCodeName codec, [errCode]) @@ -618,88 +570,85 @@ let createRealrFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Common | Real_uPER -> uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | Some (funcBodyContent,errCodes) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getPointer p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let funcBodyContent = - uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes) +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let funcBodyContent = + uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes, x.resultExpr) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | Some (funcBodyContent,errCodes, resultExpr) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us -let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getPointer p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let funcBodyContent = - uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes) +let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let funcBodyContent = + uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes, x.resultExpr) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | Some (funcBodyContent,errCodes, resultExpr) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None;} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us -let nestChildItems (lm:LanguageMacros) (codec:CommonTypes.Codec) children = +let nestChildItems (lm:LanguageMacros) (codec:CommonTypes.Codec) children = DAstUtilFunctions.nestItems lm.isvalid.JoinItems2 children - let createAcnBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (o:Asn1AcnAst.AcnBoolean) (us:State) = let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let Boolean = lm.uper.Boolean - let funcBodyContent = + let funcBodyContent = Boolean pp errCode.errCodeName codec - Some {AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false} + Some {AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr} (funcBody errCode), ns -let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : AcnFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let pvalue = lm.lg.getValue p.arg - let ptr = lm.lg.getPointer p.arg +let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : AcnFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = let Boolean = lm.uper.Boolean let acnBoolean = lm.acn.Boolean - let funcBodyContent = + let funcBodyContent, resultExpr = match o.acnProperties.encodingPattern with - | None -> Boolean pp errCode.errCodeName codec - | Some (TrueValue bitVal) -> - let arrsBits = bitVal.Value.ToCharArray() |> Seq.mapi(fun i x -> ((i+1).ToString()) + "=>" + if x='0' then "0" else "1") |> Seq.toList - let arrBytes = bitStringValueToByteArray bitVal - let bEncValIsTrue, arruTrueValueAsByteArray, arruFalseValueAsByteArray, nSize = - true, arrBytes, (arrBytes |> Array.map (~~~)), bitVal.Value.Length - acnBoolean pvalue ptr bEncValIsTrue (BigInteger nSize) arruTrueValueAsByteArray arruFalseValueAsByteArray arrsBits errCode.errCodeName codec - | Some (FalseValue bitVal) -> - let arrsBits = bitVal.Value.ToCharArray() |> Seq.mapi(fun i x -> ((i+1).ToString()) + "=>" + if x='0' then "0" else "1") |> Seq.toList - let arrBytes = bitStringValueToByteArray bitVal - let bEncValIsTrue, arruTrueValueAsByteArray, arruFalseValueAsByteArray, nSize = - false, (arrBytes |> Array.map (~~~)), arrBytes, bitVal.Value.Length - acnBoolean pvalue ptr bEncValIsTrue (BigInteger nSize) arruTrueValueAsByteArray arruFalseValueAsByteArray arrsBits errCode.errCodeName codec - - {AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false} + | None -> + let pp, resultExpr = adaptArgument lm codec p + Boolean pp errCode.errCodeName codec, resultExpr + | Some pattern -> + let pvalue, ptr, resultExpr = + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let resExpr = p.arg.asIdentifier + resExpr, resExpr, Some resExpr + | _ -> lm.lg.getValue p.arg, lm.lg.getPointer p.arg, None + let arrBits = pattern.bitVal.Value.ToCharArray() |> Seq.mapi(fun i x -> ((i+1).ToString()) + "=>" + if x='0' then "0" else "1") |> Seq.toList + let arrBytes = bitStringValueToByteArray pattern.bitVal + let arrTrueValueAsByteArray = arrBytes |> Array.map (~~~) + let arrFalseValueAsByteArray = arrBytes + let nSize = pattern.bitVal.Value.Length + acnBoolean pvalue ptr pattern.isTrue (BigInteger nSize) arrTrueValueAsByteArray arrFalseValueAsByteArray arrBits errCode.errCodeName codec, resultExpr + + {AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> Some (funcBody e acnArgs p), us) (fun atc -> true) icd soSparkAnnotations us @@ -710,8 +659,8 @@ let createAcnNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let nullType = lm.acn.Null_pattern2 match o.acnProperties.encodingPattern with | None -> None @@ -728,16 +677,21 @@ let createAcnNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: let arrsBits = bitStringPattern.ToCharArray() |> Seq.mapi(fun i x -> ((i+1).ToString()) + "=>" + if x='0' then "0" else "1") |> Seq.toList arrsBits,arrBytes,(BigInteger bitStringPattern.Length) let ret = nullType pp arrBytes nBitsSize arrsBits errCode.errCodeName o.acnProperties.savePosition codec - Some ({AcnFuncBodyResult.funcBody = ret; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + Some ({AcnFuncBodyResult.funcBody = ret; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) (funcBody errCode), ns -let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg +let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let nullType = lm.acn.Null_pattern - + match o.acnProperties.encodingPattern with - | None -> None + | None -> + match codec, lm.lg.decodingKind with + | Decode, Copy -> + // Copy-decoding backend expect all values to be declared even if they are "dummies" + Some ({AcnFuncBodyResult.funcBody = lm.acn.Null_declare pp; errCodes = []; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=Some pp}) + | _ -> None | Some encPattern -> let arrsBits, arrBytes, nBitsSize = match encPattern with @@ -751,86 +705,86 @@ let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Com let arrsBits = bitStringPattern.ToCharArray() |> Seq.mapi(fun i x -> ((i+1).ToString()) + "=>" + if x='0' then "0" else "1") |> Seq.toList arrsBits,arrBytes,(BigInteger bitStringPattern.Length) let ret = nullType pp arrBytes nBitsSize arrsBits errCode.errCodeName o.acnProperties.savePosition codec - Some ({AcnFuncBodyResult.funcBody = ret; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= lm.lg.acn.null_valIsUnReferenced; bBsIsUnReferenced=false}) + Some ({AcnFuncBodyResult.funcBody = ret; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= lm.lg.acn.null_valIsUnReferenced; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us -let getExternaField0 (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency func1 = +let getExternalField0 (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency func1 = //let dependencies = deps.acnDependencies |> List.filter(fun d -> d.asn1Type = asn1TypeIdWithDependency && func1 d ) let dependency = deps.acnDependencies |> List.find(fun d -> d.asn1Type = asn1TypeIdWithDependency && func1 d ) let rec resolveParam (prmId:ReferenceToType) = let nodes = match prmId with ReferenceToType nodes -> nodes let lastNode = nodes |> List.rev |> List.head match lastNode with - | PRM prmName -> - let newDeterminantId = - deps.acnDependencies |> - List.choose(fun d -> + | PRM prmName -> + let newDeterminantId = + deps.acnDependencies |> + List.choose(fun d -> match d.dependencyKind with | AcnDepRefTypeArgument prm when prm.id = prmId -> Some d.determinant - | _ -> None) + | _ -> None) match newDeterminantId with | det1::_ -> resolveParam det1.id | _ -> prmId | _ -> prmId getAcnDeterminantName (resolveParam dependency.determinant.id) -let getExternaFieldChoizePresentWhen (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency relPath= +let getExternalFieldChoicePresentWhen (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency relPath= let filterDependency (d:AcnDependency) = match d.dependencyKind with | AcnDepPresence (relPath0, _) -> relPath = relPath0 | _ -> true - getExternaField0 r deps asn1TypeIdWithDependency filterDependency + getExternalField0 r deps asn1TypeIdWithDependency filterDependency -let getExternaField (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency = - getExternaField0 r deps asn1TypeIdWithDependency (fun z -> true) +let getExternalField (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) asn1TypeIdWithDependency = + getExternalField0 r deps asn1TypeIdWithDependency (fun z -> true) -let createStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = - let Acn_String_Ascii_FixSize = lm.acn.Acn_String_Ascii_FixSize - let Acn_String_Ascii_Internal_Field_Determinant = lm.acn.Acn_String_Ascii_Internal_Field_Determinant - let Acn_String_Ascii_Null_Teminated = lm.acn.Acn_String_Ascii_Null_Teminated - let Acn_String_Ascii_External_Field_Determinant = lm.acn.Acn_String_Ascii_External_Field_Determinant - let Acn_String_CharIndex_External_Field_Determinant = lm.acn.Acn_String_CharIndex_External_Field_Determinant +let createStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = + let Acn_String_Ascii_FixSize = lm.acn.Acn_String_Ascii_FixSize + let Acn_String_Ascii_Internal_Field_Determinant = lm.acn.Acn_String_Ascii_Internal_Field_Determinant + let Acn_String_Ascii_Null_Terminated = lm.acn.Acn_String_Ascii_Null_Terminated + let Acn_String_Ascii_External_Field_Determinant = lm.acn.Acn_String_Ascii_External_Field_Determinant + let Acn_String_CharIndex_External_Field_Determinant = lm.acn.Acn_String_CharIndex_External_Field_Determinant let Acn_IA5String_CharIndex_External_Field_Determinant = lm.acn.Acn_IA5String_CharIndex_External_Field_Determinant - - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) (us:State) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) (us:State) = + let pp, resultExpr = adaptArgument lm codec p let td = (lm.lg.getStrTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) - let funcBodyContent, ns = + let funcBodyContent, ns = match o.acnEncodingClass with | Acn_Enc_String_uPER _ -> uperFunc.funcBody_e errCode p |> Option.map(fun x -> x.funcBody, x.errCodes, x.localVariables), us - | Acn_Enc_String_uPER_Ascii _ -> + | Acn_Enc_String_uPER_Ascii _ -> match o.maxSize.uper = o.minSize.uper with | true -> Some (Acn_String_Ascii_FixSize pp errCode.errCodeName ( o.maxSize.uper) codec, [errCode], []), us - | false -> + | false -> let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.acn - o.minSize.acn)) Some (Acn_String_Ascii_Internal_Field_Determinant pp errCode.errCodeName ( o.maxSize.acn) ( o.minSize.acn) nSizeInBits codec , [errCode], []), us - | Acn_Enc_String_Ascii_Null_Teminated (_,nullChars) -> Some (Acn_String_Ascii_Null_Teminated pp errCode.errCodeName ( o.maxSize.acn) nullChars codec, [errCode], []), us - | Acn_Enc_String_Ascii_External_Field_Determinant _ -> - let extField = getExternaField r deps t.id + | Acn_Enc_String_Ascii_Null_Terminated (_,nullChars) -> Some (Acn_String_Ascii_Null_Terminated pp errCode.errCodeName ( o.maxSize.acn) nullChars codec, [errCode], []), us + | Acn_Enc_String_Ascii_External_Field_Determinant _ -> + let extField = getExternalField r deps t.id Some(Acn_String_Ascii_External_Field_Determinant pp errCode.errCodeName ( o.maxSize.acn) extField codec, [errCode], []), us - | Acn_Enc_String_CharIndex_External_Field_Determinant _ -> - let extField = getExternaField r deps t.id + | Acn_Enc_String_CharIndex_External_Field_Determinant _ -> + let extField = getExternalField r deps t.id let typeDefinitionName = defOrRef.longTypedefName2 lm.lg.hasModules//getTypeDefinitionName t.id.tasInfo typeDefinition let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (o.uperCharSet.Length-1)) - let encDecStatement = + let encDecStatement = match o.uperCharSet.Length = 128 with - | false -> + | false -> let arrAsciiCodes = o.uperCharSet |> Array.map(fun x -> BigInteger (System.Convert.ToInt32 x)) - Acn_String_CharIndex_External_Field_Determinant pp errCode.errCodeName ( o.maxSize.acn) arrAsciiCodes (BigInteger o.uperCharSet.Length) extField td nBits codec + Acn_String_CharIndex_External_Field_Determinant pp errCode.errCodeName ( o.maxSize.acn) arrAsciiCodes (BigInteger o.uperCharSet.Length) extField td nBits codec | true -> Acn_IA5String_CharIndex_External_Field_Determinant pp errCode.errCodeName ( o.maxSize.acn) extField td nBits codec Some(encDecStatement, [errCode], []), us match funcBodyContent with | None -> None, ns - | Some (funcBodyContent,errCodes, localVars) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVars; bValIsUnReferenced= false; bBsIsUnReferenced=false}), ns + | Some (funcBodyContent,errCodes, localVars) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVars; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}), ns let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p us) (fun atc -> true) icd soSparkAnnotations us @@ -838,18 +792,16 @@ let createStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel let createAcnStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId : ReferenceToType) (t:Asn1AcnAst.AcnReferenceToIA5String) (us:State) = let errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None - let Acn_String_Ascii_FixSize = lm.acn.Acn_String_Ascii_FixSize - let Acn_String_Ascii_Internal_Field_Determinant = lm.acn.Acn_String_Ascii_Internal_Field_Determinant - let Acn_String_Ascii_Null_Teminated = lm.acn.Acn_String_Ascii_Null_Teminated - let Acn_String_Ascii_External_Field_Determinant = lm.acn.Acn_String_Ascii_External_Field_Determinant - let Acn_String_CharIndex_External_Field_Determinant = lm.acn.Acn_String_CharIndex_External_Field_Determinant + let Acn_String_Ascii_FixSize = lm.acn.Acn_String_Ascii_FixSize + let Acn_String_Ascii_Internal_Field_Determinant = lm.acn.Acn_String_Ascii_Internal_Field_Determinant + let Acn_String_Ascii_Null_Terminated = lm.acn.Acn_String_Ascii_Null_Terminated + let Acn_String_Ascii_External_Field_Determinant = lm.acn.Acn_String_Ascii_External_Field_Determinant + let Acn_String_CharIndex_External_Field_Determinant = lm.acn.Acn_String_CharIndex_External_Field_Determinant let Acn_IA5String_CharIndex_External_Field_Determinant = lm.acn.Acn_IA5String_CharIndex_External_Field_Determinant let typeDefinitionName = ToC2(r.args.TypePrefix + t.tasName.Value) - let callerProgramUnit = ToC typeId.ModName - - //let td = o. + let o = t.str - let uper_funcBody (errCode:ErroCode) (p:CallerScope) = + let uper_funcBody (errCode:ErrorCode) (p:CallerScope) = let td = let md = r.GetModuleByName t.modName let tas = md.GetTypeAssignmentByName t.tasName r @@ -857,9 +809,9 @@ let createAcnStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF | Asn1AcnAst.IA5String z -> (lm.lg.getStrTypeDefinition z.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) | Asn1AcnAst.NumericString z -> (lm.lg.getStrTypeDefinition z.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) | _ -> raise(SemanticError(t.tasName.Location, (sprintf "Type assignment %s.%s does not point to a string type" t.modName.Value t.modName.Value))) - let ii = typeId.SeqeuenceOfLevel + 1 + let ii = typeId.SequenceOfLevel + 1 let i = sprintf "i%d" ii - let lv = SequenceOfIndex (typeId.SeqeuenceOfLevel + 1, None) + let lv = SequenceOfIndex (typeId.SequenceOfLevel + 1, None) let charIndex = match lm.lg.uper.requires_charIndex with | false -> [] @@ -872,172 +824,161 @@ let createAcnStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF let InternalItem_string_with_alpha = lm.uper.InternalItem_string_with_alpha let str_FixedSize = lm.uper.str_FixedSize let str_VarSize = lm.uper.str_VarSize - + let initExpr = + match codec, lm.lg.decodingKind with + | Decode, Copy -> Some (lm.lg.initializeString (int o.maxSize.uper)) + | _ -> None + let pp, resultExpr = joinedOrAsIdentifier lm codec p let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (o.uperCharSet.Length-1)) let internalItem = match o.uperCharSet.Length = 128 with - | true -> InternalItem_string_no_alpha p.arg.p errCode.errCodeName i codec - | false -> + | true -> InternalItem_string_no_alpha pp errCode.errCodeName i codec + | false -> let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (o.uperCharSet.Length-1)) let arrAsciiCodes = o.uperCharSet |> Array.map(fun x -> BigInteger (System.Convert.ToInt32 x)) - InternalItem_string_with_alpha p.arg.p errCode.errCodeName td i (BigInteger (o.uperCharSet.Length-1)) arrAsciiCodes (BigInteger (o.uperCharSet.Length)) nBits codec + InternalItem_string_with_alpha pp errCode.errCodeName td i (BigInteger (o.uperCharSet.Length-1)) arrAsciiCodes (BigInteger (o.uperCharSet.Length)) nBits codec let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.uper - o.minSize.uper)) - let funcBodyContent, localVariables = + let funcBodyContent, localVariables = match o.minSize with - | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> - str_FixedSize p.arg.p typeDefinitionName i internalItem ( o.minSize.uper) nBits nBits 0I codec, charIndex@nStringLength - | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> - //printfn "%A\n" nStringLength - str_VarSize p.arg.p typeDefinitionName i internalItem ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits nBits nBits 0I codec , charIndex@nStringLength - | _ -> + | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> + str_FixedSize pp typeDefinitionName i internalItem ( o.minSize.uper) nBits nBits 0I initExpr codec, charIndex@nStringLength + | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> + str_VarSize pp typeDefinitionName i internalItem ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits nBits nBits 0I initExpr codec , charIndex@nStringLength + | _ -> let funcBodyContent,localVariables = DAstUPer.handleFragmentation lm p codec errCode ii ( o.uperMaxSizeInBits) o.minSize.uper o.maxSize.uper internalItem nBits false true funcBodyContent,charIndex@localVariables - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = lv::localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = lv::localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = let td = (lm.lg.getStrTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let funcBodyContent = + let pp, resultExpr = adaptArgument lm codec p + let funcBodyContent = match t.str.acnEncodingClass with - | Acn_Enc_String_uPER_Ascii _ -> + | Acn_Enc_String_uPER_Ascii _ -> match t.str.maxSize.uper = t.str.minSize.uper with | true -> Some (Acn_String_Ascii_FixSize pp errCode.errCodeName ( t.str.maxSize.uper) codec, [], []) - | false -> + | false -> let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.acn - o.minSize.acn)) Some (Acn_String_Ascii_Internal_Field_Determinant pp errCode.errCodeName ( t.str.maxSize.acn) ( t.str.minSize.acn) nSizeInBits codec , [], []) - | Acn_Enc_String_Ascii_Null_Teminated (_, nullChars) -> Some (Acn_String_Ascii_Null_Teminated pp errCode.errCodeName ( t.str.maxSize.acn) nullChars codec, [], []) - | Acn_Enc_String_Ascii_External_Field_Determinant _ -> - let extField = getExternaField r deps typeId + | Acn_Enc_String_Ascii_Null_Terminated (_, nullChars) -> Some (Acn_String_Ascii_Null_Terminated pp errCode.errCodeName ( t.str.maxSize.acn) nullChars codec, [], []) + | Acn_Enc_String_Ascii_External_Field_Determinant _ -> + let extField = getExternalField r deps typeId Some(Acn_String_Ascii_External_Field_Determinant pp errCode.errCodeName ( t.str.maxSize.acn) extField codec, [], []) - | Acn_Enc_String_CharIndex_External_Field_Determinant _ -> - let extField = getExternaField r deps typeId + | Acn_Enc_String_CharIndex_External_Field_Determinant _ -> + let extField = getExternalField r deps typeId let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (t.str.uperCharSet.Length-1)) - let encDecStatement = + let encDecStatement = match t.str.uperCharSet.Length = 128 with - | false -> + | false -> let arrAsciiCodes = t.str.uperCharSet |> Array.map(fun x -> BigInteger (System.Convert.ToInt32 x)) Acn_String_CharIndex_External_Field_Determinant pp errCode.errCodeName ( t.str.maxSize.acn) arrAsciiCodes (BigInteger t.str.uperCharSet.Length) extField td nBits codec | true -> Acn_IA5String_CharIndex_External_Field_Determinant pp errCode.errCodeName ( t.str.maxSize.acn) extField td nBits codec Some(encDecStatement, [], []) - | Acn_Enc_String_uPER _ -> - let x = (uper_funcBody errCode) p + | Acn_Enc_String_uPER _ -> + let x = (uper_funcBody errCode) p Some(x.funcBody, x.errCodes, x.localVariables) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes, lvs) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::errCodes |> List.distinct ; localVariables = lvs; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | Some (funcBodyContent,errCodes, lvs) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::errCodes |> List.distinct ; localVariables = lvs; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) (funcBody errCode), ns - -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = let oct_external_field = lm.acn.oct_external_field let oct_external_field_fix_size = lm.acn.oct_external_field_fix_size let oct_sqf_null_terminated = lm.acn.oct_sqf_null_terminated - let fixedSize = lm.uper.octect_FixedSize - let varSize = lm.uper.octect_VarSize + let fixedSize = lm.uper.octet_FixedSize + let varSize = lm.uper.octet_VarSize let InternalItem_oct_str = lm.uper.InternalItem_oct_str - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) let nAlignSize = 0I; - - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let funcBodyContent = + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg + let funcBodyContent = match o.acnEncodingClass with - | SZ_EC_FIXED_SIZE -> - let fncBody = - fixedSize p.arg.p (lm.lg.getAccess p.arg) o.minSize.acn codec + | SZ_EC_FIXED_SIZE -> + let fncBody = fixedSize td pp access o.minSize.acn codec Some(fncBody, [errCode],[]) - | SZ_EC_LENGTH_EMBEDDED lenSize -> - let fncBody = - varSize p.arg.p (lm.lg.getAccess p.arg) (o.minSize.acn) (o.maxSize.acn) lenSize errCode.errCodeName codec + | SZ_EC_LENGTH_EMBEDDED lenSize -> + let fncBody = varSize td pp access (o.minSize.acn) (o.maxSize.acn) lenSize errCode.errCodeName codec let nStringLength = match codec with | Encode -> [] | Decode -> [lm.lg.uper.count_var] Some(fncBody, [errCode],nStringLength) - | SZ_EC_ExternalField _ -> - let extField = getExternaField r deps t.id - let fncBody = + | SZ_EC_ExternalField _ -> + let extField = getExternalField r deps t.id + let fncBody = match o.isFixedSize with - | true -> oct_external_field_fix_size p.arg.p (lm.lg.getAccess p.arg) (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName codec - | false -> oct_external_field p.arg.p (lm.lg.getAccess p.arg) (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName codec + | true -> oct_external_field_fix_size td pp access (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName codec + | false -> oct_external_field td pp access (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName codec Some(fncBody, [errCode],[]) - | SZ_EC_TerminationPattern bitPattern -> + | SZ_EC_TerminationPattern bitPattern -> let mod8 = bitPattern.Value.Length % 8 let suffix = [1 .. mod8] |> Seq.map(fun _ -> "0") |> Seq.StrJoin "" let bitPatten8 = bitPattern.Value + suffix let byteArray = bitStringValueToByteArray bitPatten8.AsLoc - let internalItem = InternalItem_oct_str p.arg.p (lm.lg.getAccess p.arg) i errCode.errCodeName codec + let internalItem = InternalItem_oct_str pp access i errCode.errCodeName codec let noSizeMin = if o.minSize.acn=0I then None else Some ( o.minSize.acn) - let fncBody = oct_sqf_null_terminated p.arg.p (lm.lg.getAccess p.arg) i internalItem noSizeMin o.maxSize.acn byteArray bitPattern.Value.Length.AsBigInt errCode.errCodeName 8I 8I codec - let lv2 = + let fncBody = oct_sqf_null_terminated pp access i internalItem noSizeMin o.maxSize.acn byteArray bitPattern.Value.Length.AsBigInt errCode.errCodeName 8I 8I codec + let lv2 = match codec, lm.lg.acn.checkBitPatternPresentResult with - | Decode, true -> [IntegerLocalVariable ("checkBitPatternPresentResult", Some 0)] + | Decode, true -> [IntegerLocalVariable ("checkBitPatternPresentResult", Some (lm.lg.intValueToString 0I (ASN1SCC_Int8 (-128I, 127I))))] | _ -> [] Some(fncBody, [errCode],lv::lv2) - + match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) - let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) + let soSparkAnnotations = Some (sparkAnnotations lm td codec) + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us - - - - - -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (uperFunc: UPerFunction) (us:State) = let nAlignSize = 0I; let bitString_FixSize = lm.uper.bitString_FixSize let bitString_VarSize = lm.uper.bitString_VarSize - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let funcBodyContent = + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg + let funcBodyContent = match o.acnEncodingClass with - | SZ_EC_ExternalField _ -> - let createBitStringFunction_extfld (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (errCode:ErroCode) (p:CallerScope) (extField:string) (codec:CommonTypes.Codec) : (string*ErroCode list*LocalVariable list) = - let fncBody = - match o.minSize.uper = o.maxSize.uper with - | true -> lm.acn.bit_string_external_field_fixed_size p.arg.p errCode.errCodeName (lm.lg.getAccess p.arg) (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField codec - | false -> lm.acn.bit_string_external_field p.arg.p errCode.errCodeName (lm.lg.getAccess p.arg) (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField codec - (fncBody, [errCode], []) - - - let extField = getExternaField r deps t.id - let ret = createBitStringFunction_extfld t o errCode p extField codec - Some ret - | SZ_EC_TerminationPattern bitPattern -> - let createBitStringFunction_term_pat (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (errCode:ErroCode) (p:CallerScope) (codec:CommonTypes.Codec) (bitPattern:Asn1AcnAst.BitStringValue): (string*ErroCode list*LocalVariable list) = - let mod8 = bitPattern.Value.Length % 8 - let suffix = [1 .. mod8] |> Seq.map(fun _ -> "0") |> Seq.StrJoin "" - let bitPatten8 = bitPattern.Value + suffix - let byteArray = bitStringValueToByteArray bitPatten8.AsLoc - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) - let fncBody = lm.acn.bit_string_null_terminated p.arg.p errCode.errCodeName (lm.lg.getAccess p.arg) i (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) byteArray bitPattern.Value.Length.AsBigInt codec - (fncBody, [errCode], []) - - let ret = createBitStringFunction_term_pat t o errCode p codec bitPattern - - Some ret + | SZ_EC_ExternalField _ -> + let extField = getExternalField r deps t.id + let fncBody = + match o.minSize.uper = o.maxSize.uper with + | true -> lm.acn.bit_string_external_field_fixed_size td pp errCode.errCodeName access (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField codec + | false -> lm.acn.bit_string_external_field td pp errCode.errCodeName access (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField codec + Some (fncBody, [errCode], []) + | SZ_EC_TerminationPattern bitPattern -> + let mod8 = bitPattern.Value.Length % 8 + let suffix = [1 .. mod8] |> Seq.map(fun _ -> "0") |> Seq.StrJoin "" + let bitPatten8 = bitPattern.Value + suffix + let byteArray = bitStringValueToByteArray bitPatten8.AsLoc + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) + let fncBody = lm.acn.bit_string_null_terminated td pp errCode.errCodeName access i (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) byteArray bitPattern.Value.Length.AsBigInt codec + Some (fncBody, [errCode], []) | SZ_EC_FIXED_SIZE -> - let fncBody = - bitString_FixSize p.arg.p (lm.lg.getAccess p.arg) o.minSize.acn errCode.errCodeName codec + let fncBody = bitString_FixSize td pp access o.minSize.acn errCode.errCodeName codec Some(fncBody, [errCode],[]) - | SZ_EC_LENGTH_EMBEDDED nSizeInBits -> + | SZ_EC_LENGTH_EMBEDDED nSizeInBits -> let fncBody = - bitString_VarSize p.arg.p (lm.lg.getAccess p.arg) o.minSize.acn o.maxSize.acn errCode.errCodeName nSizeInBits codec + bitString_VarSize td pp access o.minSize.acn o.maxSize.acn errCode.errCodeName nSizeInBits codec let nStringLength = match codec with | Encode -> [] @@ -1045,45 +986,47 @@ let createBitStringFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF Some(fncBody, [errCode],nStringLength) match funcBodyContent with | None -> None - | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) - let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let icdFnc fieldName sPresent comments = - [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengtInBits = o.acnMinSizeInBits ;maxLengtInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] + | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) + let soSparkAnnotations = Some(sparkAnnotations lm td codec) + let icdFnc fieldName sPresent comments = + [{IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=(IcdPlainType (getASN1Name t)); sConstraint=None; minLengthInBits = o.acnMinSizeInBits ;maxLengthInBits=o.acnMaxSizeInBits;sUnits=t.unitsOfMeasure; rowType = IcdRowType.FieldRow; idxOffset = None}] let icd = {IcdArgAux.canBeEmbedded = true; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us - - - -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = let oct_sqf_null_terminated = lm.acn.oct_sqf_null_terminated let oct_sqf_external_field_fix_size = lm.acn.sqf_external_field_fix_size let external_field = lm.acn.sqf_external_field let fixedSize = lm.uper.seqOf_FixedSize let varSize = lm.uper.seqOf_VarSize - - let ii = t.id.SeqeuenceOfLevel + 1 + + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii - let lv = + let lv = match o.acnEncodingClass with | SZ_EC_FIXED_SIZE | SZ_EC_LENGTH_EMBEDDED _ //-> lm.lg.uper.seqof_lv t.id o.minSize.uper o.maxSize.uper | SZ_EC_ExternalField _ - | SZ_EC_TerminationPattern _ -> [SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None)] + | SZ_EC_TerminationPattern _ -> [SequenceOfIndex (t.id.SequenceOfLevel + 1, None)] let nAlignSize = 0I; - let typeDefinitionName = defOrRef.longTypedefName2 lm.lg.hasModules - let nIntItemMaxSize = ( child.acnMaxSizeInBits) - let funcBody (us:State) (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let nIntItemMaxSize = child.acnMaxSizeInBits + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + let funcBody (us:State) (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = joinedOrAsIdentifier lm codec p + // `childInitExpr` is used to initialize the array of elements in which we will write their decoded values + // It is only meaningful for "Copy" decoding kind, since InPlace will directly modify `p`'s array + let childInitExpr = DAstInitialize.getChildExpression lm child + let access = lm.lg.getAccess p.arg match child.getAcnFunction codec with | None -> None, us | Some chFunc -> let internalItem, ns = chFunc.funcBody us acnArgs ({p with arg = lm.lg.getArrayItem p.arg i child.isIA5String}) - let ret = + let ret = match o.acnEncodingClass with | SZ_EC_FIXED_SIZE - | SZ_EC_LENGTH_EMBEDDED _ -> + | SZ_EC_LENGTH_EMBEDDED _ -> let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.acn - o.minSize.acn)) let nStringLength = match o.minSize.uper = o.maxSize.uper, codec with @@ -1092,35 +1035,35 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted | false, Decode -> [lm.lg.uper.count_var] match internalItem with - | None -> - match o.isFixedSize with - | true -> None - | false -> - let funcBody = varSize p.arg.p (lm.lg.getAccess p.arg) typeDefinitionName i "" ( o.minSize.acn) ( o.maxSize.acn) nSizeInBits ( child.acnMinSizeInBits) nIntItemMaxSize 0I errCode.errCodeName codec - Some ({AcnFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = lv@nStringLength; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | None -> + match o.isFixedSize with + | true -> None + | false -> + let funcBody = varSize pp access td i "" o.minSize.acn o.maxSize.acn nSizeInBits child.acnMinSizeInBits nIntItemMaxSize 0I childInitExpr errCode.errCodeName codec + Some ({AcnFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = lv@nStringLength; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) - | Some internalItem -> + | Some internalItem -> let childErrCodes = internalItem.errCodes - let ret, localVariables = + let ret, localVariables = match o.isFixedSize with - | true -> fixedSize p.arg.p typeDefinitionName i internalItem.funcBody ( o.minSize.acn) ( child.acnMinSizeInBits) nIntItemMaxSize 0I codec , nStringLength - | false -> varSize p.arg.p (lm.lg.getAccess p.arg) typeDefinitionName i internalItem.funcBody ( o.minSize.acn) ( o.maxSize.acn) nSizeInBits ( child.acnMinSizeInBits) nIntItemMaxSize 0I errCode.errCodeName codec , nStringLength - Some ({AcnFuncBodyResult.funcBody = ret; errCodes = errCode::childErrCodes; localVariables = lv@(internalItem.localVariables@localVariables); bValIsUnReferenced= false; bBsIsUnReferenced=false}) + | true -> fixedSize pp td i internalItem.funcBody o.minSize.acn child.acnMinSizeInBits nIntItemMaxSize 0I childInitExpr codec, nStringLength + | false -> varSize pp access td i internalItem.funcBody o.minSize.acn o.maxSize.acn nSizeInBits child.acnMinSizeInBits nIntItemMaxSize 0I childInitExpr errCode.errCodeName codec, nStringLength + Some ({AcnFuncBodyResult.funcBody = ret; errCodes = errCode::childErrCodes; localVariables = lv@(internalItem.localVariables@localVariables); bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) - | SZ_EC_ExternalField _ -> + | SZ_EC_ExternalField _ -> match internalItem with | None -> None | Some internalItem -> let localVariables = internalItem.localVariables let childErrCodes = internalItem.errCodes let internalItem = internalItem.funcBody - let extField = getExternaField r deps t.id - let funcBodyContent = + let extField = getExternalField r deps t.id + let funcBodyContent = match o.isFixedSize with - | true -> oct_sqf_external_field_fix_size p.arg.p (lm.lg.getAccess p.arg) i internalItem (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits codec - | false -> external_field p.arg.p (lm.lg.getAccess p.arg) i internalItem (if o.minSize.acn=0I then None else Some ( o.minSize.acn)) ( o.maxSize.acn) extField nAlignSize errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits codec - Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::childErrCodes; localVariables = lv@localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) - | SZ_EC_TerminationPattern bitPattern -> + | true -> oct_sqf_external_field_fix_size td pp access i internalItem (if o.minSize.acn=0I then None else Some o.minSize.acn) o.maxSize.acn extField nAlignSize errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits childInitExpr codec + | false -> external_field td pp access i internalItem (if o.minSize.acn=0I then None else Some o.minSize.acn) o.maxSize.acn extField nAlignSize errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits childInitExpr codec + Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::childErrCodes; localVariables = lv@localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) + | SZ_EC_TerminationPattern bitPattern -> match internalItem with | None -> None | Some internalItem -> @@ -1132,132 +1075,138 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted let childErrCodes = internalItem.errCodes let internalItem = internalItem.funcBody let noSizeMin = if o.minSize.acn=0I then None else Some ( o.minSize.acn) - let funcBodyContent = oct_sqf_null_terminated p.arg.p (lm.lg.getAccess p.arg) i internalItem noSizeMin o.maxSize.acn byteArray bitPattern.Value.Length.AsBigInt errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits codec + let funcBodyContent = oct_sqf_null_terminated pp access i internalItem noSizeMin o.maxSize.acn byteArray bitPattern.Value.Length.AsBigInt errCode.errCodeName o.child.acnMinSizeInBits o.child.acnMaxSizeInBits codec - let lv2 = + let lv2 = match codec, lm.lg.acn.checkBitPatternPresentResult with - | Decode, true -> [IntegerLocalVariable ("checkBitPatternPresentResult", Some 0)] + | Decode, true -> [IntegerLocalVariable ("checkBitPatternPresentResult", Some (lm.lg.intValueToString 0I (ASN1SCC_Int8 (-128I, 127I))))] | _ -> [] - Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::childErrCodes; localVariables = lv2@lv@localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCode::childErrCodes; localVariables = lv2@lv@localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=None}) ret,ns - let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) + let soSparkAnnotations = Some(sparkAnnotations lm td codec) - let icdFnc fieldName sPresent comments = + let icdFnc fieldName sPresent comments = let x = child.icdFunction - let lengthRow, terminationPatern = + let lengthRow, terminationPattern = match o.acnEncodingClass with - | SZ_EC_LENGTH_EMBEDDED _ -> + | SZ_EC_LENGTH_EMBEDDED _ -> let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.acn - o.minSize.acn)) - [{IcdRow.fieldName = "Length"; comments = [$"The number of items"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengtInBits = nSizeInBits ;maxLengtInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some 1}], [] - | SZ_EC_FIXED_SIZE + [{IcdRow.fieldName = "Length"; comments = [$"The number of items"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengthInBits = nSizeInBits ;maxLengthInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some 1}], [] + | SZ_EC_FIXED_SIZE | SZ_EC_ExternalField _ -> [], [] - | SZ_EC_TerminationPattern bitPattern -> + | SZ_EC_TerminationPattern bitPattern -> let nSizeInBits = bitPattern.Value.Length.AsBigInt - [], [{IcdRow.fieldName = "Length"; comments = [$"Termination pattern {bitPattern.Value}"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengtInBits = nSizeInBits ;maxLengtInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some (int (o.maxSize.acn+1I))}] + [], [{IcdRow.fieldName = "Length"; comments = [$"Termination pattern {bitPattern.Value}"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengthInBits = nSizeInBits ;maxLengthInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some (int (o.maxSize.acn+1I))}] match x.canBeEmbedded with - | true -> + | true -> let chRows = (x.createRowsFunc "Item #1" "always" []) |> List.map(fun r -> {r with idxOffset = Some (lengthRow.Length + 1)}) - let lastChrows = chRows |> List.map(fun r -> {r with fieldName = $"Item #{o.maxSize.acn}"; idxOffset = Some ((int o.maxSize.acn)+lengthRow.Length)}) - lengthRow@chRows@[THREE_DOTS]@lastChrows@terminationPatern + let lastChRows = chRows |> List.map(fun r -> {r with fieldName = $"Item #{o.maxSize.acn}"; idxOffset = Some ((int o.maxSize.acn)+lengthRow.Length)}) + lengthRow@chRows@[THREE_DOTS]@lastChRows@terminationPattern | false -> let sType = TypeHash x.typeAss.hash - let a1 = {IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=sType; sConstraint=None; minLengtInBits = t.acnMinSizeInBits; maxLengtInBits=t.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some (lengthRow.Length + 1)} + let a1 = {IcdRow.fieldName = fieldName; comments = comments; sPresent=sPresent;sType=sType; sConstraint=None; minLengthInBits = t.acnMinSizeInBits; maxLengthInBits=t.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = Some (lengthRow.Length + 1)} let a2 = {a1 with idxOffset = Some ((int o.maxSize.acn)+lengthRow.Length)} [a1;THREE_DOTS;a2] - if (t.id.AsString = "PUS-C.TC.one-tc.manage-memory.pus-6-1-memory-dump.a") then - printfn "debug" - let sExtraComment = match o.acnEncodingClass with - | Asn1AcnAst.SZ_EC_FIXED_SIZE -> $"Length is fixed to {o.maxSize.acn} elements (no length determinant is needed)." + | Asn1AcnAst.SZ_EC_FIXED_SIZE -> $"Length is fixed to {o.maxSize.acn} elements (no length determinant is needed)." | Asn1AcnAst.SZ_EC_LENGTH_EMBEDDED _ -> if o.maxSize.acn <2I then "The array contains a single element." else "" - | Asn1AcnAst.SZ_EC_ExternalField relPath -> $"Length is determined by the external field: %s{relPath.AsString}" - | Asn1AcnAst.SZ_EC_TerminationPattern bitPattern -> $"Length is determined by the stop marker '%s{bitPattern.Value}'" + | Asn1AcnAst.SZ_EC_ExternalField relPath -> $"Length is determined by the external field: %s{relPath.AsString}" + | Asn1AcnAst.SZ_EC_TerminationPattern bitPattern -> $"Length is determined by the stop marker '%s{bitPattern.Value}'" + + - - let icd = {IcdArgAux.canBeEmbedded = false; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=[sExtraComment]; scope="type"; name= None} createAcnFunction r lm codec t typeDefinition isValidFunc funcBody (fun atc -> true) icd soSparkAnnotations us +let initExpr (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (t: Asn1AcnAst.AcnInsertedType): string = + match t with + | AcnInteger _ -> "0" + | AcnNullType _ -> "0" + | AcnBoolean _ -> lm.lg.FalseLiteral + | AcnReferenceToIA5String s -> lm.lg.initializeString (int s.str.maxSize.uper) + | AcnReferenceToEnumerated e -> + lm.lg.getNamedItemBackendName (Some (defOrRef r m e)) e.enumerated.items.Head let rec handleSingleUpdateDependency (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (d:AcnDependency) (us:State) = - let presenceDependency = lm.acn.PresenceDependency - let sizeDependency = lm.acn.SizeDependency - let sizeDependencyFixedSize = lm.acn.SizeDependencyFixedSize + let presenceDependency = lm.acn.PresenceDependency + let sizeDependency = lm.acn.SizeDependency + let sizeDependencyFixedSize = lm.acn.SizeDependencyFixedSize let sizeDep_oct_str_containing = lm.acn.SizeDependency_oct_str_containing - let getSizeableSize = lm.acn.getSizeableSize - let getStringSize = lm.acn.getStringSize + let getSizeableSize = lm.acn.getSizeableSize + let getStringSize = lm.acn.getStringSize let choiceDependencyPres = lm.acn.ChoiceDependencyPres let choiceDependencyIntPres_child = lm.acn.ChoiceDependencyIntPres_child let choiceDependencyStrPres_child = lm.acn.ChoiceDependencyStrPres_child let choiceDependencyEnum = lm.acn.ChoiceDependencyEnum let choiceDependencyEnum_Item = lm.acn.ChoiceDependencyEnum_Item let checkAccessPath = lm.acn.checkAccessPath - match d.dependencyKind with - | AcnDepRefTypeArgument acnPrm -> + | AcnDepRefTypeArgument acnPrm -> let prmUpdateStatement, ns1 = getUpdateFunctionUsedInEncoding r deps lm m acnPrm.id us match prmUpdateStatement with | None -> None, ns1 - | Some prmUpdateStatement -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = - prmUpdateStatement.updateAcnChildFnc typedefName vTarget pSrcRoot - + | Some prmUpdateStatement -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + prmUpdateStatement.updateAcnChildFnc child vTarget pSrcRoot + Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=prmUpdateStatement.errCodes; testCaseFnc = prmUpdateStatement.testCaseFnc; localVariables=[]}), ns1 - | AcnDepSizeDeterminant (minSize, maxSize, szAcnProp) -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + | AcnDepSizeDeterminant (minSize, maxSize, szAcnProp) -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let v = lm.lg.getValue vTarget.arg let pSizeable, checkPath = getAccessFromScopeNodeList d.asn1Type false lm pSrcRoot - let updateStatement = + let updateStatement = match minSize.acn = maxSize.acn with - | true -> sizeDependencyFixedSize (lm.lg.getValue vTarget.arg) minSize.acn - | false -> sizeDependency (lm.lg.getValue vTarget.arg) (getSizeableSize pSizeable.arg.p (lm.lg.getAccess pSizeable.arg)) minSize.uper maxSize.uper false typedefName + | true -> sizeDependencyFixedSize v minSize.acn + | false -> sizeDependency v (getSizeableSize (pSizeable.arg.joined lm.lg) (lm.lg.getAccess pSizeable.arg)) minSize.uper maxSize.uper false child.typeDefinitionBodyWithinSeq match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = atc.testCaseTypeIDsMap.TryFind d.asn1Type Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[]; testCaseFnc=testCaseFnc; localVariables=[]}), us - | AcnDepSizeDeterminant_bit_oct_str_containt o -> - let baseTypeDefinitionName = + | AcnDepSizeDeterminant_bit_oct_str_contain o -> + let baseTypeDefinitionName = match lm.lg.hasModules with - | false -> ToC2(r.args.TypePrefix + o.tasName.Value) - | true -> + | false -> ToC2(r.args.TypePrefix + o.tasName.Value) + | true -> match m.Name.Value = o.modName.Value with - | true -> ToC2(r.args.TypePrefix + o.tasName.Value) - | false -> (ToC o.modName.Value) + "." + ToC2(r.args.TypePrefix + o.tasName.Value) + | true -> ToC2(r.args.TypePrefix + o.tasName.Value) + | false -> (ToC o.modName.Value) + "." + ToC2(r.args.TypePrefix + o.tasName.Value) let baseFncName = baseTypeDefinitionName + "_ACN" + Encode.suffix let sReqBytesForUperEncoding = sprintf "%s_REQUIRED_BYTES_FOR_ACN_ENCODING" baseTypeDefinitionName let asn1TypeD = us.newTypesMap[d.asn1Type] :?> Asn1Type let asn1TypeD = match asn1TypeD.Kind with ReferenceType o -> o.resolvedType.ActualType | _ -> asn1TypeD - let errCodes0, localVariables0, ns = + let errCodes0, localVariables0, ns = match asn1TypeD.acnEncFunction with - | Some f -> - let fncBdRes, ns = f.funcBody us [] {CallerScope.modName = ""; arg = VALUE "dummy"} + | Some f -> + let fncBdRes, ns = f.funcBody us [] {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} match fncBdRes with | Some x -> x.errCodes, x.localVariables, ns | None -> [], [], us | None -> [], [], us - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let v = lm.lg.getValue vTarget.arg let pSizeable, checkPath = getAccessFromScopeNodeList d.asn1Type false lm pSrcRoot - let sComment= + let sComment= match asn1TypeD.acnEncFunction with - | Some f -> + | Some f -> let fncBdRes, _ = f.funcBody us [] pSizeable match fncBdRes with | None -> "" | Some a -> a.funcBody | None -> "" - - let updateStatement = sizeDep_oct_str_containing (lm.lg.getParamValue o.resolvedType pSizeable.arg Encode) baseFncName sReqBytesForUperEncoding (lm.lg.getValue vTarget.arg) (match o.encodingOptions with Some eo -> eo.octOrBitStr = ContainedInOctString | None -> false) sComment + + let updateStatement = sizeDep_oct_str_containing (lm.lg.getParamValue o.resolvedType pSizeable.arg Encode) baseFncName sReqBytesForUperEncoding v (match o.encodingOptions with Some eo -> eo.octOrBitStr = ContainedInOctString | None -> false) sComment match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = atc.testCaseTypeIDsMap.TryFind d.asn1Type let localVars = lm.lg.acn.getAcnDepSizeDeterminantLocVars sReqBytesForUperEncoding @@ -1265,38 +1214,39 @@ let rec handleSingleUpdateDependency (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.Acn Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=errCodes0; testCaseFnc=testCaseFnc; localVariables= localVariables0@localVars}), ns | AcnDepIA5StringSizeDeterminant (minSize, maxSize, szAcnProp) -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let v = lm.lg.getValue vTarget.arg let pSizeable, checkPath = getAccessFromScopeNodeList d.asn1Type true lm pSrcRoot - let updateStatement = sizeDependency (lm.lg.getValue vTarget.arg) (getStringSize pSizeable.arg.p) minSize.uper maxSize.uper true typedefName + let updateStatement = sizeDependency v (getStringSize (pSizeable.arg.joined lm.lg)) minSize.uper maxSize.uper true child.typeDefinitionBodyWithinSeq match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = atc.testCaseTypeIDsMap.TryFind d.asn1Type Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[]; testCaseFnc=testCaseFnc; localVariables=[]}), us - | AcnDepPresenceBool -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + | AcnDepPresenceBool -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = let v = lm.lg.getValue vTarget.arg let parDecTypeSeq = match d.asn1Type with | ReferenceToType (nodes) -> ReferenceToType (nodes |> List.rev |> List.tail |> List.rev) let pDecParSeq, checkPath = getAccessFromScopeNodeList parDecTypeSeq false lm pSrcRoot - let updateStatement = presenceDependency v (pDecParSeq.arg.p) (lm.lg.getAccess pDecParSeq.arg) (ToC d.asn1Type.lastItem) + let updateStatement = presenceDependency v (pDecParSeq.arg.joined lm.lg) (lm.lg.getAccess pDecParSeq.arg) (ToC d.asn1Type.lastItem) match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = match atc.testCaseTypeIDsMap.TryFind(d.asn1Type) with | Some _ -> Some TcvComponentPresent | None -> Some TcvComponentAbsent Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[]; testCaseFnc=testCaseFnc; localVariables=[]}), us - | AcnDepPresence (relPath, chc) -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + | AcnDepPresence (relPath, chc) -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = let v = lm.lg.getValue vTarget.arg let choicePath, checkPath = getAccessFromScopeNodeList d.asn1Type false lm pSrcRoot - let arrsChildUpdates = - chc.children |> - List.map(fun ch -> + let arrsChildUpdates = + chc.children |> + List.map(fun ch -> let pres = ch.acnPresentWhenConditions |> Seq.find(fun x -> x.relativePath = relPath) let presentWhenName = match ST.lang with @@ -1305,85 +1255,80 @@ let rec handleSingleUpdateDependency (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.Acn match pres with | PresenceInt (_, intVal) -> choiceDependencyIntPres_child v presentWhenName intVal.Value | PresenceStr (_, strVal) -> raise(SemanticError(strVal.Location, "Unexpected presence condition. Expected integer, found string"))) - let updateStatement = choiceDependencyPres choicePath.arg.p (lm.lg.getAccess choicePath.arg) arrsChildUpdates + let updateStatement = choiceDependencyPres v (choicePath.arg.joined lm.lg) (lm.lg.getAccess choicePath.arg) arrsChildUpdates match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = - let updateValues = - chc.children |> + let updateValues = + chc.children |> List.filter(fun ch -> atc.testCaseTypeIDsMap.ContainsKey ch.Type.id) |> - List.choose(fun ch -> + List.choose(fun ch -> let pres = ch.acnPresentWhenConditions |> Seq.find(fun x -> x.relativePath = relPath) match pres with | PresenceInt (_, intVal) -> Some (TcvChoiceAlternativePresentWhenInt intVal.Value) - | PresenceStr (_, strVal) -> None) + | PresenceStr (_, strVal) -> None) match updateValues with | v1::[] -> Some v1 | _ -> None Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[] ; testCaseFnc=testCaseFnc; localVariables=[]}), us - | AcnDepPresenceStr (relPath, chc, str) -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + | AcnDepPresenceStr (relPath, chc, str) -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = let v = lm.lg.getValue vTarget.arg let choicePath, checkPath = getAccessFromScopeNodeList d.asn1Type false lm pSrcRoot - let arrsChildUpdates = - chc.children |> - List.map(fun ch -> - let pres = ch.acnPresentWhenConditions |> Seq.find(fun x -> x.relativePath = relPath) + let arrsChildUpdates = + chc.children |> + List.map(fun ch -> + let pres = ch.acnPresentWhenConditions |> Seq.find(fun x -> x.relativePath = relPath) let presentWhenName = match ST.lang with | Scala -> chc.typeDef[Scala].typeName + "." + ch.presentWhenName | _ -> ch.presentWhenName match pres with - | PresenceInt (_, intVal) -> + | PresenceInt (_, intVal) -> raise(SemanticError(intVal.Location, "Unexpected presence condition. Expected string, found integer")) - //choiceDependencyIntPres_child v ch.presentWhenName intVal.Value - | PresenceStr (_, strVal) -> - let arrNuls = [0 .. ((int str.maxSize.acn)- strVal.Value.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) - choiceDependencyStrPres_child v presentWhenName strVal.Value arrNuls) - let updateStatement = choiceDependencyPres choicePath.arg.p (lm.lg.getAccess choicePath.arg) arrsChildUpdates + | PresenceStr (_, strVal) -> + let arrNulls = [0 .. ((int str.maxSize.acn)- strVal.Value.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) + choiceDependencyStrPres_child v presentWhenName strVal.Value arrNulls) + let updateStatement = choiceDependencyPres v (choicePath.arg.joined lm.lg) (lm.lg.getAccess choicePath.arg) arrsChildUpdates match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = - let updateValues = - chc.children |> + let updateValues = + chc.children |> List.filter(fun ch -> atc.testCaseTypeIDsMap.ContainsKey ch.Type.id) |> - List.choose(fun ch -> + List.choose(fun ch -> let pres = ch.acnPresentWhenConditions |> Seq.find(fun x -> x.relativePath = relPath) match pres with | PresenceInt (_, intVal) -> None - | PresenceStr (_, strVal) -> Some (TcvChoiceAlternativePresentWhenStr strVal.Value)) + | PresenceStr (_, strVal) -> Some (TcvChoiceAlternativePresentWhenStr strVal.Value)) match updateValues with | v1::[] -> Some v1 | _ -> None Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[]; testCaseFnc = testCaseFnc; localVariables=[]}), us - | AcnDepChoiceDeteterminant (enm,chc) -> - let updateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + | AcnDepChoiceDeterminant (enm, chc, isOptional) -> + let updateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = let v = lm.lg.getValue vTarget.arg let choicePath, checkPath = getAccessFromScopeNodeList d.asn1Type false lm pSrcRoot - let defOrRef (a:Asn1AcnAst.ReferenceToEnumerated) = - match m.Name.Value = a.modName with - | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} - | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName); typedefName = ToC (r.args.TypePrefix + a.tasName) ; definedInRtl = false} - - let arrsChildUpdates = - chc.children |> + let arrsChildUpdates = + chc.children |> List.map(fun ch -> let enmItem = enm.enm.items |> List.find(fun itm -> itm.Name.Value = ch.Name.Value) let choiceName = chc.typeDef[Scala].typeName - choiceDependencyEnum_Item v ch.presentWhenName choiceName (lm.lg.getNamedItemBackendName (Some (defOrRef enm)) enmItem)) - let updateStatement = choiceDependencyEnum choicePath.arg.p (lm.lg.getAccess choicePath.arg) arrsChildUpdates + choiceDependencyEnum_Item v ch.presentWhenName choiceName (lm.lg.getNamedItemBackendName (Some (defOrRef2 r m enm)) enmItem) isOptional) + let updateStatement = choiceDependencyEnum v (choicePath.arg.joined lm.lg) (lm.lg.getAccess choicePath.arg) arrsChildUpdates isOptional (initExpr r lm m child.Type) + // TODO: !!!!! let updateStatement = match ST.lang with | Scala -> match checkPath.Length > 0 with - | true -> (sprintf "var %s = %s.%s\n%s" choicePath.arg.p (checkPath[0].Replace("isInstanceOf", "asInstanceOf")) choicePath.arg.p updateStatement) - | false -> updateStatement + | true -> (sprintf "var %s = %s.%s\n%s" (choicePath.arg.joined lm.lg) (checkPath[0].Replace("isInstanceOf", "asInstanceOf")) (choicePath.arg.joined lm.lg) updateStatement) + | false -> updateStatement | _ -> updateStatement match checkPath with | [] -> updateStatement - | _ -> checkAccessPath checkPath updateStatement + | _ -> checkAccessPath checkPath updateStatement v (initExpr r lm m child.Type) let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = atc.testCaseTypeIDsMap.TryFind d.asn1Type Some ({AcnChildUpdateResult.updateAcnChildFnc = updateFunc; errCodes=[] ; testCaseFnc=testCaseFnc; localVariables=[]}), us @@ -1392,70 +1337,90 @@ and getUpdateFunctionUsedInEncoding (r: Asn1AcnAst.AstRoot) (deps: Asn1AcnAst.Ac let multiAcnUpdate = lm.acn.MultiAcnUpdate match deps.acnDependencies |> List.filter(fun d -> d.determinant.id = acnChildOrAcnParameterId) with - | [] -> + | [] -> None, us - | d1::[] -> + | d1::[] -> let ret, ns = handleSingleUpdateDependency r deps lm m d1 us ret, ns - | d1::dds -> + | d1::dds -> let _errCodeName = ToC ("ERR_ACN" + (Encode.suffix.ToUpper()) + "_UPDATE_" + ((acnChildOrAcnParameterId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, us = getNextValidErrorCode us _errCodeName None let ds = d1::dds let c_name0 = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) 0 - let localVars (typedefName :string) = - ds |> - List.mapi(fun i d1 -> + let localVars (child: AcnChild) = + ds |> + List.mapi(fun i d1 -> let c_name = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) i - let typegetDeterminantTypeDefinitionBodyWithinSeq = typedefName // getDeterminantTypeDefinitionBodyWithinSeq r l d1.determinant - [AcnInsertedChild (c_name, typegetDeterminantTypeDefinitionBodyWithinSeq, ""); BooleanLocalVariable (c_name+"_is_initialized", Some false)]) |> + let childLv = + if lm.lg.decodingKind = Copy then [] + else [AcnInsertedChild (c_name, child.typeDefinitionBodyWithinSeq, child.initExpression)] + let initLv = + if lm.lg.usesWrappedOptional then [] + else [BooleanLocalVariable (c_name+"_is_initialized", Some lm.lg.FalseLiteral)] + childLv@initLv) |> List.collect(fun lvList -> lvList |> List.map (fun lv -> lm.lg.getLocalVariableDeclaration lv)) let localUpdateFuns,ns = ds |> - List.fold(fun (updates, ns) d1 -> - let f1, nns = handleSingleUpdateDependency r deps lm m d1 ns + List.fold(fun (updates, ns) d1 -> + let f1, nns = handleSingleUpdateDependency r deps lm m d1 ns updates@[f1], nns) ([],us) let restErrCodes = localUpdateFuns |> List.choose id |> List.collect(fun z -> z.errCodes) let restLocalVariables = localUpdateFuns |> List.choose id |> List.collect(fun z -> z.localVariables) - let multiUpdateFunc (typedefName :string) (vTarget : CallerScope) (pSrcRoot : CallerScope) = + let multiUpdateFunc (child: AcnChild) (vTarget : CallerScope) (pSrcRoot : CallerScope) = let v = lm.lg.getValue vTarget.arg - let arrsLocalUpdateStatements = - localUpdateFuns |> - List.mapi(fun i fn -> + let arrsLocalUpdateStatements = + localUpdateFuns |> + List.mapi(fun i fn -> let c_name = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) i - let lv = {CallerScope.modName = vTarget.modName; arg = VALUE c_name} + let lv = {CallerScope.modName = vTarget.modName; arg = Selection.valueEmptyPath c_name} match fn with | None -> None - | Some fn -> Some(fn.updateAcnChildFnc typedefName lv pSrcRoot)) |> + | Some fn -> Some(fn.updateAcnChildFnc child lv pSrcRoot)) |> List.choose id - let v0 = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) 0 + + let isAlwaysInit (d: AcnDependency): bool = + match d.dependencyKind with + | AcnDepRefTypeArgument p -> + // last item is the determinant, and the second-to-last is the field referencing the determinant + not p.id.dropLast.lastItemIsOptional + | AcnDepChoiceDeterminant (_, c, isOpt) -> not isOpt + | _ -> true + + let firstAlwaysInit = ds |> List.tryFind isAlwaysInit let arrsGetFirstIntValue = - ds |> - List.mapi (fun i d -> - let cmp = getDeterminantTypeUpdateMacro r lm d.determinant + let ds2 = + match firstAlwaysInit with + | Some fst when lm.lg.usesWrappedOptional -> [fst] + | _ -> ds + ds2 |> + List.mapi (fun i d -> + let cmp = getDeterminantTypeUpdateMacro lm d.determinant let vi = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) i - cmp v vi (i=0) ) - let arrsLocalCheckEquality = - ds |> - List.mapi (fun i d -> - let cmp = getDeterminantTypeCheckEqual r lm d.determinant + let choicePath, _ = getAccessFromScopeNodeList d.asn1Type d.dependencyKind.isString lm pSrcRoot + cmp v vi (choicePath.arg.joined lm.lg) (i=0) (ds2.Length = 1)) + let arrsLocalCheckEquality = + ds |> + List.mapi (fun i d -> + let cmp = getDeterminantTypeCheckEqual lm d.determinant let vi = sprintf "%s%02d" (getAcnDeterminantName acnChildOrAcnParameterId) i - cmp v vi ) - let updateStatement = multiAcnUpdate vTarget.arg.p c_name0 (errCode.errCodeName ) (localVars typedefName) arrsLocalUpdateStatements arrsGetFirstIntValue arrsLocalCheckEquality + let choicePath, _ = getAccessFromScopeNodeList d.asn1Type d.dependencyKind.isString lm pSrcRoot + cmp v vi (choicePath.arg.joined lm.lg) (isAlwaysInit d)) + let updateStatement = multiAcnUpdate (vTarget.arg.joined lm.lg) c_name0 (errCode.errCodeName) (localVars child) arrsLocalUpdateStatements arrsGetFirstIntValue firstAlwaysInit.IsSome arrsLocalCheckEquality (initExpr r lm m child.Type) updateStatement let testCaseFnc (atc:AutomaticTestCase) : TestCaseValue option = let updateValues = localUpdateFuns |> List.map(fun z -> match z with None -> None | Some res -> res.testCaseFnc atc) match updateValues |> Seq.exists(fun z -> z.IsNone) with | true -> None //at least one update is not present - | false -> + | false -> match updateValues |> List.choose id with | [] -> None - | u1::us -> + | u1::us -> match us |> Seq.exists(fun z -> z <> u1) with | true -> None | false -> Some u1 - + let ret = Some(({AcnChildUpdateResult.updateAcnChildFnc = multiUpdateFunc; errCodes=errCode::restErrCodes ; testCaseFnc = testCaseFnc; localVariables = restLocalVariables})) ret, ns @@ -1469,40 +1434,51 @@ type private HandleChild_Aux = { statementKind : AcnSequenceStatement acnPresenceStatement : string option localVariableList : LocalVariable list - errCodeList : ErroCode list + errCodeList : ErrorCode list } -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (acnPrms:DastAcnParameter list) (us:State) = +type private SequenceChildStmt = { + acnStatement: AcnSequenceStatement + body: string option + lvs: LocalVariable list + errCodes: ErrorCode list +} +type private SequenceChildResult = { + stmts: SequenceChildStmt list + resultExpr: string option + existVar: string option +} + +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (acnPrms:DastAcnParameter list) (us:State) = (* 1. all Acn inserted children are declared as local variables in the encoded and decode functions (declaration step) - 2. all Acn inserted children must be initialized appropriatelly in the encoding phase - 3. + 2. all Acn inserted children must be initialized appropriately in the encoding phase + 3. *) - // stg macros - let sequence_presense_optChild = lm.acn.sequence_presense_optChild - let sequence_presense_optChild_pres_bool = lm.acn.sequence_presense_optChild_pres_bool - let sequence_presense_optChild_pres_acn_expression = lm.acn.sequence_presense_optChild_pres_acn_expression - let sequence_mandatory_child = lm.acn.sequence_mandatory_child - let sequence_optional_child = lm.acn.sequence_optional_child - let sequence_always_present_child = lm.acn.sequence_always_present_child - let sequence_always_absent_child = lm.acn.sequence_always_absent_child - let sequence_default_child = lm.acn.sequence_default_child - let sequence_acn_child = lm.acn.sequence_acn_child - let sequence_call_post_encoding_function = lm.acn.sequence_call_post_encoding_function - let sequence_call_post_decoding_validator = lm.acn.sequence_call_post_decoding_validator - let sequence_save_bitStream_start = lm.acn.sequence_save_bitStream_start + let sequence_presence_optChild = lm.acn.sequence_presence_optChild + let sequence_presence_optChild_pres_bool = lm.acn.sequence_presence_optChild_pres_bool + let sequence_presence_optChild_pres_acn_expression = lm.acn.sequence_presence_optChild_pres_acn_expression + let sequence_mandatory_child = lm.acn.sequence_mandatory_child + let sequence_optional_child = lm.acn.sequence_optional_child + let sequence_always_present_child = lm.acn.sequence_always_present_child + let sequence_always_absent_child = lm.acn.sequence_always_absent_child + let sequence_default_child = lm.acn.sequence_default_child + let sequence_acn_child = lm.acn.sequence_acn_child + let sequence_call_post_encoding_function = lm.acn.sequence_call_post_encoding_function + let sequence_call_post_decoding_validator = lm.acn.sequence_call_post_decoding_validator + let sequence_save_bitStream_start = lm.acn.sequence_save_bitStream_start let bitStreamName = lm.lg.bitStreamName let acnExpressionToBackendExpression (seq:Asn1AcnAst.Sequence) (pSeq:CallerScope) (exp:AcnExpression) = let unaryNotOperator = lm.lg.unaryNotOperator - let modOp = lm.lg.modOp - let eqOp = lm.lg.eqOp - let neqOp = lm.lg.neqOp - let andOp = lm.lg.andOp - let orOp = lm.lg.orOp + let modOp = lm.lg.modOp + let eqOp = lm.lg.eqOp + let neqOp = lm.lg.neqOp + let andOp = lm.lg.andOp + let orOp = lm.lg.orOp - let printUnary op chExpPriority expStr minePriority = + let printUnary op chExpPriority expStr minePriority = minePriority, if chExpPriority >= minePriority then sprintf "%s(%s)" op expStr else sprintf "%s%s" op expStr let printBinary op (chExpPriority1, expStr1) (chExpPriority2, expStr2) minePriority = minePriority, (if chExpPriority1 >= minePriority then "(" + expStr1 + ")" else expStr1 ) + " " + op + " " + (if chExpPriority2 >= minePriority then "(" + expStr2 + ")" else expStr2 ) @@ -1513,17 +1489,17 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi | [] -> raise(BugErrorException "empty relative path") | x1::xs -> match seq.children |> Seq.tryFind(fun c -> c.Name = x1) with - | None -> + | None -> raise (SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (lp |> Seq.StrJoin ".")))) - | Some ch -> + | Some ch -> match ch with | Asn1AcnAst.AcnChild ch -> raise (SemanticError(x1.Location, (sprintf "Invalid reference '%s'. Expecting an ASN.1 child" (lp |> Seq.StrJoin ".")))) - | Asn1AcnAst.Asn1Child ch -> + | Asn1AcnAst.Asn1Child ch -> match ch.Type.ActualType.Kind with - | Asn1AcnAst.Integer _ - | Asn1AcnAst.Real _ - | Asn1AcnAst.Boolean _ -> {pSeq with arg = lm.lg.getSeqChild pSeq.arg (lm.lg.getAsn1ChildBackendName0 ch) false false} - | Asn1AcnAst.Sequence s when xs.Length > 1 -> getChildResult s {pSeq with arg = lm.lg.getSeqChild pSeq.arg (lm.lg.getAsn1ChildBackendName0 ch) false false} (RelativePath xs) + | Asn1AcnAst.Integer _ + | Asn1AcnAst.Real _ + | Asn1AcnAst.Boolean _ -> {pSeq with arg = lm.lg.getSeqChild pSeq.arg (lm.lg.getAsn1ChildBackendName0 ch) false ch.Optionality.IsSome} + | Asn1AcnAst.Sequence s when xs.Length > 1 -> getChildResult s {pSeq with arg = lm.lg.getSeqChild pSeq.arg (lm.lg.getAsn1ChildBackendName0 ch) false ch.Optionality.IsSome} (RelativePath xs) | _ -> raise (SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (lp |> Seq.StrJoin ".")))) @@ -1535,74 +1511,79 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi (fun i s -> ( (0, i.Value.ToString().ToLower()) , 0)) (fun lf s -> let plf = getChildResult seq pSeq lf - (0, plf.arg.p) , 0) + (0, (plf.arg.joined lm.lg)) , 0) (fun loc (chExpPriority, expStr) s -> printUnary unaryNotOperator chExpPriority expStr 1, 0) //NotUnaryExpression (fun loc (chExpPriority, expStr) s -> printUnary "-" chExpPriority expStr 1, 0)//MinusUnaryExpression - (fun l e1 e2 s -> printBinary "+" e1 e2 3, 0 ) - (fun l e1 e2 s -> printBinary "-" e1 e2 3, 0 ) - (fun l e1 e2 s -> printBinary "*" e1 e2 2, 0 ) - (fun l e1 e2 s -> printBinary "/" e1 e2 2, 0 ) - (fun l e1 e2 s -> printBinary modOp e1 e2 2, 0 ) - (fun l e1 e2 s -> printBinary "<=" e1 e2 4, 0 ) - (fun l e1 e2 s -> printBinary "<" e1 e2 4, 0 ) - (fun l e1 e2 s -> printBinary ">=" e1 e2 4, 0 ) - (fun l e1 e2 s -> printBinary ">" e1 e2 4, 0 ) - (fun l e1 e2 s -> printBinary eqOp e1 e2 5, 0 ) - (fun l e1 e2 s -> printBinary neqOp e1 e2 5, 0 ) - (fun lc e1 e2 s -> printBinary andOp e1 e2 6, 0 ) - (fun lc e1 e2 s -> printBinary orOp e1 e2 6, 0 ) + (fun l e1 e2 s -> printBinary "+" e1 e2 3, 0 ) + (fun l e1 e2 s -> printBinary "-" e1 e2 3, 0 ) + (fun l e1 e2 s -> printBinary "*" e1 e2 2, 0 ) + (fun l e1 e2 s -> printBinary "/" e1 e2 2, 0 ) + (fun l e1 e2 s -> printBinary modOp e1 e2 2, 0 ) + (fun l e1 e2 s -> printBinary "<=" e1 e2 4, 0 ) + (fun l e1 e2 s -> printBinary "<" e1 e2 4, 0 ) + (fun l e1 e2 s -> printBinary ">=" e1 e2 4, 0 ) + (fun l e1 e2 s -> printBinary ">" e1 e2 4, 0 ) + (fun l e1 e2 s -> printBinary eqOp e1 e2 5, 0 ) + (fun l e1 e2 s -> printBinary neqOp e1 e2 5, 0 ) + (fun lc e1 e2 s -> printBinary andOp e1 e2 6, 0 ) + (fun lc e1 e2 s -> printBinary orOp e1 e2 6, 0 ) exp 0 |> fst |> snd ret - + //let baseFuncName = match baseTypeUperFunc with None -> None | Some baseFunc -> baseFunc.funcName let acnChildren = children |> List.choose(fun x -> match x with AcnChild z -> Some z | Asn1Child _ -> None) let asn1Children = children |> List.choose(fun x -> match x with Asn1Child z -> Some z | AcnChild _ -> None) - let funcBody (us:State) (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let acnlocalVariablesCh = - acnChildren |> - List.filter(fun x -> match x.Type with Asn1AcnAst.AcnNullType _ -> false | _ -> true) |> - List.collect(fun x -> - let defaultVal = extractACNDefaultInitValue x.Type + let funcBody (us:State) (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let acnlocalVariablesCh = + acnChildren |> + List.filter(fun x -> match x.Type with Asn1AcnAst.AcnNullType _ -> false | _ -> true) |> + List.collect(fun x -> + let childLv = + match lm.lg.decodingKind with + | InPlace -> [AcnInsertedChild(x.c_name, x.typeDefinitionBodyWithinSeq, x.initExpression)] + | Copy -> [] match codec with - | Encode -> [AcnInsertedChild(x.c_name, x.typeDefinitionBodyWithinSeq, defaultVal); BooleanLocalVariable(x.c_name+"_is_initialized", Some false)] - | Decode -> [AcnInsertedChild(x.c_name, x.typeDefinitionBodyWithinSeq, defaultVal)]) - - let acnlocalVariablesPrms = + | Encode -> + let initLv = + if lm.lg.usesWrappedOptional then [] + else [BooleanLocalVariable(x.c_name+"_is_initialized", Some lm.lg.FalseLiteral)] + childLv@initLv + | Decode -> childLv) + + let acnlocalVariablesPrms = match t.id.tasInfo with - | Some _ -> [] // if the encoding type is a top level type (i.e. TAS) then the encodig parameters are transformed into function parameters and not local variables. + | Some _ -> [] // if the encoding type is a top level type (i.e. TAS) then the encoding parameters are transformed into function parameters and not local variables. | None -> [] // acnPrms |> List.map(fun x -> AcnInsertedChild(x.c_name, x.typeDefinitionBodyWithinSeq)) let acnlocalVariables = acnlocalVariablesCh @ acnlocalVariablesPrms - //let acnParams = r.acnParameters |> List.filter(fun prm -> prm.ModName ) + //let acnParams = r.acnParameters |> List.filter(fun prm -> prm.ModName ) - let printPresenceBit (child:Asn1Child) = + let printPresenceBit (child:Asn1Child) (existVar: string option)= match child.Optionality with | None -> None | Some Asn1AcnAst.AlwaysAbsent -> None | Some Asn1AcnAst.AlwaysPresent -> None - | Some (Asn1AcnAst.Optional opt) -> + | Some (Asn1AcnAst.Optional opt) -> match opt.acnPresentWhen with - | None -> Some (sequence_presense_optChild p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName codec) + | None -> + assert (codec = Encode || existVar.IsSome) + Some (sequence_presence_optChild (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) existVar errCode.errCodeName codec) | Some _ -> None - let localVariables = - match asn1Children |> List.choose printPresenceBit with - | x::_ when lm.lg.uper.requires_presenceBit && codec = CommonTypes.Decode -> (FlagLocalVariable ("presenceBit", None))::acnlocalVariables - | _ -> acnlocalVariables - + let localVariables = acnlocalVariables let td = lm.lg.getSequenceTypeDefinition o.typeDef let localVariables, post_encoding_function, soBitStreamPositionsLocalVar, soSaveInitialBitStrmStatement = - let bitStreamPositionsLocalVar = sprintf "bitStreamPositions_%d" (t.id.SeqeuenceOfLevel + 1) - let bsPosStart = sprintf "bitStreamPositions_start%d" (t.id.SeqeuenceOfLevel + 1) + let bitStreamPositionsLocalVar = sprintf "bitStreamPositions_%d" (t.id.SequenceOfLevel + 1) + let bsPosStart = sprintf "bitStreamPositions_start%d" (t.id.SequenceOfLevel + 1) match o.acnProperties.postEncodingFunction with | Some (PostEncodingFunction (modFncName, fncName)) when codec = Encode -> - let actualFncName = - match lm.lg.hasModules with - | false -> (ToC fncName.Value) - | true -> + let actualFncName = + match lm.lg.hasModules with + | false -> (ToC fncName.Value) + | true -> match modFncName with | None -> (ToC (r.args.mappingFunctionsModule.orElse "")) + "." + (ToC fncName.Value) | Some modFncName -> (ToC modFncName.Value) + "." + (ToC fncName.Value) @@ -1610,160 +1591,203 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi let fncCall = sequence_call_post_encoding_function (lm.lg.getPointer p.arg) (actualFncName) bsPosStart bitStreamPositionsLocalVar let initialBitStrmStatement = sequence_save_bitStream_start bsPosStart codec - [AcnInsertedChild(bitStreamPositionsLocalVar, td.extention_function_potisions, ""); AcnInsertedChild(bsPosStart, bitStreamName, "")]@localVariables, Some fncCall, Some bitStreamPositionsLocalVar, Some initialBitStrmStatement + [AcnInsertedChild(bitStreamPositionsLocalVar, td.extension_function_positions, ""); AcnInsertedChild(bsPosStart, bitStreamName, "")]@localVariables, Some fncCall, Some bitStreamPositionsLocalVar, Some initialBitStrmStatement | _ -> match o.acnProperties.preDecodingFunction with | Some (PreDecodingFunction (modFncName, fncName)) when codec = Decode -> - let actualFncName = - match lm.lg.hasModules with - | false -> (ToC fncName.Value) - | true -> + let actualFncName = + match lm.lg.hasModules with + | false -> (ToC fncName.Value) + | true -> match modFncName with | None -> (ToC (r.args.mappingFunctionsModule.orElse "")) + "." + (ToC fncName.Value) | Some modFncName -> (ToC modFncName.Value) + "." + (ToC fncName.Value) let fncCall = sequence_call_post_decoding_validator (lm.lg.getPointer p.arg) (actualFncName) bsPosStart bitStreamPositionsLocalVar let initialBitStrmStatement = sequence_save_bitStream_start bsPosStart codec - [AcnInsertedChild(bitStreamPositionsLocalVar, td.extention_function_potisions, ""); AcnInsertedChild(bsPosStart, bitStreamName, "")]@localVariables, Some fncCall, Some bitStreamPositionsLocalVar, Some initialBitStrmStatement + [AcnInsertedChild(bitStreamPositionsLocalVar, td.extension_function_positions, ""); AcnInsertedChild(bsPosStart, bitStreamName, "")]@localVariables, Some fncCall, Some bitStreamPositionsLocalVar, Some initialBitStrmStatement | _ -> localVariables, None, None, None - - let handleChild (us:State) (child:SeqChildInfo) = + let handleChild (us:State) (child:SeqChildInfo): SequenceChildResult * State = let soSaveBitStrmPosStatement = None -// match soBitStreamPositionsLocalVar with -// | Some lvName when child.savePosition -> Some (sequence_save_bitstream lvName (child.getBackendName l) codec) -// | _ -> None match child with - | Asn1Child child -> + | Asn1Child child -> + let childTypeDef = child.Type.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules + let childName = lm.lg.getAsn1ChildBackendName child let chFunc = child.Type.getAcnFunction codec - let childContentResult, ns1 = + let childContentResult, ns1 = match chFunc with - | Some chFunc -> chFunc.funcBodyAsSeqComp us [] ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) (lm.lg.getAsn1ChildBackendName child) - | None -> None, us + | Some chFunc -> + let newArg = lm.lg.getSeqChild p.arg childName child.Type.isIA5String child.Optionality.IsSome + let newArg = if lm.lg.usesWrappedOptional && newArg.isOptional && codec = Encode then newArg.asLast else newArg + let newP = {p with arg = newArg} + chFunc.funcBodyAsSeqComp us [] newP childName + | None -> None, us //handle present-when acn property - let present_when_statements, ns2 = - let acnPresenceStatement, errCodes, ns1b = - match child.Optionality with - | Some (Asn1AcnAst.Optional opt) -> - match opt.acnPresentWhen with - | None -> None, [], ns1 - | Some (PresenceWhenBool _) -> - match codec with - | Codec.Encode -> None, [], ns1 - | Codec.Decode -> - let extField = getExternaField r deps child.Type.id - Some(sequence_presense_optChild_pres_bool p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) extField codec), [], ns1 - | Some (PresenceWhenBoolExpression exp) -> - let _errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((child.Type.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_PRESENT_WHEN_EXP_FAILED") - let errCode, ns1a = getNextValidErrorCode ns1 _errCodeName None - let retExp = acnExpressionToBackendExpression o p exp - Some(sequence_presense_optChild_pres_acn_expression p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) retExp errCode.errCodeName codec), [errCode], ns1a - | _ -> None, [], ns1 - [(AcnPresenceStatement, acnPresenceStatement, [], errCodes)], ns1b - - let childEncDecStatement, ns3 = + let present_when_statements, existVar, ns2 = + let acnPresenceStatement, lvs, errCodes, existVar, ns1b = + match child.Optionality with + | Some (Asn1AcnAst.Optional opt) -> + match opt.acnPresentWhen with + | None -> + match codec with + | Encode -> + // We do not need the `exist` variable for encoding as we use the child `exist` bit + None, [], [], None, ns1 + | Decode -> + let existVar = ToC (child._c_name + "_exist") + let lv = FlagLocalVariable (existVar, None) + None, [lv], [], Some existVar, ns1 + | Some (PresenceWhenBool _) -> + match codec with + | Encode -> None, [], [], None, ns1 + | Decode -> + let extField = getExternalField r deps child.Type.id + let body = sequence_presence_optChild_pres_bool (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childName extField codec + Some body, [], [], Some extField, ns1 + | Some (PresenceWhenBoolExpression exp) -> + let _errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((child.Type.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_PRESENT_WHEN_EXP_FAILED") + let errCode, ns1a = getNextValidErrorCode ns1 _errCodeName None + let retExp = acnExpressionToBackendExpression o p exp + let existVar = + if codec = Decode then Some (ToC (child._c_name + "_exist")) + else None + let lv = existVar |> Option.toList |> List.map (fun v -> FlagLocalVariable (v, None)) + let body = sequence_presence_optChild_pres_acn_expression (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childName retExp existVar errCode.errCodeName codec + Some body, lv, [errCode], existVar, ns1a + | _ -> None, [], [], None, ns1 + {acnStatement=AcnPresenceStatement; body=acnPresenceStatement; lvs=lvs; errCodes=errCodes}, existVar, ns1b + + let childEncDecStatement, childResultExpr, ns3 = match childContentResult with - | None -> + | None -> + // Copy-decoding expects to have a result expression (even if unused), so we pick the initExpression + let childResultExpr = + match codec, lm.lg.decodingKind with + | Decode, Copy -> Some child.Type.initFunction.initExpression + | _ -> None match child.Optionality with - | Some Asn1AcnAst.AlwaysPresent -> - let childBody = Some(sequence_always_present_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) None soSaveBitStrmPosStatement codec) - let chLocalVars = [] - [(Asn1ChildEncodeStatement, childBody, chLocalVars, [])], ns2 - | _ -> [], ns2 + | Some Asn1AcnAst.AlwaysPresent -> + let childBody = Some(sequence_always_present_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childName None childResultExpr soSaveBitStrmPosStatement codec) + Some {acnStatement=Asn1ChildEncodeStatement; body=childBody; lvs=[]; errCodes=[]}, childResultExpr, ns2 + | _ -> None, childResultExpr, ns2 | Some childContent -> - let childBody, chLocalVars = + let childBody, chLocalVars = match child.Optionality with - | None -> Some (sequence_mandatory_child (lm.lg.getAsn1ChildBackendName child) childContent.funcBody soSaveBitStrmPosStatement codec), childContent.localVariables - | Some Asn1AcnAst.AlwaysAbsent -> Some (sequence_always_absent_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody soSaveBitStrmPosStatement codec), [] - | Some Asn1AcnAst.AlwaysPresent -> Some(sequence_always_present_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) (Some childContent.funcBody) soSaveBitStrmPosStatement codec), childContent.localVariables - | Some (Asn1AcnAst.Optional opt) -> + | None -> Some (sequence_mandatory_child childName childContent.funcBody soSaveBitStrmPosStatement codec), childContent.localVariables + | Some Asn1AcnAst.AlwaysAbsent -> Some (sequence_always_absent_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childName childContent.funcBody childTypeDef soSaveBitStrmPosStatement codec), [] + | Some Asn1AcnAst.AlwaysPresent -> Some (sequence_always_present_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childName (Some childContent.funcBody) childContent.resultExpr soSaveBitStrmPosStatement codec), childContent.localVariables + | Some (Asn1AcnAst.Optional opt) -> + assert (codec = Encode || existVar.IsSome) + let pp, _ = joinedOrAsIdentifier lm codec p match opt.defaultValue with - | None -> Some(sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody soSaveBitStrmPosStatement codec), childContent.localVariables - | Some v -> - let defInit= child.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) (mapValue v).kind - Some(sequence_default_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody defInit soSaveBitStrmPosStatement codec), childContent.localVariables - [(Asn1ChildEncodeStatement, childBody, chLocalVars, childContent.errCodes)], ns2 - present_when_statements@childEncDecStatement,ns3 - | AcnChild acnChild -> + | None -> + Some(sequence_optional_child pp (lm.lg.getAccess p.arg) childName childContent.funcBody existVar childContent.resultExpr childTypeDef soSaveBitStrmPosStatement codec), childContent.localVariables + | Some v -> + let defInit= child.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg childName child.Type.isIA5String child.Optionality.IsSome}) (mapValue v).kind + Some(sequence_default_child pp (lm.lg.getAccess p.arg) childName childContent.funcBody defInit existVar childContent.resultExpr childTypeDef soSaveBitStrmPosStatement codec), childContent.localVariables + Some {acnStatement=Asn1ChildEncodeStatement; body=childBody; lvs=chLocalVars; errCodes=childContent.errCodes}, childContent.resultExpr, ns2 + {stmts=[present_when_statements]@(childEncDecStatement |> Option.toList); resultExpr=childResultExpr; existVar=existVar}, ns3 + | AcnChild acnChild -> //handle updates //acnChild.c_name - let childP = {CallerScope.modName = p.modName; arg= VALUE (getAcnDeterminantName acnChild.id)} + let childP = {CallerScope.modName = p.modName; arg= Selection.valueEmptyPath (getAcnDeterminantName acnChild.id)} - let updtateStatement, ns1 = + let updateStatement, ns1 = match codec with - | CommonTypes.Encode -> + | Encode -> let pRoot : CallerScope = lm.lg.getParamType t codec //???? - let updateStatement, lvs, lerCodes = + let updateStatement, lvs, errCodes = match acnChild.funcUpdateStatement with - | Some funcUpdateStatement -> Some (funcUpdateStatement.updateAcnChildFnc acnChild.typeDefinitionBodyWithinSeq childP pRoot), funcUpdateStatement.localVariables, funcUpdateStatement.errCodes + | Some funcUpdateStatement -> Some (funcUpdateStatement.updateAcnChildFnc acnChild childP pRoot), funcUpdateStatement.localVariables, funcUpdateStatement.errCodes | None -> None, [], [] - - [(AcnChildUpdateStatement, updateStatement, lvs, lerCodes)], us - | CommonTypes.Decode -> [], us + Some {acnStatement=AcnChildUpdateStatement; body=updateStatement; lvs=lvs; errCodes=errCodes}, us + | Decode -> None, us //acn child encode/decode - let childEncDecStatement, ns2 = + let childEncDecStatement, ns2 = let chFunc = acnChild.funcBody codec let childContentResult = chFunc [] childP match childContentResult with - | None -> [],ns1 + | None -> None, ns1 | Some childContent -> match codec with | Encode -> match acnChild.Type with | Asn1AcnAst.AcnNullType _ -> let childBody = Some (sequence_mandatory_child acnChild.c_name childContent.funcBody soSaveBitStrmPosStatement codec) - [(AcnChildEncodeStatement, childBody, childContent.localVariables, childContent.errCodes)], ns1 + Some {acnStatement=AcnChildEncodeStatement; body=childBody; lvs=childContent.localVariables; errCodes=childContent.errCodes}, ns1 | _ -> - let _errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((acnChild.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_UNITIALIZED") + let _errCodeName = ToC ("ERR_ACN" + (codec.suffix.ToUpper()) + "_" + ((acnChild.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_UNINITIALIZED") let errCode, ns1a = getNextValidErrorCode ns1 _errCodeName None - let childBody = Some (sequence_acn_child acnChild.c_name childContent.funcBody errCode.errCodeName soSaveBitStrmPosStatement codec) - [(AcnChildEncodeStatement, childBody, childContent.localVariables, errCode::childContent.errCodes)], ns1a + Some {acnStatement=AcnChildEncodeStatement; body=childBody; lvs=childContent.localVariables; errCodes=errCode::childContent.errCodes}, ns1a | Decode -> let childBody = Some (sequence_mandatory_child acnChild.c_name childContent.funcBody soSaveBitStrmPosStatement codec) - [(AcnChildEncodeStatement, childBody, childContent.localVariables, childContent.errCodes)], ns1 - updtateStatement@childEncDecStatement, ns2 + Some {acnStatement=AcnChildEncodeStatement; body=childBody; lvs=childContent.localVariables; errCodes=childContent.errCodes}, ns1 + {stmts=(updateStatement |> Option.toList)@(childEncDecStatement |> Option.toList); resultExpr=None; existVar=None}, ns2 // find acn inserted fields, which are not NULL types and which have no dependency. // For those fields we shoud generated no anc encode/decode function - // Otherwise, the encoding function is wrong since an unitialized value is encoded. + // Otherwise, the encoding function is wrong since an uninitialized value is encoded. let existsAcnChildWithNoUpdates = acnChildren |> List.filter (fun acnChild -> match acnChild.Type with Asn1AcnAst.AcnNullType _ -> false | _ -> true) |> - List.filter(fun acnChild -> - let childP = {CallerScope.modName = p.modName; arg = VALUE (getAcnDeterminantName acnChild.id)} - let pRoot : CallerScope = lm.lg.getParamType t codec - let updateStatement = + List.filter(fun acnChild -> + let childP = {CallerScope.modName = p.modName; arg = Selection.valueEmptyPath (getAcnDeterminantName acnChild.id)} + let pRoot : CallerScope = lm.lg.getParamType t codec + let updateStatement = match acnChild.funcUpdateStatement with - | Some funcUpdateStatement -> Some (funcUpdateStatement.updateAcnChildFnc acnChild.typeDefinitionBodyWithinSeq childP pRoot) + | Some funcUpdateStatement -> Some (funcUpdateStatement.updateAcnChildFnc acnChild childP pRoot) | None -> None updateStatement.IsNone) let saveInitialBitStrmStatements = soSaveInitialBitStrmStatement |> Option.toList - let presenseBits = asn1Children |> List.choose printPresenceBit let childrenStatements00, ns = children |> foldMap handleChild us - let childrenStatements0 = childrenStatements00 |> List.collect id - let childrenStatements = childrenStatements0 |> List.choose(fun (_, s,_,_) -> s) - let childrenLocalvars = childrenStatements0 |> List.collect(fun (_, _,s,_) -> s) - let childrenErrCodes = childrenStatements0 |> List.collect(fun (_, _,_,s) -> s) - - - let seqContent = (saveInitialBitStrmStatements@presenseBits@childrenStatements@(post_encoding_function |> Option.toList)) |> nestChildItems lm codec + let childrenStatements0 = childrenStatements00 |> List.collect (fun xs -> xs.stmts) + let childrenStatements = childrenStatements0 |> List.choose(fun s -> s.body) + let presenceBits = ((List.zip children childrenStatements00) + |> List.choose (fun (child, res) -> + match child with + | Asn1Child asn1 -> printPresenceBit asn1 res.existVar + | AcnChild _ -> None)) + let childrenLocalvars = childrenStatements0 |> List.collect(fun s -> s.lvs) + let childrenExistVar = childrenStatements00 |> List.choose(fun res -> res.existVar) + let childrenResultExpr = childrenStatements00 |> List.choose(fun res -> res.resultExpr) + let childrenErrCodes = childrenStatements0 |> List.collect(fun s -> s.errCodes) + + let resultExpr, seqBuild= + match codec, lm.lg.decodingKind with + | Decode, Copy -> + // If we are Decoding with Copy decoding kind, then all children `resultExpr` + // must be defined as well (i.e. we must have the same number of `resultExpr` as children) + // assert (childrenResultExpr.Length = asn1Children.Length) + assert (childrenResultExpr.Length = asn1Children.Length) + let existSeq = + if lm.lg.usesWrappedOptional || childrenExistVar.IsEmpty then [] + else + let existTd = (lm.lg.getSequenceTypeDefinition o.typeDef).exist + [lm.init.initSequenceExpr existTd existTd childrenExistVar []] + let resultExpr = p.arg.asIdentifier + Some resultExpr, [lm.uper.sequence_build resultExpr (typeDefinition.longTypedefName2 lm.lg.hasModules) (existSeq@childrenResultExpr)] + | _ -> None, [] + + let seqContent = (saveInitialBitStrmStatements@presenceBits@childrenStatements@(post_encoding_function |> Option.toList)@seqBuild) |> nestChildItems lm codec match existsAcnChildWithNoUpdates with | [] -> match seqContent with - | None -> + | None -> match codec with | Encode -> None, ns | Decode -> - match lm.lg.decodeEmptySeq p.arg.p with + match lm.lg.decodeEmptySeq (p.arg.joined lm.lg) with | None -> None, ns | Some decodeEmptySeq -> - Some ({AcnFuncBodyResult.funcBody = decodeEmptySeq; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=true}), ns - | Some ret -> Some ({AcnFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=(o.acnMaxSizeInBits = 0I)}), ns - - | errChild::_ -> + Some ({AcnFuncBodyResult.funcBody = decodeEmptySeq; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=true; resultExpr=Some decodeEmptySeq}), ns + | Some ret -> + Some ({AcnFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=(o.acnMaxSizeInBits = 0I); resultExpr=resultExpr}), ns + + | errChild::_ -> let determinantUsage = match errChild.Type with | Asn1AcnAst.AcnInteger _-> "length" @@ -1778,63 +1802,58 @@ The field '%s' must either be removed or used as %s determinant of another ASN.1 //let loc = errChild.Name.Location //Console.Out.WriteLine (FrontEntMain.formatSemanticWarning loc errMessage) //None, ns - + let isTestVaseValid (atc:AutomaticTestCase) = //an automatic test case value is valid //if all ach children can be update during the encoding from the value acnChildren |> List.filter (fun acnChild -> match acnChild.Type with Asn1AcnAst.AcnNullType _ -> false | _ -> true) |> - Seq.forall(fun acnChild -> + Seq.forall(fun acnChild -> match acnChild.funcUpdateStatement with | Some funcUpdateStatement -> (funcUpdateStatement.testCaseFnc atc).IsSome | None -> false) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) let sPresenceBitIndexMap = - asn1Children |> + asn1Children |> List.filter(fun c -> match c.Optionality with Some(Optional _) -> true | _ -> false) |> List.mapi (fun i c -> (c.Name.Value, i)) |> Map.ofList - let uperPresenceMask = + let uperPresenceMask = match sPresenceBitIndexMap.IsEmpty with | true -> [] | false -> - [{IcdRow.fieldName = "Presence Mask"; comments = [$"Presence bit mask"]; sPresent="always";sType=IcdPlainType "bit mask"; sConstraint=None; minLengtInBits = sPresenceBitIndexMap.Count.AsBigInt ;maxLengtInBits=sPresenceBitIndexMap.Count.AsBigInt;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] + [{IcdRow.fieldName = "Presence Mask"; comments = [$"Presence bit mask"]; sPresent="always";sType=IcdPlainType "bit mask"; sConstraint=None; minLengthInBits = sPresenceBitIndexMap.Count.AsBigInt ;maxLengthInBits=sPresenceBitIndexMap.Count.AsBigInt;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] - if (t.id.AsString = "PUS-C.TC.one-tc.manage-memory.pus-6-1-memory-dump") then - printfn "debug" - - let icdFnc fieldName sPresent comments = - if t.id.AsString = "PUS-C.Dump-Params" then - printfn "debug" + let icdFnc fieldName sPresent comments = let chRows = children |> List.collect(fun c -> match c with - | Asn1Child c -> + | Asn1Child c -> let optionality = match c.Optionality with | None -> "always" | Some(AlwaysAbsent ) -> "never" | Some(AlwaysPresent) -> "always" - | Some(Optional opt) -> + | Some(Optional opt) -> match opt.acnPresentWhen with - | None -> $"when bit %d{sPresenceBitIndexMap[c.Name.Value]} is set in the uPER bit mask" + | None -> $"when bit %d{sPresenceBitIndexMap[c.Name.Value]} is set in the uPER bit mask" | Some(PresenceWhenBool relPath) -> $"when %s{relPath.AsString} is true" - | Some(PresenceWhenBoolExpression acnExp) -> - let dummyScope = {CallerScope.modName = ""; arg = VALUE ""} + | Some(PresenceWhenBoolExpression acnExp) -> + let dummyScope = {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} let retExp = acnExpressionToBackendExpression o dummyScope acnExp $"when %s{retExp}" let comments = c.Comments |> Seq.toList let x = c.Type.icdFunction //let isRef = match c.Type.Kind with ReferenceType _ -> true | _ -> false match x.canBeEmbedded with - | true -> + | true -> x.createRowsFunc c.Name.Value optionality comments - | false -> + | false -> let icdHash = x.typeAss.hash let sType = TypeHash x.typeAss.hash - [{IcdRow.fieldName = c.Name.Value; comments = comments; sPresent=optionality;sType=sType; sConstraint=None; minLengtInBits = c.Type.acnMinSizeInBits; maxLengtInBits=c.Type.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] - | AcnChild c -> + [{IcdRow.fieldName = c.Name.Value; comments = comments; sPresent=optionality;sType=sType; sConstraint=None; minLengthInBits = c.Type.acnMinSizeInBits; maxLengthInBits=c.Type.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] + | AcnChild c -> let icdFunc = createAcnChildIcdFunction c let comments = c.Comments |> Seq.toList [icdFunc c.Name.Value comments]) @@ -1844,21 +1863,21 @@ The field '%s' must either be removed or used as %s determinant of another ASN.1 -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (acnPrms:DastAcnParameter list) (us:State) = - let choice_uper = lm.acn.Choice - let choiceChildAlwaysAbsent = lm.acn.ChoiceChildAlwaysAbsent - let choiceChild = lm.acn.ChoiceChild - let choice_Enum = lm.acn.Choice_Enum - let choiceChild_Enum = lm.acn.ChoiceChild_Enum - let choice_preWhen = lm.acn.Choice_preWhen - let choiceChild_preWhen = lm.acn.ChoiceChild_preWhen - let choiceChild_preWhen_int_condition = lm.acn.ChoiceChild_preWhen_int_condition - let choiceChild_preWhen_str_condition = lm.acn.ChoiceChild_preWhen_str_condition +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (acnPrms:DastAcnParameter list) (us:State) = + let choice_uper = lm.acn.Choice + let choiceChildAlwaysAbsent = lm.acn.ChoiceChildAlwaysAbsent + let choiceChild = lm.acn.ChoiceChild + let choice_Enum = lm.acn.Choice_Enum + let choiceChild_Enum = lm.acn.ChoiceChild_Enum + let choice_preWhen = lm.acn.Choice_preWhen + let choiceChild_preWhen = lm.acn.ChoiceChild_preWhen + let choiceChild_preWhen_int_condition = lm.acn.ChoiceChild_preWhen_int_condition + let choiceChild_preWhen_str_condition = lm.acn.ChoiceChild_preWhen_str_condition let isAcnChild (ch:ChChildInfo) = match ch.Optionality with Some (ChoiceAlwaysAbsent) -> false | _ -> true let acnChildren = children |> List.filter isAcnChild let alwaysAbsentChildren = children |> List.filter (isAcnChild >> not) - let children = + let children = match lm.lg.acn.choice_handle_always_absent_child with | false -> acnChildren | true -> acnChildren@alwaysAbsentChildren //in Spark, we have to cover all cases even the ones that are always absent due to SPARK strictness @@ -1869,12 +1888,12 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel //let nBits = (GetNumberOfBitsForNonNegativeInteger (nMax-nMin)) let nIndexSizeInBits = (GetNumberOfBitsForNonNegativeInteger (BigInteger (acnChildren.Length - 1))) let sChoiceIndexName = (ToC t.id.AsString) + "_index_tmp" - let ec = + let ec = match o.acnProperties.enumDeterminant with - | Some _ -> + | Some _ -> let dependency = deps.acnDependencies |> List.find(fun d -> d.asn1Type = t.id) match dependency.dependencyKind with - | Asn1AcnAst.AcnDepChoiceDeteterminant (enm,_) -> CEC_enum (enm, dependency.determinant) + | Asn1AcnAst.AcnDepChoiceDeterminant (enm, _, _) -> CEC_enum (enm, dependency.determinant) | _ -> raise(BugErrorException("unexpected dependency type")) | None -> match children |> Seq.exists(fun c -> not (Seq.isEmpty c.acnPresentWhenConditions)) with @@ -1890,143 +1909,124 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel let typeDefinitionName = defOrRef.longTypedefName2 lm.lg.hasModules//getTypeDefinitionName t.id.tasInfo typeDefinition - let funcBody (us:State) (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let funcBody (us:State) (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = let td = (lm.lg.getChoiceTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules (ToC p.modName) let handleChild (us:State) (idx:int) (child:ChChildInfo) = - let chFunc = child.chType.getAcnFunction codec - - let sChildInitExpr = - match ST.lang with - | Scala -> - let sChInitExpr = - match child.chType.initFunction.initFunction with - | Some x -> x.funcName - | None -> child.chType.initFunction.initExpression - match hasInitMethSuffix sChInitExpr (lm.init.methodNameSuffix()) with - | true -> sChInitExpr + "()" - | false -> - match child.chType.Kind with - | Sequence sequence -> sequence.baseInfo.typeDef[Scala].typeName + "(" + sChInitExpr + ")" - | (OctetString _ | BitString _ | IA5String _) -> sChInitExpr - | _ -> extractDefaultInitValue child.chType.Kind - | _ -> child.chType.initFunction.initExpression - - let childContentResult, ns1 = - //match child.Optionality with - //| Some (ChoiceAlwaysAbsent) -> None//Some (always_false_statement errCode.errCodeName) - //| Some (ChoiceAlwaysPresent) - //| None -> - match chFunc with - | Some chFunc -> + let chFunc = child.chType.getAcnFunction codec + let sChildInitExpr = child.chType.initFunction.initExpression + + let childContentResult, ns1 = + match chFunc with + | Some chFunc -> + match lm.lg.acn.choice_requires_tmp_decoding with + | false -> chFunc.funcBody us [] ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) + | true when codec = CommonTypes.Decode -> chFunc.funcBody us [] ({CallerScope.modName = p.modName; arg = Selection.valueEmptyPath ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) + | true -> chFunc.funcBody us [] ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) + | None -> None, us + + let childContent_funcBody, childContent_localVariables, childContent_errCodes = + match childContentResult with + | None -> + match codec with + | Encode -> lm.lg.emptyStatement, [], [] + | Decode -> + let childp = match lm.lg.acn.choice_requires_tmp_decoding with - | false -> chFunc.funcBody us [] ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) - | true when codec = CommonTypes.Decode -> chFunc.funcBody us [] ({CallerScope.modName = p.modName; arg = VALUE ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) - | true -> chFunc.funcBody us [] ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) - | None -> None, us + | true -> ({CallerScope.modName = p.modName; arg = Selection.valueEmptyPath ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) + | false -> ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) + let decStatement = + match child.chType.ActualType.Kind with + | NullType _ -> lm.lg.decode_nullType (childp.arg.joined lm.lg) + | Sequence _ -> lm.lg.decodeEmptySeq (childp.arg.joined lm.lg) + | _ -> None + match decStatement with + | None -> lm.lg.emptyStatement,[], [] + | Some ret -> + ret ,[],[] + + | Some childContent -> childContent.funcBody, childContent.localVariables, childContent.errCodes + + let childBody = + let sChildName = (lm.lg.getAsn1ChChildBackendName child) + let sChildTypeDef = child.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules //child.chType.typeDefinition.typeDefinitionBodyWithinSeq + + let sChoiceTypeName = typeDefinitionName + match child.Optionality with + | Some (ChoiceAlwaysAbsent) -> Some (choiceChildAlwaysAbsent (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) (BigInteger idx) errCode.errCodeName codec) + | Some (ChoiceAlwaysPresent) + | None -> + match ec with + | CEC_uper -> + Some (choiceChild (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) (BigInteger idx) nIndexSizeInBits nMax childContent_funcBody sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) + | CEC_enum (enm,_) -> + let getDefOrRef (a:Asn1AcnAst.ReferenceToEnumerated) = + match p.modName = a.modName with + | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} + | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName); typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} + + + let enmItem = enm.enm.items |> List.find(fun itm -> itm.Name.Value = child.Name.Value) + Some (choiceChild_Enum (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getNamedItemBackendName (Some (getDefOrRef enm)) enmItem ) (lm.lg.presentWhenName (Some defOrRef) child) childContent_funcBody sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) + | CEC_presWhen -> + let handPresenceCond (cond:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = + match cond with + | PresenceInt (relPath, intLoc) -> + let extField = getExternalFieldChoicePresentWhen r deps t.id relPath + choiceChild_preWhen_int_condition extField intLoc.Value + | PresenceStr (relPath, strVal) -> + let strType = + deps.acnDependencies |> + List.filter(fun d -> d.asn1Type = t.id) |> + List.choose(fun d -> + match d.dependencyKind with + | AcnDepPresenceStr(relPathCond, ch, str) when relPathCond = relPath-> Some str + | _ -> None) |> Seq.head + + + let extField = getExternalFieldChoicePresentWhen r deps t.id relPath + let arrNulls = [0 .. ((int strType.maxSize.acn) - strVal.Value.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) + choiceChild_preWhen_str_condition extField strVal.Value arrNulls + let conds = child.acnPresentWhenConditions |>List.map handPresenceCond + let pp, _ = joinedOrAsIdentifier lm codec p + Some (choiceChild_preWhen pp (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) childContent_funcBody conds (idx=0) sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) + [(childBody, childContent_localVariables, childContent_errCodes)], ns1 - let childContent_funcBody, childContent_localVariables, childContent_errCodes = - match childContentResult with - | None -> - match codec with - | Encode -> lm.lg.emtyStatement, [], [] - | Decode -> - let childp = - match lm.lg.acn.choice_requires_tmp_decoding with - | true -> ({CallerScope.modName = p.modName; arg = VALUE ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) - | false -> ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) - let decStatement = - match child.chType.ActualType.Kind with - | NullType _ -> lm.lg.decode_nullType childp.arg.p - | Sequence _ -> lm.lg.decodeEmptySeq childp.arg.p - | _ -> None - match decStatement with - | None -> lm.lg.emtyStatement,[], [] - | Some ret -> - ret ,[],[] - - | Some childContent -> childContent.funcBody, childContent.localVariables, childContent.errCodes - -// match childContentResult with -// | None -> [], ns1 -// | Some childContent -> - let childBody = - let sChildName = (lm.lg.getAsn1ChChildBackendName child) - let sChildTypeDef = child.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules //child.chType.typeDefinition.typeDefinitionBodyWithinSeq - - let sChoiceTypeName = typeDefinitionName - match child.Optionality with - | Some (ChoiceAlwaysAbsent) -> Some (choiceChildAlwaysAbsent p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) (BigInteger idx) errCode.errCodeName codec) - | Some (ChoiceAlwaysPresent) - | None -> - match ec with - | CEC_uper -> - Some (choiceChild p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) (BigInteger idx) nIndexSizeInBits nMax childContent_funcBody sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) - | CEC_enum (enm,_) -> - let getDefOrRef (a:Asn1AcnAst.ReferenceToEnumerated) = - match p.modName = a.modName with - | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} - | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName); typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} - - - let enmItem = enm.enm.items |> List.find(fun itm -> itm.Name.Value = child.Name.Value) - Some (choiceChild_Enum p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getNamedItemBackendName (Some (getDefOrRef enm)) enmItem ) (lm.lg.presentWhenName (Some defOrRef) child) childContent_funcBody sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) - | CEC_presWhen -> - let handPresenseCond (cond:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = - match cond with - | PresenceInt (relPath, intLoc) -> - let extField = getExternaFieldChoizePresentWhen r deps t.id relPath - choiceChild_preWhen_int_condition extField intLoc.Value - | PresenceStr (relPath, strVal) -> - let strType = - deps.acnDependencies |> - List.filter(fun d -> d.asn1Type = t.id) |> - List.choose(fun d -> - match d.dependencyKind with - | AcnDepPresenceStr(relPathCond, ch, str) when relPathCond = relPath-> Some str - | _ -> None) |> Seq.head - - - let extField = getExternaFieldChoizePresentWhen r deps t.id relPath - let arrNuls = [0 .. ((int strType.maxSize.acn) - strVal.Value.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) - choiceChild_preWhen_str_condition extField strVal.Value arrNuls - let conds = child.acnPresentWhenConditions |>List.map handPresenseCond - Some (choiceChild_preWhen p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some defOrRef) child) childContent_funcBody conds (idx=0) sChildName sChildTypeDef sChoiceTypeName sChildInitExpr codec) - [(childBody, childContent_localVariables, childContent_errCodes)], ns1 let childrenStatements00, ns = children |> List.mapi (fun i x -> i,x) |> foldMap (fun us (i,x) -> handleChild us i x) us let childrenStatements0 = childrenStatements00 |> List.collect id let childrenStatements = childrenStatements0 |> List.choose(fun (s,_,_) -> s) let childrenLocalvars = childrenStatements0 |> List.collect(fun (_,s,_) -> s) let childrenErrCodes = childrenStatements0 |> List.collect(fun (_,_,s) -> s) - let choiceContent = + let choiceContent, resultExpr = + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg match ec with - | CEC_uper -> - //let ret = choice p.arg.p (lm.lg.getAccess p.arg) childrenContent (BigInteger (children.Length - 1)) sChoiceIndexName errCode.errCodeName typeDefinitionName nBits codec - choice_uper p.arg.p (lm.lg.getAccess p.arg) childrenStatements nMax sChoiceIndexName td nIndexSizeInBits errCode.errCodeName codec - | CEC_enum enm -> - let extField = getExternaField r deps t.id - choice_Enum p.arg.p (lm.lg.getAccess p.arg) childrenStatements extField errCode.errCodeName codec - | CEC_presWhen -> choice_preWhen p.arg.p (lm.lg.getAccess p.arg) childrenStatements errCode.errCodeName codec - Some ({AcnFuncBodyResult.funcBody = choiceContent; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=false}), ns + | CEC_uper -> + choice_uper pp access childrenStatements nMax sChoiceIndexName td nIndexSizeInBits errCode.errCodeName codec, resultExpr + | CEC_enum enm -> + let extField = getExternalField r deps t.id + choice_Enum pp access childrenStatements extField errCode.errCodeName codec, resultExpr + | CEC_presWhen -> choice_preWhen pp access childrenStatements errCode.errCodeName codec, resultExpr + Some ({AcnFuncBodyResult.funcBody = choiceContent; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}), ns let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let uperPresenceMask, extraComment = + let uperPresenceMask, extraComment = match acnChildren.Length with | 1 -> [], [] | _ -> match ec with - | CEC_uper -> + | CEC_uper -> let indexSize = GetChoiceUperDeterminantLengthInBits acnChildren.Length.AsBigInt - [{IcdRow.fieldName = "ChoiceIndex"; comments = [$"Special field used by ACN to indicate which choice alternative is present."]; sPresent="always" ;sType=IcdPlainType "unsigned int"; sConstraint=None; minLengtInBits = indexSize; maxLengtInBits=indexSize;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}], [] + [{IcdRow.fieldName = "ChoiceIndex"; comments = [$"Special field used by ACN to indicate which choice alternative is present."]; sPresent="always" ;sType=IcdPlainType "unsigned int"; sConstraint=None; minLengthInBits = indexSize; maxLengthInBits=indexSize;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}], [] | CEC_enum (enm,d) -> [],[] - | CEC_presWhen -> + | CEC_presWhen -> let extFields = acnChildren |> List.collect(fun c -> c.acnPresentWhenConditions) |> List.map(fun x -> "'" + x.relativePath.AsString + "'") |> Seq.distinct |> Seq.StrJoin "," let plural = if extFields.Contains "," then "s" else "" [],[$"Active alternative is determined by ACN using the field{plural}: %s{extFields}"] - let icdFnc fieldName sPresent comments = + let icdFnc fieldName sPresent comments = let chRows = acnChildren |> List.mapi(fun idx c -> @@ -2034,30 +2034,30 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel let optionality = match c.Optionality with | Some(ChoiceAlwaysAbsent ) -> "never" - | Some(ChoiceAlwaysPresent) + | Some(ChoiceAlwaysPresent) | None -> match ec with - | CEC_uper -> + | CEC_uper -> match acnChildren.Length <= 1 with | true -> "always" | false -> sprintf "ChoiceIndex = %d" idx - | CEC_enum (enm,d) -> + | CEC_enum (enm,d) -> let refToStr id = match id with - | ReferenceToType sn -> sn |> List.rev |> List.head |> (fun x -> x.AsString) + | ReferenceToType sn -> sn |> List.rev |> List.head |> (fun x -> x.AsString) sprintf "%s = %s" (refToStr d.id) c.Name.Value - | CEC_presWhen -> - let getPresenceSingle (pc:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = + | CEC_presWhen -> + let getPresenceSingle (pc:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = match pc with | AcnGenericTypes.PresenceInt (rp, intLoc) -> sprintf "%s=%A" rp.AsString intLoc.Value | AcnGenericTypes.PresenceStr (rp, strLoc) -> sprintf "%s=%A" rp.AsString strLoc.Value - c.acnPresentWhenConditions |> Seq.map getPresenceSingle |> Seq.StrJoin " AND " + c.acnPresentWhenConditions |> Seq.map getPresenceSingle |> Seq.StrJoin " AND " let x = c.chType.icdFunction match x.canBeEmbedded with | true -> x.createRowsFunc c.Name.Value optionality childComments - | false -> + | false -> let sType = TypeHash x.typeAss.hash - [{IcdRow.fieldName = c.Name.Value; comments = comments; sPresent=optionality;sType=sType; sConstraint=None; minLengtInBits = c.chType.acnMinSizeInBits; maxLengtInBits=c.chType.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}]) |> + [{IcdRow.fieldName = c.Name.Value; comments = comments; sPresent=optionality;sType=sType; sConstraint=None; minLengthInBits = c.chType.acnMinSizeInBits; maxLengthInBits=c.chType.acnMaxSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}]) |> List.collect id uperPresenceMask@chRows |> List.mapi(fun i r -> {r with idxOffset = Some (i+1)}) @@ -2065,38 +2065,11 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel createAcnFunction r lm codec t typeDefinition isValidFunc funcBody (fun atc -> true) icd soSparkAnnotations us, ec -(* -let rec isIcdTypeAssEquivalent (t1:IcdTypeAss) (t2:IcdTypeAss) = - let childrenAreEquivalent = - t1.compositeChildren.Length = t2.compositeChildren.Length && - (List.zip t1.compositeChildren t2.compositeChildren |> Seq.forall (fun (x1,x2) -> isIcdTypeAssEquivalent x1 x2)) - t1.acnLink = t2.acnLink && - t1.asn1Link = t2.asn1Link && - t1.name = t2.name && - t1.kind = t2.kind && - t1.comments = t2.comments && - t1.rows = t2.rows && - t1.minLengtInBytes = t2.minLengtInBytes && - t1.maxLengtInBytes = t2.maxLengtInBytes && - childrenAreEquivalent - -*) - - - - - - - -let createReferenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = +let createReferenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = let baseTypeDefinitionName, baseFncName = getBaseFuncName lm typeDefinition o t.id "_ACN" codec - if (t.id.AsString = "MOD-A.MyCompositeSeq.c") then - printfn "debug" - - let x = baseType.icdFunction - let td = lm.lg.getTypeDefinition t.FT_TypeDefintion + let td = lm.lg.getTypeDefinition t.FT_TypeDefinition let getNewSType (r:IcdRow) = let newType = match r.sType with @@ -2105,97 +2078,99 @@ let createReferenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF | IcdPlainType plainType -> IcdPlainType plainType {r with sType = newType} - let icdFnc,exraComment, name = - if t.id.AsString = "PUS-C.TC.apidf" then - printfn "debug" - - - match o.encodingOptions with - | None -> - let name = + let icdFnc,extraComment, name = + match o.encodingOptions with + | None -> + let name = match o.hasExtraConstrainsOrChildrenOrAcnArgs with | false -> None | true -> Some t.id.AsString.RDD - - let icdFnc fieldName sPresent comments = - let rows = x.createRowsFunc fieldName sPresent comments + + let icdFnc fieldName sPresent comments = + let rows = x.createRowsFunc fieldName sPresent comments rows |> List.map(fun r -> getNewSType r) - + icdFnc, x.typeAss.comments, name | Some encOptions -> - let legthDetRow = + let lengthDetRow = match encOptions.acnEncodingClass with - | SZ_EC_LENGTH_EMBEDDED nSizeInBits -> + | SZ_EC_LENGTH_EMBEDDED nSizeInBits -> let sCommentUnit = match encOptions.octOrBitStr with ContainedInOctString -> "bytes" | ContainedInBitString -> "bits" - - [ {IcdRow.fieldName = "Length"; comments = [$"The number of {sCommentUnit} used in the encoding"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengtInBits = nSizeInBits ;maxLengtInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] + + [ {IcdRow.fieldName = "Length"; comments = [$"The number of {sCommentUnit} used in the encoding"]; sPresent="always";sType=IcdPlainType "INTEGER"; sConstraint=None; minLengthInBits = nSizeInBits ;maxLengthInBits=nSizeInBits;sUnits=None; rowType = IcdRowType.LengthDeterminantRow; idxOffset = None}] | _ -> [] - let icdFnc fieldName sPresent comments = + let icdFnc fieldName sPresent comments = let rows = x.createRowsFunc fieldName sPresent comments |> List.map(fun r -> getNewSType r) - legthDetRow@rows |> List.mapi(fun i r -> {r with idxOffset = Some (i+1)}) + lengthDetRow@rows |> List.mapi(fun i r -> {r with idxOffset = Some (i+1)}) icdFnc, ("OCTET STING CONTAINING BY"::x.typeAss.comments), Some (t.id.AsString.RDD + "_OCT_STR" ) - let icd = {IcdArgAux.canBeEmbedded = x.canBeEmbedded; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=exraComment; scope="REFTYPE"; name=name} - - + let icd = {IcdArgAux.canBeEmbedded = x.canBeEmbedded; baseAsn1Kind = (getASN1Name t); rowsFunc = icdFnc; commentsForTas=extraComment; scope="REFTYPE"; name=name} - match o.encodingOptions with - | None -> + match o.encodingOptions with + | None -> match o.hasExtraConstrainsOrChildrenOrAcnArgs with | true -> match codec with | Codec.Encode -> baseType.getAcnFunction codec, us - | Codec.Decode -> + | Codec.Decode -> let paramsArgsPairs = List.zip o.acnArguments o.resolvedType.acnParameters - let baseTypeAcnFunction = baseType.getAcnFunction codec + let baseTypeAcnFunction = baseType.getAcnFunction codec let ret = match baseTypeAcnFunction with | None -> None | Some baseTypeAcnFunction -> - let funcBody us (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let funcBody us (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = baseTypeAcnFunction.funcBody us (acnArgs@paramsArgsPairs) p - Some {baseTypeAcnFunction with funcBody = funcBody} + Some {baseTypeAcnFunction with funcBody = funcBody} ret, us - | false -> - let funcBody (us:State) (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let funcBodyContent = callBaseTypeFunc lm (lm.lg.getParamValue t p.arg codec) baseFncName codec - Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false}), us + | false -> + let funcBody (us:State) (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = + let str = lm.lg.getParamValue t p.arg codec + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let toc = ToC str + toc, Some toc + | _ -> str, None + let funcBodyContent = callBaseTypeFunc lm pp baseFncName codec + Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}), us let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) - let a, ns = createAcnFunction r lm codec t typeDefinition isValidFunc funcBody (fun atc -> true) icd soSparkAnnotations us Some a, ns - | Some( encOptions) -> + | Some encOptions -> //contained type i.e. MyOct ::= OCTET STRING (CONTAINING Other-Type) let loc = o.tasName.Location let sReqBytesForUperEncoding = sprintf "%s_REQUIRED_BYTES_FOR_ACN_ENCODING" baseTypeDefinitionName let sReqBitForUperEncoding = sprintf "%s_REQUIRED_BITS_FOR_ACN_ENCODING" baseTypeDefinitionName - + let octet_string_containing_func = lm.acn.octet_string_containing_func let bit_string_containing_func = lm.acn.bit_string_containing_func let octet_string_containing_ext_field_func = lm.acn.octet_string_containing_ext_field_func let bit_string_containing_ext_field_func = lm.acn.bit_string_containing_ext_field_func - let baseTypeAcnFunction = baseType.getAcnFunction codec - - - - let funcBody (errCode:ErroCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = - let funcBodyContent = + let baseTypeAcnFunction = baseType.getAcnFunction codec + + let funcBody (errCode:ErrorCode) (acnArgs: (AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) (p:CallerScope) = + let pp, resultExpr = + let str = lm.lg.getParamValue t p.arg codec + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let toc = ToC str + toc, Some toc + | _ -> str, None + let funcBodyContent, errCodes, localVariables = match encOptions.acnEncodingClass, encOptions.octOrBitStr with - | SZ_EC_ExternalField relPath , ContainedInOctString -> + | SZ_EC_ExternalField relPath , ContainedInOctString -> let filterDependency (d:AcnDependency) = match d.dependencyKind with - | AcnDepSizeDeterminant_bit_oct_str_containt _ -> true + | AcnDepSizeDeterminant_bit_oct_str_contain _ -> true | _ -> false - - - let extField = getExternaField0 r deps t.id filterDependency - + let extField = getExternalField0 r deps t.id filterDependency let soInner, errCodes0, localVariables0 = match baseTypeAcnFunction with | None -> None, [], [] @@ -2205,58 +2180,28 @@ let createReferenceFunction (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF | None -> None, [], [] | Some r -> Some r.funcBody, r.errCodes, r.localVariables - let fncBody = octet_string_containing_ext_field_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding extField errCode.errCodeName soInner codec - Some(fncBody, errCode::errCodes0,localVariables0) - | SZ_EC_ExternalField relPath , ContainedInBitString -> - let extField = getExternaField r deps t.id - let fncBody = bit_string_containing_ext_field_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding extField errCode.errCodeName codec - Some(fncBody, [errCode],[]) - - + let fncBody = octet_string_containing_ext_field_func pp baseFncName sReqBytesForUperEncoding extField errCode.errCodeName soInner codec + fncBody, errCode::errCodes0,localVariables0 + | SZ_EC_ExternalField relPath , ContainedInBitString -> + let extField = getExternalField r deps t.id + let fncBody = bit_string_containing_ext_field_func pp baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding extField errCode.errCodeName codec + fncBody, [errCode],[] | SZ_EC_FIXED_SIZE , ContainedInOctString -> - let fncBody = octet_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding 0I encOptions.minSize.acn encOptions.maxSize.acn true codec - Some(fncBody, [errCode],[]) - | SZ_EC_LENGTH_EMBEDDED nBits , ContainedInOctString -> - let fncBody = octet_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding nBits encOptions.minSize.acn encOptions.maxSize.acn false codec - Some(fncBody, [errCode],[]) + let fncBody = octet_string_containing_func pp baseFncName sReqBytesForUperEncoding 0I encOptions.minSize.acn encOptions.maxSize.acn true codec + fncBody, [errCode],[] + | SZ_EC_LENGTH_EMBEDDED nBits , ContainedInOctString -> + let fncBody = octet_string_containing_func pp baseFncName sReqBytesForUperEncoding nBits encOptions.minSize.acn encOptions.maxSize.acn false codec + fncBody, [errCode],[] | SZ_EC_FIXED_SIZE , ContainedInBitString -> - let fncBody = bit_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding 0I encOptions.minSize.acn encOptions.maxSize.acn true codec - Some(fncBody, [errCode],[]) - | SZ_EC_LENGTH_EMBEDDED nBits , ContainedInBitString -> - let fncBody = bit_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding nBits encOptions.minSize.acn encOptions.maxSize.acn false codec - Some(fncBody, [errCode],[]) + let fncBody = bit_string_containing_func pp baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding 0I encOptions.minSize.acn encOptions.maxSize.acn true codec + fncBody, [errCode],[] + | SZ_EC_LENGTH_EMBEDDED nBits , ContainedInBitString -> + let fncBody = bit_string_containing_func pp baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding nBits encOptions.minSize.acn encOptions.maxSize.acn false codec + fncBody, [errCode],[] | SZ_EC_TerminationPattern nullVal , _ -> raise(SemanticError (loc, "Invalid type for parameter4")) - match funcBodyContent with - | None -> None - | Some (funcBodyContent,errCodes, localVariables) -> Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false}) + Some ({AcnFuncBodyResult.funcBody = funcBodyContent; errCodes = errCodes; localVariables = localVariables; bValIsUnReferenced= false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (typeDefinition.longTypedefName2 lm.lg.hasModules) codec) let a,b = createAcnFunction r lm codec t typeDefinition isValidFunc (fun us e acnArgs p -> funcBody e acnArgs p, us) (fun atc -> true) icd soSparkAnnotations us Some a, b - - - - - - - - -///////////////////////////////////// - -(* -type NewType = - | NewInt of (int*int) //min, max, ... any other related to int - | NewReal of (double*double) //min, max, ... any other related to int - | NewSequence of {|name:string; newTypeId:string|} list - -type NewTas = { - newTypeId : string - superTypeId : string option - newType : NewType -} -*) - - - - diff --git a/BackendAst/DAstAsn1.fs b/BackendAst/DAstAsn1.fs index 8c2e9ef54..d292b079a 100644 --- a/BackendAst/DAstAsn1.fs +++ b/BackendAst/DAstAsn1.fs @@ -13,7 +13,7 @@ open Asn1Fold open DAst open DAstUtilFunctions -let printComponent (c:ObjectIdentifierValueCompoent) = +let printComponent (c:ObjectIdentifierValueComponent) = match c with | ObjInteger nVal -> nVal.Value.ToString() | ObjNamedDefValue (label,(md,ts)) -> sprintf "%s(%s.%s)" label.Value md.Value ts.Value //named form, points to an integer value @@ -21,15 +21,15 @@ let printComponent (c:ObjectIdentifierValueCompoent) = | ObjRegisteredKeyword (label, nVal) -> sprintf "%s(%s)" label.Value (nVal.ToString()) // | ObjDefinedValue (md,ts) -> sprintf "%s.%s" md.Value ts.Value //named form, points to an integer value //value assignment to Integer value or ObjectIdentifier or RelativeObject -let rec printAsn1Value (v:Asn1AcnAst.Asn1Value) = +let rec printAsn1Value (v:Asn1AcnAst.Asn1Value) = match v.kind with | Asn1AcnAst.IntegerValue v -> stg_asn1.Print_IntegerValue v.Value | Asn1AcnAst.EnumValue v -> v.Value | Asn1AcnAst.RealValue v -> stg_asn1.Print_RealValue v.Value - | Asn1AcnAst.StringValue(parts,_) -> + | Asn1AcnAst.StringValue(parts,_) -> match parts with | (CStringValue v)::[] -> stg_asn1.Print_StringValue v - | _ -> stg_asn1.Print_SeqOfValue (parts |> List.map(fun p -> p.AsAsn1)) + | _ -> stg_asn1.Print_SeqOfValue (parts |> List.map(fun p -> p.AsAsn1)) | Asn1AcnAst.BooleanValue v -> stg_asn1.Print_BooleanValue v.Value | Asn1AcnAst.BitStringValue v -> stg_asn1.Print_BitStringValue v.Value | Asn1AcnAst.OctetStringValue v -> stg_asn1.Print_OctetStringValue (v |> List.map (fun b -> b.Value)) @@ -51,22 +51,22 @@ let foldGenericCon valToStrFunc (c:GenericConstraint<'v>) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc v) ,s) c 0 |> fst let foldRangeCon valToStrFunc1 valToStrFunc2 (c:RangeTypeConstraint<'v1,'v2>) = - foldRangeTypeConstraint + foldRangeTypeConstraint (fun _ e1 e2 b s -> stg_asn1.Print_UnionConstraint e1 e2, s) (fun _ e1 e2 s -> stg_asn1.Print_IntersectionConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_AllExceptConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc2 v) ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> stg_asn1.Print_RangeContraint (valToStrFunc1 v1) (valToStrFunc1 v2) minIsIn maxIsIn , s) - (fun _ v1 minIsIn s -> stg_asn1.Print_RangeContraint_val_MAX (valToStrFunc1 v1) minIsIn, s) - (fun _ v2 maxIsIn s -> stg_asn1.Print_RangeContraint_MIN_val (valToStrFunc1 v2) maxIsIn, s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc2 v) ,s) + (fun _ v1 v2 minIsIn maxIsIn s -> stg_asn1.Print_RangeConstraint (valToStrFunc1 v1) (valToStrFunc1 v2) minIsIn maxIsIn , s) + (fun _ v1 minIsIn s -> stg_asn1.Print_RangeConstraint_val_MAX (valToStrFunc1 v1) minIsIn, s) + (fun _ v2 maxIsIn s -> stg_asn1.Print_RangeConstraint_MIN_val (valToStrFunc1 v2) maxIsIn, s) c 0 |> fst @@ -80,7 +80,7 @@ let foldSizableConstraint printSingValueFunc (c:SizableTypeConstraint<'v>) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (printSingValueFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (printSingValueFunc v) ,s) (fun _ intCon s -> foldRangeCon (fun i -> i.ToString()) (fun i -> i.ToString()) intCon, s) c 0 |> fst @@ -93,7 +93,7 @@ let foldSequenceOfConstraint printSingValueFunc (c:SequenceOfConstraint) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (printSingValueFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (printSingValueFunc v) ,s) (fun _ intCon s -> foldRangeCon (fun i -> i.ToString()) (fun i -> i.ToString()) intCon, s) (fun _ c l s -> "", s) c @@ -107,9 +107,9 @@ let foldStringCon (c:IA5StringConstraint) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (stg_asn1.Print_StringValue v ),s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (stg_asn1.Print_StringValue v ),s) (fun _ intCon s -> foldRangeCon (fun i -> i.ToString()) (fun i -> i.ToString()) intCon , s) - (fun _ alphcon s -> foldRangeCon (fun i -> "\"" + i.ToString() + "\"") (fun i -> "\"" + i.ToString() + "\"") alphcon,s) + (fun _ alphcon s -> foldRangeCon (fun i -> "\"" + i.ToString() + "\"") (fun i -> "\"" + i.ToString() + "\"") alphcon,s) c 0 |> fst @@ -121,7 +121,7 @@ let foldSequenceCon valToStrFunc (c:SeqConstraint) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc v) ,s) (fun _ nc s -> "", s) c 0 |> fst @@ -134,31 +134,31 @@ let foldChoiceCon valToStrFunc (c:ChoiceConstraint) = (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc v) ,s) (fun _ nc s -> "", s) c 0 |> fst let createAcnInteger (cons:IntegerTypeConstraint list) = let conToStrFunc = foldRangeCon stg_asn1.Print_IntegerValue stg_asn1.Print_IntegerValue - cons |> List.map conToStrFunc + cons |> List.map conToStrFunc let createIntegerFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) = let conToStrFunc = foldRangeCon stg_asn1.Print_IntegerValue stg_asn1.Print_IntegerValue - o.AllCons |> List.map conToStrFunc + o.AllCons |> List.map conToStrFunc let createRealFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) = let conToStrFunc = foldRangeCon stg_asn1.Print_RealValue stg_asn1.Print_RealValue - o.AllCons |> List.map conToStrFunc + o.AllCons |> List.map conToStrFunc let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) = - let conToStrFunc = + let conToStrFunc = foldGenericCon (fun (_,coms) -> stg_asn1.Print_ObjOrRelObjIdValue (coms |> List.map printComponent)) o.AllCons |> List.map conToStrFunc let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) = - let conToStrFunc = + let conToStrFunc = foldGenericCon (fun (v:TimeValue) -> stg_asn1.Print_TimeValue (asn1DateTimeValueToString v)) o.AllCons |> List.map conToStrFunc @@ -172,8 +172,8 @@ let createBoolFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1Ac let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) = let conToStrFunc = foldGenericCon (fun b -> b) - //remove the "virtual constraint" that is added in all ENUMERAED wich constraints the type to all of each possible values - let actualConstraints = + //remove the "virtual constraint" that is added in all ENUMERATED which constraints the type to all of each possible values + let actualConstraints = o.AllCons |> List.filter(fun c -> match c with @@ -198,8 +198,8 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:As stg_asn1.Print_SeqValue arrsValues let conToStrFunc = foldSequenceCon printSeqValue o.AllCons |> List.map conToStrFunc - - + + let createChoiceFunction (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (children:ChChildInfo list) = let printChValue (ni:Asn1AcnAst.NamedValue) = stg_asn1.Print_ChValue ni.name.Value (printAsn1Value ni.Value) diff --git a/BackendAst/DAstConstruction.fs b/BackendAst/DAstConstruction.fs index 65d98d9d6..34436d18c 100644 --- a/BackendAst/DAstConstruction.fs +++ b/BackendAst/DAstConstruction.fs @@ -24,86 +24,82 @@ let private mapAcnParameter (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF //let funcUpdateStatement, ns1 = DAstACN.getUpdateFunctionUsedInEncoding r deps l m prm.id us let ns1 = us { - DastAcnParameter.asn1Type = prm.asn1Type; - name = prm.name; + DastAcnParameter.asn1Type = prm.asn1Type; + name = prm.name; loc = prm.loc id = prm.id c_name = DAstACN.getAcnDeterminantName prm.id typeDefinitionBodyWithinSeq = DAstACN.getDeterminantTypeDefinitionBodyWithinSeq r lm (Asn1AcnAst.AcnParameterDeterminant prm) - //funcUpdateStatement00 = funcUpdateStatement + //funcUpdateStatement00 = funcUpdateStatement }, ns1 let private createAcnChild (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (ch:Asn1AcnAst.AcnChild) (us:State) = - let defOrRef (a:Asn1AcnAst.AcnReferenceToEnumerated) = - match m.Name.Value = a.modName.Value with - | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName.Value) ; definedInRtl = false} - | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName.Value); typedefName = ToC (r.args.TypePrefix + a.tasName.Value); definedInRtl = false} - let acnAligment = + + let acnAlignment = match ch.Type with - | Asn1AcnAst.AcnInteger a -> a.acnAligment - | Asn1AcnAst.AcnBoolean a -> a.acnAligment - | Asn1AcnAst.AcnNullType a -> a.acnAligment - | Asn1AcnAst.AcnReferenceToEnumerated a -> a.acnAligment - | Asn1AcnAst.AcnReferenceToIA5String a -> a.acnAligment + | Asn1AcnAst.AcnInteger a -> a.acnAlignment + | Asn1AcnAst.AcnBoolean a -> a.acnAlignment + | Asn1AcnAst.AcnNullType a -> a.acnAlignment + | Asn1AcnAst.AcnReferenceToEnumerated a -> a.acnAlignment + | Asn1AcnAst.AcnReferenceToIA5String a -> a.acnAlignment - let funcBodyEncode, ns1= + let funcBodyEncode, ns1= match ch.Type with | Asn1AcnAst.AcnInteger a -> DAstACN.createAcnIntegerFunction r lm Codec.Encode ch.id a us | Asn1AcnAst.AcnBoolean a -> DAstACN.createAcnBooleanFunction r lm Codec.Encode ch.id a us | Asn1AcnAst.AcnNullType a -> DAstACN.createAcnNullTypeFunction r lm Codec.Encode ch.id a us - | Asn1AcnAst.AcnReferenceToEnumerated a -> DAstACN.createAcnEnumeratedFunction r lm Codec.Encode ch.id a (defOrRef a) us + | Asn1AcnAst.AcnReferenceToEnumerated a -> DAstACN.createAcnEnumeratedFunction r lm Codec.Encode ch.id a (defOrRef r m a) us | Asn1AcnAst.AcnReferenceToIA5String a -> DAstACN.createAcnStringFunction r deps lm Codec.Encode ch.id a us - - let funcBodyDecode, ns2 = + + let funcBodyDecode, ns2 = match ch.Type with | Asn1AcnAst.AcnInteger a -> DAstACN.createAcnIntegerFunction r lm Codec.Decode ch.id a ns1 | Asn1AcnAst.AcnBoolean a -> DAstACN.createAcnBooleanFunction r lm Codec.Decode ch.id a ns1 | Asn1AcnAst.AcnNullType a -> DAstACN.createAcnNullTypeFunction r lm Codec.Decode ch.id a ns1 - | Asn1AcnAst.AcnReferenceToEnumerated a -> DAstACN.createAcnEnumeratedFunction r lm Codec.Decode ch.id a (defOrRef a) ns1 + | Asn1AcnAst.AcnReferenceToEnumerated a -> DAstACN.createAcnEnumeratedFunction r lm Codec.Decode ch.id a (defOrRef r m a) ns1 | Asn1AcnAst.AcnReferenceToIA5String a -> DAstACN.createAcnStringFunction r deps lm Codec.Decode ch.id a ns1 - + let funcUpdateStatement, ns3 = DAstACN.getUpdateFunctionUsedInEncoding r deps lm m ch.id ns2 let c_name = DAstACN.getAcnDeterminantName ch.id - + let newFuncBody (codec:Codec) (prms:((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list)) (p:CallerScope) : (AcnFuncBodyResult option)= - let funBodyWithState st errCode prms p = + let funBodyWithState st errCode prms p = let funcBody codec = match codec with Codec.Encode -> funcBodyEncode | Codec.Decode -> funcBodyDecode funcBody codec prms p, st - let retFunc = DAstACN.handleSavePostion funBodyWithState ch.Type.savePosition c_name ch.id lm codec prms p - retFunc emptyState {ErroCode.errCodeName = ""; ErroCode.errCodeValue=0; comment=None} prms p |> fst - + let retFunc = DAstACN.handleSavePosition funBodyWithState ch.Type.savePosition c_name ch.id lm codec prms p + retFunc emptyState {ErrorCode.errCodeName = ""; ErrorCode.errCodeValue=0; comment=None} prms p |> fst - let ret = + let tdBodyWithinSeq = DAstACN.getDeterminantTypeDefinitionBodyWithinSeq r lm (Asn1AcnAst.AcnChildDeterminant ch) + let initExpression = + match ch.Type with + | Asn1AcnAst.AcnInteger _ -> "0" + | Asn1AcnAst.AcnBoolean _ -> lm.lg.FalseLiteral + | Asn1AcnAst.AcnNullType _ -> "0" + | Asn1AcnAst.AcnReferenceToEnumerated e -> + lm.lg.getNamedItemBackendName (Some (defOrRef r m e)) e.enumerated.items.Head + | Asn1AcnAst.AcnReferenceToIA5String s -> + lm.lg.initializeString (int (s.str.maxSize.acn + 1I)) + + let ret = { - + AcnChild.Name = ch.Name id = ch.id c_name = c_name Type = ch.Type - typeDefinitionBodyWithinSeq = DAstACN.getDeterminantTypeDefinitionBodyWithinSeq r lm (Asn1AcnAst.AcnChildDeterminant ch) - funcBody = DAstACN.handleAlignemntForAcnTypes r lm acnAligment newFuncBody + typeDefinitionBodyWithinSeq = tdBodyWithinSeq + funcBody = DAstACN.handleAlignmentForAcnTypes r lm acnAlignment newFuncBody funcUpdateStatement = funcUpdateStatement Comments = ch.Comments + initExpression = initExpression } AcnChild ret, ns3 type ParentInfoData = unit let private createInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (us:State) = - //let typeDefinition = DAstTypeDefinition.createInteger r l t o us let defOrRef = TL "DAstTypeDefinition" (fun () -> DAstTypeDefinition.createInteger_u r lm t o us) - (* - let automaticTestCasesIntValues = TL "EncodeDecodeTestCase" (fun () -> EncodeDecodeTestCase.IntegerAutomaticTestCaseValues r t o) - //let initialValue = - match automaticTestCasesIntValues with - | [] -> getValueByUperRange o.uperRange 0I - | x::_ -> - match automaticTestCasesIntValues |> Seq.exists ((=) 0I) with - |true -> 0I - |false -> x - *) - //let automaticTestCasesValues = automaticTestCasesIntValues |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (IntegerValue x)) let initFunction = TL "DAstInitialize" (fun () -> DAstInitialize.createIntegerInitFunc r lm t o defOrRef) let equalFunction = TL "DAstEqual" (fun () -> DAstEqual.createIntegerEqualFunction r lm t o defOrRef) let isValidFunction, s1 = TL "DastValidate2" (fun () -> DastValidate2.createIntegerFunction r lm t o defOrRef us) @@ -119,19 +115,19 @@ let private createInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Acn let xerEncFunction, s8 = TL "DAstXer" (fun () -> XER r (fun () -> DAstXer.createIntegerFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7) let xerDecFunction, s9 = TL "DAstXer" (fun () -> XER r (fun () -> DAstXer.createIntegerFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8) let xerEncDecTestFunc,s10 = TL "DAstXer" (fun () -> EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9) - + let ret = { Integer.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createIntegerFunction r lm t o + printValue = DAstVariables.createIntegerFunction r lm t o //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -147,20 +143,20 @@ let private createInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Acn let private createReal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (us:State) = //let typeDefinition = DAstTypeDefinition.createReal r l t o us let defOrRef = DAstTypeDefinition.createReal_u r lm t o us - let equalFunction = DAstEqual.createRealEqualFunction r lm t o defOrRef + let equalFunction = DAstEqual.createRealEqualFunction r lm t o defOrRef //let initialValue = getValueByUperRange o.uperRange 0.0 - let initFunction = DAstInitialize.createRealInitFunc r lm t o defOrRef + let initFunction = DAstInitialize.createRealInitFunc r lm t o defOrRef let isValidFunction, s1 = DastValidate2.createRealFunction r lm t o defOrRef us let uperEncFunction, s2 = DAstUPer.createRealFunction r lm Codec.Encode t o defOrRef None isValidFunction s1 let uperDecFunction, s3 = DAstUPer.createRealFunction r lm Codec.Decode t o defOrRef None isValidFunction s2 - let acnEncFunction, s4 = DAstACN.createRealrFunction r lm Codec.Encode t o defOrRef isValidFunction uperEncFunction s3 - let acnDecFunction, s5 = DAstACN.createRealrFunction r lm Codec.Decode t o defOrRef isValidFunction uperDecFunction s4 + let acnEncFunction, s4 = DAstACN.createRealFunction r lm Codec.Encode t o defOrRef isValidFunction uperEncFunction s3 + let acnDecFunction, s5 = DAstACN.createRealFunction r lm Codec.Decode t o defOrRef isValidFunction uperDecFunction s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.RealAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (RealValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.RealAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (RealValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createRealFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createRealFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createRealFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = @@ -168,13 +164,13 @@ let private createReal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst Real.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createRealFunction r lm t o + printValue = DAstVariables.createRealFunction r lm t o //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -192,12 +188,12 @@ let private createReal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst let private createStringType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (us:State) = let newPrms, us0 = t.acnParameters |> foldMap(fun ns p -> mapAcnParameter r deps lm m t p ns) us //let typeDefinition = DAstTypeDefinition.createString r l t o us0 - + let defOrRef = DAstTypeDefinition.createString_u r lm t o us0 //let defOrRef = DAstTypeDefinition.createString_u r l t o us0 - - let equalFunction = DAstEqual.createStringEqualFunction r lm t o defOrRef - let initFunction = DAstInitialize.createIA5StringInitFunc r lm t o defOrRef + + let equalFunction = DAstEqual.createStringEqualFunction r lm t o defOrRef + let initFunction = DAstInitialize.createIA5StringInitFunc r lm t o defOrRef let isValidFunction, s1 = DastValidate2.createStringFunction r lm t o defOrRef us let uperEncFunction, s2 = DAstUPer.createIA5StringFunction r lm Codec.Encode t o defOrRef None isValidFunction s1 let uperDecFunction, s3 = DAstUPer.createIA5StringFunction r lm Codec.Decode t o defOrRef None isValidFunction s2 @@ -205,9 +201,9 @@ let private createStringType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted let acnDecFunction, s5 = DAstACN.createStringFunction r deps lm Codec.Decode t o defOrRef defOrRef isValidFunction uperDecFunction s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - //let automaticTestCasesValues = EncodeDecodeTestCase.StringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (StringValue x)) + //let automaticTestCasesValues = EncodeDecodeTestCase.StringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (StringValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createIA5StringFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createIA5StringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createIA5StringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = @@ -215,13 +211,13 @@ let private createStringType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted StringType.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createStringFunction r lm t o + printValue = DAstVariables.createStringFunction r lm t o //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -239,8 +235,8 @@ let private createOctetString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserte let newPrms, us0 = t.acnParameters |> foldMap(fun ns p -> mapAcnParameter r deps lm m t p ns) us //let typeDefinition = DAstTypeDefinition.createOctet r l t o us0 let defOrRef = DAstTypeDefinition.createOctetString_u r lm t o us0 - let equalFunction = DAstEqual.createOctetStringEqualFunction r lm t o defOrRef - let printValue = DAstVariables.createOctetStringFunction r lm t o defOrRef + let equalFunction = DAstEqual.createOctetStringEqualFunction r lm t o defOrRef + let printValue = DAstVariables.createOctetStringFunction r lm t o defOrRef let isValidFunction, s1 = DastValidate2.createOctetStringFunction r lm t o defOrRef equalFunction printValue us let initFunction = DAstInitialize.createOctetStringInitFunc r lm t o defOrRef isValidFunction @@ -250,11 +246,11 @@ let private createOctetString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserte let acnDecFunction, s5 = DAstACN.createOctetStringFunction r deps lm Codec.Decode t o defOrRef isValidFunction uperDecFunction s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.OctetStringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (OctetStringValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.OctetStringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (OctetStringValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createOctetStringFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createOctetStringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createOctetStringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 - + let ret = { OctetString.baseInfo = o @@ -266,7 +262,7 @@ let private createOctetString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserte equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -285,7 +281,7 @@ let private createNullType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Ac //let typeDefinition = DAstTypeDefinition.createNull r l t o us let defOrRef = DAstTypeDefinition.createNull_u r lm t o us let equalFunction = DAstEqual.createNullTypeEqualFunction r lm t o defOrRef - let initFunction = DAstInitialize.createNullTypeInitFunc r lm t o defOrRef + let initFunction = DAstInitialize.createNullTypeInitFunc r lm t o defOrRef let uperEncFunction, s2 = DAstUPer.createNullTypeFunction r lm Codec.Encode t o defOrRef None None us let uperDecFunction, s3 = DAstUPer.createNullTypeFunction r lm Codec.Decode t o defOrRef None None s2 let acnEncFunction, s4 = DAstACN.createNullTypeFunction r lm Codec.Encode t o defOrRef None s3 @@ -293,19 +289,19 @@ let private createNullType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Ac let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction None (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction None (Some acnEncFunction) (Some acnDecFunction) s6 let xerEncFunction, s8 = XER r (fun () -> DAstXer.createNullTypeFunction r lm Codec.Encode t o defOrRef None s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createNullTypeFunction r lm Codec.Decode t o defOrRef None s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createNullTypeFunction r lm Codec.Decode t o defOrRef None s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction None xerEncFunction xerDecFunction s9 let ret = { NullType.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createNullTypeFunction r lm t o + printValue = DAstVariables.createNullTypeFunction r lm t o //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -323,9 +319,9 @@ let private createBitString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF let newPrms, us0 = t.acnParameters |> foldMap(fun ns p -> mapAcnParameter r deps lm m t p ns) us //let typeDefinition = DAstTypeDefinition.createBitString r l t o us0 let defOrRef = DAstTypeDefinition.createBitString_u r lm t o us - - let equalFunction = DAstEqual.createBitStringEqualFunction r lm t o defOrRef - let printValue = DAstVariables.createBitStringFunction r lm t o defOrRef + + let equalFunction = DAstEqual.createBitStringEqualFunction r lm t o defOrRef + let printValue = DAstVariables.createBitStringFunction r lm t o defOrRef let isValidFunction, s1 = DastValidate2.createBitStringFunction r lm t o defOrRef defOrRef equalFunction printValue us let initFunction = DAstInitialize.createBitStringInitFunc r lm t o defOrRef isValidFunction @@ -335,9 +331,9 @@ let private createBitString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF let acnDecFunction, s5 = DAstACN.createBitStringFunction r deps lm Codec.Decode t o defOrRef isValidFunction uperDecFunction s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.BitStringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (BitStringValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.BitStringAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (BitStringValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createBitStringFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createBitStringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createBitStringFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = { @@ -350,7 +346,7 @@ let private createBitString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -367,9 +363,9 @@ let private createBitString (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedF let private createBoolean (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (us:State) = //let typeDefinition = DAstTypeDefinition.createBoolean r l t o us let defOrRef = DAstTypeDefinition.createBoolean_u r lm t o us - let equalFunction = DAstEqual.createBooleanEqualFunction r lm t o defOrRef + let equalFunction = DAstEqual.createBooleanEqualFunction r lm t o defOrRef //let initialValue = false - let initFunction = DAstInitialize.createBooleanInitFunc r lm t o defOrRef + let initFunction = DAstInitialize.createBooleanInitFunc r lm t o defOrRef let isValidFunction, s1 = DastValidate2.createBoolFunction r lm t o defOrRef us let uperEncFunction, s2 = DAstUPer.createBooleanFunction r lm Codec.Encode t o defOrRef None isValidFunction s1 let uperDecFunction, s3 = DAstUPer.createBooleanFunction r lm Codec.Decode t o defOrRef None isValidFunction s2 @@ -377,22 +373,22 @@ let private createBoolean (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Acn let acnDecFunction, s5 = DAstACN.createBooleanFunction r lm Codec.Decode t o defOrRef None isValidFunction s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.BooleanAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (BooleanValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.BooleanAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (BooleanValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createBooleanFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createBooleanFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createBooleanFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = { Boolean.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createBooleanFunction r lm t o + printValue = DAstVariables.createBooleanFunction r lm t o //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -409,7 +405,7 @@ let private createBoolean (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Acn let private createEnumerated (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (us:State) = //let typeDefinition = DAstTypeDefinition.createEnumerated r l t o us let defOrRef = DAstTypeDefinition.createEnumerated_u r lm t o us - let equalFunction = DAstEqual.createEnumeratedEqualFunction r lm t o defOrRef + let equalFunction = DAstEqual.createEnumeratedEqualFunction r lm t o defOrRef let initialValue =o.items.Head.Name.Value let initFunction = DAstInitialize.createEnumeratedInitFunc r lm t o defOrRef (EnumValue initialValue) @@ -422,9 +418,9 @@ let private createEnumerated (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm: let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.EnumeratedAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (EnumValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.EnumeratedAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (EnumValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createEnumeratedFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createEnumeratedFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createEnumeratedFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = @@ -432,13 +428,13 @@ let private createEnumerated (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm: Enumerated.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createEnumeratedFunction r lm t o defOrRef + printValue = DAstVariables.createEnumeratedFunction r lm t o defOrRef //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -461,7 +457,7 @@ let private createEnumerated (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (lm: let private createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (us:State) = //let typeDefinition = DAstTypeDefinition.createEnumerated r l t o us let defOrRef = DAstTypeDefinition.createObjectIdentifier_u r lm t o us - let equalFunction = DAstEqual.createObjectIdentifierEqualFunction r lm t o defOrRef + let equalFunction = DAstEqual.createObjectIdentifierEqualFunction r lm t o defOrRef let initialValue = InternalObjectIdentifierValue([]) let initFunction = DAstInitialize.createObjectIdentifierInitFunc r lm t o defOrRef (ObjOrRelObjIdValue initialValue) @@ -474,9 +470,9 @@ let private createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) ( let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.ObjectIdentifierAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (ObjOrRelObjIdValue (InternalObjectIdentifierValue x))) + let automaticTestCasesValues = EncodeDecodeTestCase.ObjectIdentifierAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (ObjOrRelObjIdValue (InternalObjectIdentifierValue x))) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createObjectIdentifierFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createObjectIdentifierFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createObjectIdentifierFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = @@ -484,13 +480,13 @@ let private createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) ( ObjectIdentifier.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createObjectIdentifierFunction r lm t o defOrRef + printValue = DAstVariables.createObjectIdentifierFunction r lm t o defOrRef //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -506,12 +502,12 @@ let private createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) ( let private createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (us:State) = let defOrRef = DAstTypeDefinition.createTimeType_u r lm t o us - let equalFunction = DAstEqual.createTimeTypeEqualFunction r lm t o defOrRef + let equalFunction = DAstEqual.createTimeTypeEqualFunction r lm t o defOrRef let initialValue = (EncodeDecodeTestCase.TimeTypeAutomaticTestCaseValues r t o).Head let initFunction = DAstInitialize.createTimeTypeInitFunc r lm t o defOrRef (TimeValue initialValue) let isValidFunction, s1 = DastValidate2.createTimeTypeFunction r lm t o defOrRef us - + let uperEncFunction, s2 = DAstUPer.createTimeTypeFunction r lm Codec.Encode t o defOrRef None isValidFunction s1 let uperDecFunction, s3 = DAstUPer.createTimeTypeFunction r lm Codec.Decode t o defOrRef None isValidFunction s2 @@ -520,9 +516,9 @@ let private createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Ac let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 - let automaticTestCasesValues = EncodeDecodeTestCase.TimeTypeAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (TimeValue x)) + let automaticTestCasesValues = EncodeDecodeTestCase.TimeTypeAutomaticTestCaseValues r t o |> List.mapi (fun i x -> createAsn1ValueFromValueKind t i (TimeValue x)) let xerEncFunction, s8 = XER r (fun () -> DAstXer.createTimeTypeFunction r lm Codec.Encode t o defOrRef isValidFunction s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createTimeTypeFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createTimeTypeFunction r lm Codec.Decode t o defOrRef isValidFunction s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = @@ -530,13 +526,13 @@ let private createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Ac TimeType.baseInfo = o //typeDefinition = typeDefinition definitionOrRef = defOrRef - printValue = DAstVariables.createTimeTypeFunction r lm t o defOrRef + printValue = DAstVariables.createTimeTypeFunction r lm t o defOrRef //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -560,19 +556,19 @@ let private createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1Ac let private createSequenceOf (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (pi : Asn1Fold.ParentInfo option) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (childType:Asn1Type, us:State) = let newPrms, us0 = t.acnParameters |> foldMap(fun ns p -> mapAcnParameter r deps lm m t p ns) us - let defOrRef = DAstTypeDefinition.createSequenceOf_u r lm t o childType.typeDefintionOrReference us0 + let defOrRef = DAstTypeDefinition.createSequenceOf_u r lm t o childType.typeDefinitionOrReference us0 //let typeDefinition = DAstTypeDefinition.createSequenceOf r l t o childType.typeDefinition us0 let equalFunction = DAstEqual.createSequenceOfEqualFunction r lm t o defOrRef childType - let initFunction = DAstInitialize.createSequenceOfInitFunc r lm t o defOrRef childType + let initFunction = DAstInitialize.createSequenceOfInitFunc r lm t o defOrRef childType let isValidFunction, s1 = DastValidate2.createSequenceOfFunction r lm t o defOrRef childType equalFunction us0 let uperEncFunction, s2 = DAstUPer.createSequenceOfFunction r lm Codec.Encode t o defOrRef None isValidFunction childType s1 let uperDecFunction, s3 = DAstUPer.createSequenceOfFunction r lm Codec.Decode t o defOrRef None isValidFunction childType s2 - let acnEncFunction, s4 = DAstACN.createSequenceOfFunction r deps lm Codec.Encode t o defOrRef defOrRef isValidFunction childType s3 - let acnDecFunction, s5 = DAstACN.createSequenceOfFunction r deps lm Codec.Decode t o defOrRef defOrRef isValidFunction childType s4 + let acnEncFunction, s4 = DAstACN.createSequenceOfFunction r deps lm Codec.Encode t o defOrRef isValidFunction childType s3 + let acnDecFunction, s5 = DAstACN.createSequenceOfFunction r deps lm Codec.Decode t o defOrRef isValidFunction childType s4 let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some acnEncFunction) (Some acnDecFunction) s6 let xerEncFunction, s8 = XER r (fun () -> DAstXer.createSequenceOfFunction r lm Codec.Encode t o defOrRef isValidFunction childType s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createSequenceOfFunction r lm Codec.Decode t o defOrRef isValidFunction childType s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createSequenceOfFunction r lm Codec.Decode t o defOrRef isValidFunction childType s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 let ret = { @@ -581,12 +577,12 @@ let private createSequenceOf (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted definitionOrRef = defOrRef printValue = DAstVariables.createSequenceOfFunction r lm t o defOrRef childType //typeDefinition = typeDefinition - //initialValue = initialValue + //initialValue = initialValue initFunction = initFunction equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -602,9 +598,9 @@ let private createSequenceOf (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInserted let private createAsn1Child (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (ch:Asn1AcnAst.Asn1Child) (newChildType : Asn1Type, us:State) = - let ret = + let ret = { - + Asn1Child.Name = ch.Name _c_name = ch._c_name _scala_name = ch._scala_name @@ -627,7 +623,7 @@ let private createSequence (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi let equalFunction = TL "SQ_DAstEqual" (fun () -> DAstEqual.createSequenceEqualFunction r lm t o defOrRef children) let initFunction = TL "SQ_DAstInitialize" (fun () -> DAstInitialize.createSequenceInitFunc r lm t o defOrRef children ) let isValidFunction, s1 = TL "SQ_DAstInitialize" (fun () -> DastValidate2.createSequenceFunction r lm t o defOrRef children us) - + let uperEncFunction, s2 = TL "SQ_DAstUPer" (fun () ->DAstUPer.createSequenceFunction r lm Codec.Encode t o defOrRef isValidFunction children s1) let uperDecFunction, s3 = TL "SQ_DAstUPer" (fun () ->DAstUPer.createSequenceFunction r lm Codec.Decode t o defOrRef isValidFunction children s2) let acnEncFunction, s4 = TL "SQ_DAstACN" (fun () ->DAstACN.createSequenceFunction r deps lm Codec.Encode t o defOrRef isValidFunction children newPrms s3) @@ -649,7 +645,7 @@ let private createSequence (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFi equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -690,7 +686,7 @@ let private createChoice (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction acnDecFunction = acnDecFunction uperEncDecTestFunc = uperEncDecTestFunc @@ -705,12 +701,12 @@ let private createChoice (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFiel ((Choice ret),newPrms), s10 let private createChoiceChild (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (ch:Asn1AcnAst.ChChildInfo) (newChildType : Asn1Type, us:State) = - let typeDefinitionName = + let typeDefinitionName = let longName = newChildType.id.AcnAbsPath.Tail |> List.rev |> List.tail |> List.rev |> Seq.StrJoin "_" ToC2(r.args.TypePrefix + longName.Replace("#","elem")) - let ret = + let ret = { - + ChChildInfo.Name = ch.Name _c_name = ch._c_name _scala_name = ch._scala_name @@ -737,15 +733,15 @@ let private createReferenceType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInser let uperDecFunction, s3 = DAstUPer.createReferenceFunction r lm Codec.Decode t o defOrRef isValidFunction newResolvedType s2 let acnEncFunction, s4 = DAstACN.createReferenceFunction r deps lm Codec.Encode t o defOrRef isValidFunction newResolvedType s3 let acnDecFunction, s5 = DAstACN.createReferenceFunction r deps lm Codec.Decode t o defOrRef isValidFunction newResolvedType s4 - + let uperEncDecTestFunc,s6 = EncodeDecodeTestCase.createUperEncDecFunction r lm t defOrRef equalFunction isValidFunction (Some uperEncFunction) (Some uperDecFunction) s5 let acnEncDecTestFunc ,s7 = EncodeDecodeTestCase.createAcnEncDecFunction r lm t defOrRef equalFunction isValidFunction acnEncFunction acnDecFunction s6 let xerEncFunction, s8 = XER r (fun () -> DAstXer.createReferenceFunction r lm Codec.Encode t o defOrRef isValidFunction newResolvedType s7) s7 - let xerDecFunction, s9 = XER r (fun () -> DAstXer.createReferenceFunction r lm Codec.Decode t o defOrRef isValidFunction newResolvedType s8) s8 + let xerDecFunction, s9 = XER r (fun () -> DAstXer.createReferenceFunction r lm Codec.Decode t o defOrRef isValidFunction newResolvedType s8) s8 let xerEncDecTestFunc,s10 = EncodeDecodeTestCase.createXerEncDecFunction r lm t defOrRef equalFunction isValidFunction xerEncFunction xerDecFunction s9 - let ret = + let ret = { ReferenceType.baseInfo = o resolvedType = newResolvedType @@ -757,7 +753,7 @@ let private createReferenceType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInser equalFunction = equalFunction isValidFunction = isValidFunction uperEncFunction = uperEncFunction - uperDecFunction = uperDecFunction + uperDecFunction = uperDecFunction acnEncFunction = acnEncFunction.Value acnDecFunction = acnDecFunction.Value uperEncDecTestFunc = uperEncDecTestFunc @@ -771,12 +767,12 @@ let private createReferenceType (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInser ((ReferenceType ret),newPrms), s10 let private createType (r:Asn1AcnAst.AstRoot) pi (t:Asn1AcnAst.Asn1Type) ((newKind, newPrms), (us:State )) = - let newAsn1Type = + let newAsn1Type = { Asn1Type.Kind = newKind id = t.id - acnAligment = t.acnAligment - acnParameters = newPrms + acnAlignment = t.acnAlignment + acnParameters = newPrms Location = t.Location moduleName = t.moduleName inheritInfo = t.inheritInfo @@ -793,17 +789,17 @@ let private mapType (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1Acn Asn1Fold.foldType2 (fun pi t ti us -> TL "createInteger" (fun () -> createInteger r lm m pi t ti us)) (fun pi t ti us -> TL "createReal" (fun () -> createReal r lm m pi t ti us)) - (fun pi t ti us -> + (fun pi t ti us -> let (strtype, prms), ns = TL "createStringType" (fun () -> createStringType r deps lm m pi t ti us) ((IA5String strtype),prms), ns) - (fun pi t ti us -> + (fun pi t ti us -> let (strtype, prms), ns = TL "createStringType" (fun () -> createStringType r deps lm m pi t ti us) ((IA5String strtype),prms), ns) (fun pi t ti us -> TL "createOctetString" (fun () -> createOctetString r deps lm m pi t ti us)) (fun pi t ti us -> TL "createTimeType" (fun () -> createTimeType r lm m pi t ti us)) (fun pi t ti us -> TL "createNullType" (fun () -> createNullType r lm m pi t ti us)) (fun pi t ti us -> TL "createBitString" (fun () -> createBitString r deps lm m pi t ti us)) - + (fun pi t ti us -> TL "createBoolean" (fun () -> createBoolean r lm m pi t ti us)) (fun pi t ti us -> TL "createEnumerated" (fun () -> createEnumerated r icdStgFileName lm m pi t ti us)) (fun pi t ti us -> TL "createObjectIdentifier" (fun () -> createObjectIdentifier r lm m pi t ti us)) @@ -813,12 +809,12 @@ let private mapType (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1Acn (fun pi t ti newChildren -> TL "createSequence" (fun () -> createSequence r deps lm m pi t ti newChildren)) (fun ch newChild -> TL "createAsn1Child" (fun () -> createAsn1Child r lm m ch newChild)) (fun ch us -> TL "createAcnChild" (fun () -> createAcnChild r deps lm m ch us)) - + (fun pi t ti newChildren -> TL "createChoice" (fun () -> createChoice r deps lm m pi t ti newChildren)) (fun ch newChild -> TL "createChoiceChild" (fun () -> createChoiceChild r lm m ch newChild)) - (fun pi t ti newBaseType -> + (fun pi t ti newBaseType -> TL "createReferenceType" (fun () -> createReferenceType r deps lm m pi t ti newBaseType)) (fun pi t ((newKind, newPrms),us) -> TL "createType" (fun () -> createType r pi t ((newKind, newPrms),us))) @@ -830,8 +826,8 @@ let private mapType (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1Acn deps None t - us - + us + let private mapTypeId (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (t:Asn1AcnAst.Asn1Type) = Asn1Fold.foldType2 @@ -843,7 +839,7 @@ let private mapTypeId (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldD (fun pi t ti us -> [t.id], us) (fun pi t ti us -> [t.id], us) (fun pi t ti us -> [t.id], us) - + (fun pi t ti us -> [t.id], us) (fun pi t ti us -> [t.id], us) (fun pi t ti us -> [t.id], us) @@ -853,7 +849,7 @@ let private mapTypeId (r:Asn1AcnAst.AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldD (fun pi t ti (newChildren,_) -> (newChildren|> List.collect id)@[t.id], 0) (fun ch (newChild,_) -> newChild, 0) (fun ch us -> [ch.id], us) - + (fun pi t ti (newChildren,_) -> (newChildren|> List.collect id)@[t.id], 0) (fun ch (newChild,_) -> newChild, 0) @@ -887,16 +883,16 @@ let private mapTas (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1AcnA let private mapVas (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (allNewTypeAssignments : (Asn1Module*TypeAssignment) list) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (vas:Asn1AcnAst.ValueAssignment) (us:State)= - let newType, ns = + let newType, ns = match vas.Type.Kind with | Asn1AcnAst.ReferenceType ref -> //let aaa = allNewTypeAssignments |> Seq.map(fun tz -> sprintf "%s.%s") match allNewTypeAssignments |> Seq.tryFind(fun (tm, ts) -> ts.Name.Value = ref.tasName.Value && ref.modName.Value = tm.Name.Value) with - | None -> + | None -> let oldType = Asn1AcnAstUtilFunctions.GetActualTypeByName r ref.modName ref.tasName mapType r icdStgFileName deps lm m (oldType, us) - | Some (mt, newTas) -> - let (newKind, newPrms),ns = createReferenceType r deps lm m None vas.Type ref (newTas.Type, us) + | Some (mt, newTas) -> + let (newKind, newPrms),ns = createReferenceType r deps lm m None vas.Type ref (newTas.Type, us) createType r None vas.Type ((newKind, newPrms),us) //newTas.Type, us | _ -> mapType r icdStgFileName deps lm m (vas.Type, us) @@ -911,8 +907,6 @@ let private mapVas (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (allNewTypeAss let private mapModule (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lm:LanguageMacros) (m:Asn1AcnAst.Asn1Module) (us:State) = let newTases, ns1 = TL "mapTas" (fun () -> m.TypeAssignments |> foldMap (fun ns nt -> mapTas r icdStgFileName deps lm m nt ns) us) - //let newTases = m.TypeAssignments |> List.toArray |> Microsoft.FSharp.Collections.Array.Parallel.map (fun nt -> mapTas r deps l m nt us) |> Array.toList |> List.unzip |> fst - //let ns1 = us { Asn1Module.Name = m.Name @@ -944,10 +938,10 @@ let private reMapFile (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (files0:Asn let DoWork (r:Asn1AcnAst.AstRoot) (icdStgFileName:string) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (lang:CommonTypes.ProgrammingLanguage) (lm:LanguageMacros) (encodings: CommonTypes.Asn1Encoding list) : AstRoot= let l = lang - let typeIdsSet = - r.Files |> - Seq.collect(fun f -> f.Modules) |> - Seq.collect(fun m -> m.TypeAssignments) |> + let typeIdsSet = + r.Files |> + Seq.collect(fun f -> f.Modules) |> + Seq.collect(fun m -> m.TypeAssignments) |> Seq.collect(fun tas -> mapTypeId r deps tas.Type) |> Seq.map(fun tid -> ToC (tid.AcnAbsPath.Tail.StrJoin("_").Replace("#","elem"))) |> Seq.groupBy id |> diff --git a/BackendAst/DAstEqual.fs b/BackendAst/DAstEqual.fs index a1e809085..c0724061d 100644 --- a/BackendAst/DAstEqual.fs +++ b/BackendAst/DAstEqual.fs @@ -24,80 +24,80 @@ let isEqualBodyPrimitive (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = let isEqualBodyString (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = - Some (lm.equal.isEqual_String v1.arg.p v2.arg.p , []) + Some (lm.equal.isEqual_String (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) , []) let isEqualBodyObjectIdentifier (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = Some (lm.equal.isObjectIdentifier_equal (lm.lg.getPointer v1.arg) (lm.lg.getPointer v2.arg), []) let isEqualBodyTimeType (o:Asn1AcnAst.TimeType) (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = - let namespacePrefix = lm.lg.rtlModuleName - let getRtlTypeName = + let namespacePrefix = lm.lg.rtlModuleName + let getRtlTypeName = match o.timeClass with - |Asn1LocalTime _ -> lm.typeDef.Declare_Asn1LocalTimeNoRTL - |Asn1UtcTime _ -> lm.typeDef.Declare_Asn1UtcTimeNoRTL - |Asn1LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1LocalTimeWithTimeZoneNoRTL - |Asn1Date -> lm.typeDef.Declare_Asn1DateNoRTL - |Asn1Date_LocalTime _ -> lm.typeDef.Declare_Asn1Date_LocalTimeNoRTL - |Asn1Date_UtcTime _ -> lm.typeDef.Declare_Asn1Date_UtcTimeNoRTL - |Asn1Date_LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1Date_LocalTimeWithTimeZoneNoRTL + |Asn1LocalTime _ -> lm.typeDef.Declare_Asn1LocalTimeNoRTL + |Asn1UtcTime _ -> lm.typeDef.Declare_Asn1UtcTimeNoRTL + |Asn1LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1LocalTimeWithTimeZoneNoRTL + |Asn1Date -> lm.typeDef.Declare_Asn1DateNoRTL + |Asn1Date_LocalTime _ -> lm.typeDef.Declare_Asn1Date_LocalTimeNoRTL + |Asn1Date_UtcTime _ -> lm.typeDef.Declare_Asn1Date_UtcTimeNoRTL + |Asn1Date_LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1Date_LocalTimeWithTimeZoneNoRTL let timeTypeName = getRtlTypeName () Some (sprintf "%s%s_equal(%s, %s)" namespacePrefix timeTypeName (lm.lg.getPointer v1.arg) (lm.lg.getPointer v2.arg) , []) let isEqualBodyOctetString (lm:LanguageMacros) sMin sMax (v1:CallerScope) (v2:CallerScope) = - let v1 = sprintf "%s%s" v1.arg.p (lm.lg.getAccess v1.arg) - let v2 = sprintf "%s%s" v2.arg.p (lm.lg.getAccess v2.arg) + let v1 = sprintf "%s%s" (v1.arg.joined lm.lg) (lm.lg.getAccess v1.arg) + let v2 = sprintf "%s%s" (v2.arg.joined lm.lg) (lm.lg.getAccess v2.arg) Some (lm.equal.isEqual_OctetString v1 v2 (sMin = sMax) sMax, []) let isEqualBodyBitString (lm:LanguageMacros) sMin sMax (v1:CallerScope) (v2:CallerScope) = - let v1 = sprintf "%s%s" v1.arg.p (lm.lg.getAccess v1.arg) - let v2 = sprintf "%s%s" v2.arg.p (lm.lg.getAccess v2.arg) + let v1 = sprintf "%s%s" (v1.arg.joined lm.lg) (lm.lg.getAccess v1.arg) + let v2 = sprintf "%s%s" (v2.arg.joined lm.lg) (lm.lg.getAccess v2.arg) Some (lm.equal.isEqual_BitString v1 v2 (sMin = sMax) sMax, []) -let isEqualBodySequenceChild (lm:LanguageMacros) (o:Asn1AcnAst.Asn1Child) (newChild:Asn1Type) (v1:CallerScope) (v2:CallerScope) = - let c_name = lm.lg.getAsn1ChildBackendName0 o +let isEqualBodySequenceChild (lm:LanguageMacros) (o:Asn1AcnAst.Asn1Child) (newChild:Asn1Type) (v1:CallerScope) (v2:CallerScope) = + let c_name = lm.lg.getAsn1ChildBackendName0 o let callChildEqualFunc = lm.equal.callChildEqualFunc - let sInnerStatement = - let chp1 = {v1 with arg = lm.lg.getSeqChild v1.arg c_name newChild.isIA5String false} - let chp2 = {v2 with arg = lm.lg.getSeqChild v2.arg c_name newChild.isIA5String false} + let sInnerStatement = + let chp1 = {v1 with arg = lm.lg.getSeqChild v1.arg c_name newChild.isIA5String o.Optionality.IsSome} + let chp2 = {v2 with arg = lm.lg.getSeqChild v2.arg c_name newChild.isIA5String o.Optionality.IsSome} match newChild.equalFunction.isEqualFuncName with | None -> match newChild.equalFunction.isEqualBody with - | EqualBodyExpression func -> + | EqualBodyExpression func -> match func chp1 chp2 with | Some (exp, lvars) -> Some (sprintf "ret %s (%s);" lm.lg.AssignOperator exp, lvars) | None -> None - | EqualBodyStatementList func -> func ({v1 with arg = lm.lg.getSeqChild v1.arg c_name newChild.isIA5String false}) ({v2 with arg = lm.lg.getSeqChild v2.arg c_name newChild.isIA5String false}) + | EqualBodyStatementList func -> func chp1 chp2 | Some fncName -> - Some ((callChildEqualFunc (lm.lg.getPointer chp1.arg) (lm.lg.getPointer chp2.arg) fncName), []) + Some ((callChildEqualFunc (lm.lg.getPointer chp1.arg) (lm.lg.getPointer chp2.arg) fncName), []) match sInnerStatement with - | None when o.Optionality.IsSome -> Some (lm.equal.isEqual_Sequence_child v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) o.Optionality.IsSome c_name None, []) + | None when o.Optionality.IsSome -> Some (lm.equal.isEqual_Sequence_child (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) o.Optionality.IsSome c_name None, []) | None -> None - | Some (sInnerStatement, lvars) -> Some (lm.equal.isEqual_Sequence_child v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) o.Optionality.IsSome c_name (Some sInnerStatement), lvars) + | Some (sInnerStatement, lvars) -> Some (lm.equal.isEqual_Sequence_child (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) o.Optionality.IsSome c_name (Some sInnerStatement), lvars) -let isEqualBodyChoiceChild (choiceTypeDefName:string) (lm:LanguageMacros) (o:Asn1AcnAst.ChChildInfo) (newChild:Asn1Type) (v1:CallerScope) (v2:CallerScope) = +let isEqualBodyChoiceChild (choiceTypeDefName:string) (lm:LanguageMacros) (o:Asn1AcnAst.ChChildInfo) (newChild:Asn1Type) (v1:CallerScope) (v2:CallerScope) = let p1,p2 = match ST.lang with | ProgrammingLanguage.Scala -> - ({v1 with arg = lm.lg.getChChild v1.arg (sprintf "%s_%s_tmp" v1.arg.p (lm.lg.getAsn1ChChildBackendName0 o)) newChild.isIA5String}), - ({v2 with arg = lm.lg.getChChild v2.arg (sprintf "%s_%s_tmp" v2.arg.p (lm.lg.getAsn1ChChildBackendName0 o)) newChild.isIA5String}) + ({v1 with arg = lm.lg.getChChild v1.arg (sprintf "%s_%s_tmp" (v1.arg.joined lm.lg) (lm.lg.getAsn1ChChildBackendName0 o)) newChild.isIA5String}), + ({v2 with arg = lm.lg.getChChild v2.arg (sprintf "%s_%s_tmp" (v2.arg.joined lm.lg) (lm.lg.getAsn1ChChildBackendName0 o)) newChild.isIA5String}) | _ -> ({v1 with arg = lm.lg.getChChild v1.arg (lm.lg.getAsn1ChChildBackendName0 o) newChild.isIA5String}), ({v2 with arg = lm.lg.getChChild v2.arg (lm.lg.getAsn1ChChildBackendName0 o) newChild.isIA5String}) - + let sInnerStatement, lvars = match newChild.equalFunction.isEqualFuncName with | None -> match newChild.equalFunction.isEqualBody with - | EqualBodyExpression func -> + | EqualBodyExpression func -> match func p1 p2 with | Some (exp, lvars) -> sprintf "ret %s (%s);" lm.lg.AssignOperator exp, lvars | None -> sprintf "ret %s %s;" lm.lg.AssignOperator lm.lg.TrueLiteral, [] - | EqualBodyStatementList func -> + | EqualBodyStatementList func -> match func p1 p2 with | Some a -> a | None -> sprintf "ret %s %s;" lm.lg.AssignOperator lm.lg.TrueLiteral, [] @@ -105,31 +105,31 @@ let isEqualBodyChoiceChild (choiceTypeDefName:string) (lm:LanguageMacros) (o:A let exp = callBaseTypeFunc lm (lm.lg.getPointer p1.arg) (lm.lg.getPointer p2.arg) fncName makeExpressionToStatement lm exp, [] - lm.equal.isEqual_Choice_Child choiceTypeDefName o.presentWhenName sInnerStatement p1.arg.p p2.arg.p, lvars + lm.equal.isEqual_Choice_Child choiceTypeDefName o.presentWhenName sInnerStatement (p1.arg.joined lm.lg) (p2.arg.joined lm.lg), lvars -let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefintionOrReference) = +let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefinitionOrReference) = //getFuncNameGeneric r "_Equal" tasInfo inhInfo typeKind typeDefinition getFuncNameGeneric typeDefinition "_Equal" -let createEqualFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) isEqualBody = +let createEqualFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) isEqualBody = let equalTypeAssignment = lm.equal.equalTypeAssignment let equalTypeAssignment_def = lm.equal.equalTypeAssignment_def let alwaysTrue = lm.lg.TrueLiteral - let p1 = lm.lg.getParamTypeSuffix t "1" CommonTypes.Codec.Encode + let p1 = lm.lg.getParamTypeSuffix t "1" CommonTypes.Codec.Encode let p2 = lm.lg.getParamTypeSuffix t "2" CommonTypes.Codec.Encode let funcName = getFuncName r lm typeDefinition - let varName1 = p1.arg.p - let varName2 = p2.arg.p + let varName1 = p1.arg.receiverId + let varName2 = p2.arg.receiverId let sStar = lm.lg.getStar p1.arg - let isEqualFunc, isEqualFuncDef = + let isEqualFunc, isEqualFuncDef = match funcName with | None -> None, None - | Some funcName -> + | Some funcName -> let content, lvars, bExp, bUnreferenced = match isEqualBody with | EqualBodyExpression expFunc -> @@ -142,7 +142,7 @@ let createEqualFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac | None -> alwaysTrue, [], true, true let lvarsStr = lvars |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct let isEqualFunc = equalTypeAssignment varName1 varName2 sStar funcName (lm.lg.getLongTypedefName typeDefinition) content lvarsStr bExp bUnreferenced - let isEqualFuncDef = equalTypeAssignment_def varName1 varName2 sStar funcName (lm.lg.getLongTypedefName typeDefinition) + let isEqualFuncDef = equalTypeAssignment_def varName1 varName2 sStar funcName (lm.lg.getLongTypedefName typeDefinition) Some isEqualFunc, Some isEqualFuncDef { @@ -150,79 +150,79 @@ let createEqualFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac isEqualBody = isEqualBody isEqualFunc = isEqualFunc isEqualFuncDef = isEqualFuncDef - } + } let castRPp (lm:LanguageMacros) codec realClass pp = - match codec with - | CommonTypes.Encode -> + match codec with + | CommonTypes.Encode -> match realClass with | Asn1AcnAst.ASN1SCC_REAL -> pp - | Asn1AcnAst.ASN1SCC_FP32 -> (lm.lg.castExpression pp (lm.typeDef.Declare_Real())) + | Asn1AcnAst.ASN1SCC_FP32 -> (lm.lg.castExpression pp (lm.typeDef.Declare_Real())) | Asn1AcnAst.ASN1SCC_FP64 -> pp | CommonTypes.Decode -> pp -let createIntegerEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) = +let createIntegerEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyPrimitive lm ) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createRealEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) = +let createRealEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) = let isEqualBodyPrimitive (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = - let castPp pp = castRPp lm Encode (o.getClass r.args) pp - let pp1 = (lm.lg.getValue v1.arg) + let castPp pp = castRPp lm Encode (o.getClass r.args) pp + let pp1 = (lm.lg.getValue v1.arg) let pp2 = (lm.lg.getValue v2.arg) Some(lm.equal.isEqual_Real (castPp pp1) (castPp pp2), []) let isEqualBody = EqualBodyExpression (isEqualBodyPrimitive lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createBooleanEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) = +let createBooleanEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyPrimitive lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createEnumeratedEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) = +let createEnumeratedEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyPrimitive lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createObjectIdentifierEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) = +let createObjectIdentifierEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyObjectIdentifier lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createTimeTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefintionOrReference) = +let createTimeTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyTimeType o lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) = +let createStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (isEqualBodyString lm) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createNullTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefintionOrReference) = +let createNullTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = EqualBodyExpression (fun v1 v2 -> None) - createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) + createEqualFunction_any r lm t typeDefinition isEqualBody //(stgPrintEqualPrimitive l) (stgMacroPrimDefFunc l) -let createOctetStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) = +let createOctetStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = isEqualBodyOctetString lm ( o.minSize.uper) ( o.maxSize.uper) createEqualFunction_any r lm t typeDefinition (EqualBodyExpression isEqualBody) - //createOctetOrBitStringEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) + //createOctetOrBitStringEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) -let createBitStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) = +let createBitStringEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) = let isEqualBody = isEqualBodyBitString lm ( o.minSize.uper) ( o.maxSize.uper) createEqualFunction_any r lm t typeDefinition (EqualBodyExpression isEqualBody) - //createOctetOrBitStringEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) + //createOctetOrBitStringEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) -let createSequenceOfEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (childType:Asn1Type) = +let createSequenceOfEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (childType:Asn1Type) = let isEqualBodySequenceOf (childType:Asn1Type) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (lm:LanguageMacros) (v1:CallerScope) (v2:CallerScope) = - let getInnerStatement i = + let getInnerStatement i = let childAccesPath (p:CallerScope) = {p with arg = lm.lg.getArrayItem p.arg i childType.isIA5String} //v + childAccess + l.ArrName + (l.ArrayAccess i) //"[" + i + "]" match childType.equalFunction.isEqualFuncName with | None -> match childType.equalFunction.isEqualBody with - | EqualBodyExpression func -> + | EqualBodyExpression func -> match func (childAccesPath v1) (childAccesPath v2) with | Some (exp, lvars) -> Some (sprintf "ret %s (%s);" lm.lg.AssignOperator exp, lvars) // ret = (boolExp); | None -> None @@ -233,66 +233,66 @@ let createSequenceOfEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t: let exp = callBaseTypeFunc lm (lm.lg.getPointer p1.arg) (lm.lg.getPointer p2.arg) fncName Some(makeExpressionToStatement lm exp, []) - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) match getInnerStatement i with | None when o.minSize.uper = o.maxSize.uper -> None | None -> - Some (lm.equal.isEqual_SequenceOf_var_size v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) i None, []) + Some (lm.equal.isEqual_SequenceOf_var_size (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) i None, []) | Some (innerStatement, lvars) -> match (o.minSize.uper = o.maxSize.uper) with - | true -> Some (lm.equal.isEqual_SequenceOf_fix_size v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) i ( o.minSize.uper) innerStatement, lv::lvars) - | false -> Some (lm.equal.isEqual_SequenceOf_var_size v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) i (Some innerStatement), lv::lvars) + | true -> Some (lm.equal.isEqual_SequenceOf_fix_size (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) i ( o.minSize.uper) innerStatement, lv::lvars) + | false -> Some (lm.equal.isEqual_SequenceOf_var_size (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) i (Some innerStatement), lv::lvars) let isEqualBody = isEqualBodySequenceOf childType t o lm createEqualFunction_any r lm t typeDefinition (EqualBodyStatementList isEqualBody) - //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) + //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) -let createSequenceEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (children:SeqChildInfo list) = - let isEqualBodySequence (lm:LanguageMacros) (children:SeqChildInfo list) (v1:CallerScope) (v2:CallerScope) = - let printChild (content:string, lvars:LocalVariable list) (sNestedContent:string option) = +let createSequenceEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (children:SeqChildInfo list) = + let isEqualBodySequence (lm:LanguageMacros) (children:SeqChildInfo list) (v1:CallerScope) (v2:CallerScope) = + let printChild (content:string, lvars:LocalVariable list) (sNestedContent:string option) = match sNestedContent with | None -> content, lvars | Some c-> lm.equal.JoinItems content sNestedContent, lvars - let rec printChildren children : Option> = + let rec printChildren children : Option> = match children with |[] -> None - |x::xs -> + |x::xs -> match printChildren xs with | None -> Some (printChild x None) - | Some (childrenCont, lvars) -> + | Some (childrenCont, lvars) -> let content, lv = printChild x (Some childrenCont) Some (content, lv@lvars) - - let childrenConent = - children |> - List.choose(fun c -> match c with Asn1Child x -> Some x | AcnChild _ -> None) |> + + let childrenConent = + children |> + List.choose(fun c -> match c with Asn1Child x -> Some x | AcnChild _ -> None) |> List.choose(fun c -> c.isEqualBodyStats v1 v2 ) printChildren childrenConent let isEqualBody = isEqualBodySequence lm children createEqualFunction_any r lm t typeDefinition (EqualBodyStatementList isEqualBody) - //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) + //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) -let createChoiceEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (children:ChChildInfo list) = - let isEqualBodyChoice (typeDefinition:TypeDefintionOrReference) (lm:LanguageMacros) (children:ChChildInfo list) (v1:CallerScope) (v2:CallerScope) = - let childrenConent,lvars = - children |> +let createChoiceEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (children:ChChildInfo list) = + let isEqualBodyChoice (typeDefinition:TypeDefinitionOrReference) (lm:LanguageMacros) (children:ChChildInfo list) (v1:CallerScope) (v2:CallerScope) = + let childrenConent,lvars = + children |> List.map(fun c -> c.isEqualBodyStats v1 v2) |> List.unzip let lvars = lvars |> List.collect id - Some(lm.equal.isEqual_Choice v1.arg.p v2.arg.p (lm.lg.getAccess v1.arg) childrenConent, lvars) + Some(lm.equal.isEqual_Choice (v1.arg.joined lm.lg) (v2.arg.joined lm.lg) (lm.lg.getAccess v1.arg) childrenConent, lvars) let isEqualBody = isEqualBodyChoice typeDefinition lm children createEqualFunction_any r lm t typeDefinition (EqualBodyStatementList isEqualBody) - //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) + //createCompositeEqualFunction r l lm t typeDefinition isEqualBody (stgMacroCompDefFunc l) -let createReferenceTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (defOrRef:TypeDefintionOrReference) (baseType:Asn1Type) = +let createReferenceTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (defOrRef:TypeDefinitionOrReference) (baseType:Asn1Type) = //let isEqualFuncName = getEqualFuncName r l lm t.id let isEqualFuncName = getFuncName r lm defOrRef let typeDefinitionName = lm.lg.getLongTypedefName defOrRef - let moduleName, typeDefinitionName0 = + let moduleName, typeDefinitionName0 = match defOrRef with | ReferenceToExistingDefinition refToExist -> match refToExist.programUnit with @@ -301,7 +301,7 @@ let createReferenceTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) | TypeDefinition tdDef -> match tdDef.baseType with | None -> ToC t.id.ModName, tdDef.typedefName - | Some refToExist -> + | Some refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName | None -> ToC t.id.ModName, refToExist.typedefName @@ -310,59 +310,55 @@ let createReferenceTypeEqualFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) let baseTypeDefName = typeDefinitionName0//ToC2(r.args.TypePrefix + o.tasName.Value) - let baseEqName = + let baseEqName = match lm.lg.hasModules with | false -> baseTypeDefName + "_Equal" - | true -> + | true -> match t.id.ModName = o.modName.Value with | true -> baseTypeDefName + "_Equal" | false -> moduleName + "." + baseTypeDefName + "_Equal" - + match baseType.Kind with | Integer _ | Real _ | Boolean _ | Enumerated _ | NullType _ - | IA5String _ + | IA5String _ | ReferenceType _ -> let bs = baseType.equalFunction createEqualFunction_any r lm t defOrRef bs.isEqualBody | OctetString _ - | BitString _ + | BitString _ | ObjectIdentifier _ | TimeType _ | SequenceOf _ | Sequence _ - | Choice _ -> - - let isEqualBody = - let eqBody (p1:CallerScope) (p2:CallerScope) = - let exp = callBaseTypeFunc lm (lm.lg.getPointer p1.arg) (lm.lg.getPointer p2.arg) baseEqName - Some(makeExpressionToStatement lm exp, []) - eqBody - + | Choice _ -> + let isEqualBody (p1:CallerScope) (p2:CallerScope) = + let exp = callBaseTypeFunc lm (lm.lg.getPointer p1.arg) (lm.lg.getPointer p2.arg) baseEqName + Some(makeExpressionToStatement lm exp, []) - let val1 = lm.lg.getParamTypeSuffix t "1" CommonTypes.Codec.Encode + let val1 = lm.lg.getParamTypeSuffix t "1" CommonTypes.Codec.Encode let val2 = lm.lg.getParamTypeSuffix t "2" CommonTypes.Codec.Encode - let stgMacroDefFunc = lm.equal.PrintEqualDefintionComposite - - let isEqualFunc, isEqualFuncDef = - match isEqualFuncName with - | None -> None, None - | Some funcName -> - match isEqualBody val1 val2 with - | Some (funcBody,lvars) -> - let lvars = lvars |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct - Some (lm.equal.PrintEqualComposite funcName typeDefinitionName funcBody lvars), Some (stgMacroDefFunc funcName typeDefinitionName) - | None -> None, None + let stgMacroDefFunc = lm.equal.PrintEqualDefinitionComposite + + let isEqualFunc, isEqualFuncDef = + match isEqualFuncName with + | None -> None, None + | Some funcName -> + match isEqualBody val1 val2 with + | Some (funcBody,lvars) -> + let lvars = lvars |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct + Some (lm.equal.PrintEqualComposite funcName typeDefinitionName funcBody lvars), Some (stgMacroDefFunc funcName typeDefinitionName) + | None -> None, None { EqualFunction.isEqualFuncName = isEqualFuncName isEqualBody = EqualBodyStatementList (isEqualBody ) isEqualFunc = isEqualFunc isEqualFuncDef = isEqualFuncDef - } + } diff --git a/BackendAst/DAstEqualExp.fs b/BackendAst/DAstEqualExp.fs index 95d920d78..74a038515 100644 --- a/BackendAst/DAstEqualExp.fs +++ b/BackendAst/DAstEqualExp.fs @@ -25,6 +25,6 @@ type TC_Function = { } -let getFuncName (r:Asn1AcnAst.AstRoot) (typeDefinition:TypeDefintionOrReference) = +let getFuncName (r:Asn1AcnAst.AstRoot) (typeDefinition:TypeDefinitionOrReference) = getFuncNameGeneric typeDefinition "_Equal" diff --git a/BackendAst/DAstExportToXml.fs b/BackendAst/DAstExportToXml.fs index a832394ec..226b3418d 100644 --- a/BackendAst/DAstExportToXml.fs +++ b/BackendAst/DAstExportToXml.fs @@ -29,187 +29,187 @@ let exportElement (tagName:string) (cnt:string) = -let private exportType (r:AstRoot) (t:Asn1Type) = +let private exportType (r:AstRoot) (t:Asn1Type) = foldAsn1Type t () - (fun t ti us -> + (fun t ti us -> XElement(xname "INTEGER", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) - ), us ) + ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "REAL", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "IA5STRING", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "OctetString", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "Null", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "BitString", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "Boolean", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "Enumerated", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) // (exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), // (exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "ObjectIdentifier", XAttribute(xname "id", t.id.AsString), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) ), us ) - (fun t ti us -> + (fun t ti us -> XElement(xname "TIME", XAttribute(xname "id", t.id.AsString), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind) + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind) ), us ) - (fun t ti (child,us) -> + (fun t ti (child,us) -> XElement(xname "SEQUENCEOF", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind), + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind), child //(exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), //(exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq) ), us ) - (fun t ti ch (chType, us) -> + (fun t ti ch (chType, us) -> XElement(xname "SEQUENCE_COMPONENT", XAttribute(xname "Name", ch.Name.Value), (ExportToXml.exportOptionality ch.Optionality ), chType), us ) - (fun t ti ch us -> + (fun t ti ch us -> XElement(xname "ACN_COMPONENT", XAttribute(xname "Name", ch.Name.Value), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )) ), us ) - (fun t ti (children,us) -> + (fun t ti (children,us) -> XElement(xname "SEQUENCE", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind), + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind), //(exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), //(exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq), children ), us ) - - (fun t ti ch (chType, us) -> + + (fun t ti ch (chType, us) -> XElement(xname "CHOICE_ALTERNATIVE", XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "PresentWhenName", ch.presentWhenName (Some ch.chType.typeDefintionOrReference) Ada), + XAttribute(xname "PresentWhenName", ch.presentWhenName (Some ch.chType.typeDefinitionOrReference) Ada), XAttribute(xname "AdaName", (ch.getBackendName Ada)), XAttribute(xname "CName", (ch.getBackendName C)), XAttribute(xname "ScalaName", (ch.getBackendName Scala)), XAttribute(xname "AcnPresentWhenCont", (ch.acnPresentWhenConditions |> List.map(fun pwc -> sprintf "%s = %s" pwc.relativePath.AsString pwc.valueAsString) |> Seq.StrJoin ", ")), chType), us ) - (fun t ti (children, us) -> + (fun t ti (children, us) -> XElement(xname "CHOICE", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), XAttribute(xname "newTypedefName2", (ti.baseInfo.typeDef.[CommonTypes.ProgrammingLanguage.C].typeName)), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind), + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind), XAttribute(xname "ancEncClass", ti.ancEncClass.ToString()), //(exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), @@ -217,18 +217,18 @@ let private exportType (r:AstRoot) (t:Asn1Type) = children ), us ) - (fun t ti (baseType,us) -> + (fun t ti (baseType,us) -> XElement(xname "REFERENCE_TYPE", XAttribute(xname "id", t.id.AsString), //(match t.parInfoData with Some pi-> (XAttribute(xname "parentData.typedefName",pi.parentData.typedefName)) | None -> null), // XAttribute(xname "typeDefinition.name", ti.typeDefinition.name), // XAttribute(xname "typeDefinition.typeDefinitionBodyWithinSeq", ti.typeDefinition.typeDefinitionBodyWithinSeq), - XAttribute(xname "newTypedefName", (t.typeDefintionOrReference.longTypedefName2 true)), - XAttribute(xname "typeDefintionOrReference", (match t.typeDefintionOrReference with ReferenceToExistingDefinition r -> "ReferenceToExistingDefinition" | TypeDefinition td -> "TypeDefinition" )), + XAttribute(xname "newTypedefName", (t.typeDefinitionOrReference.longTypedefName2 true)), + XAttribute(xname "typeDefinitionOrReference", (match t.typeDefinitionOrReference with ReferenceToExistingDefinition r -> "ReferenceToExistingDefinition" | TypeDefinition td -> "TypeDefinition" )), XAttribute(xname "Module", ti.baseInfo.modName.Value), XAttribute(xname "TypeAssignment", ti.baseInfo.tasName.Value), - XAttribute(xname "newTypedefName2", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].typeName), - XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].kind), + XAttribute(xname "newTypedefName2", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].typeName), + XAttribute(xname "newTypedefName2_kind", t.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].kind), //(exportElement "CompleteDefinition" ti.typeDefinition.completeDefinition), //(exportOptionalElement "CompleteDefinitionWithinSeq" ti.typeDefinition.completeDefinitionWithinSeq), (match ti.baseInfo.acnArguments with @@ -236,9 +236,9 @@ let private exportType (r:AstRoot) (t:Asn1Type) = | args -> [XElement(xname "AcnArguments", (args |> List.map ExportToXml.exprtRefTypeArgument) )]), baseType), us ) - (fun o newKind -> - let a = o.FT_TypeDefintion.[CommonTypes.ProgrammingLanguage.C].typeName - let b = o.typeDefintionOrReference.longTypedefName2 false + (fun o newKind -> + let a = o.FT_TypeDefinition.[CommonTypes.ProgrammingLanguage.C].typeName + let b = o.typeDefinitionOrReference.longTypedefName2 false match a = b with | true -> () | false -> ()//printfn "@@@@@@@@@@ %s FE='%s' B='%s'" o.id.AsString a b diff --git a/BackendAst/DAstInitialize.fs b/BackendAst/DAstInitialize.fs index 4e8229d15..f5d3846d5 100644 --- a/BackendAst/DAstInitialize.fs +++ b/BackendAst/DAstInitialize.fs @@ -28,13 +28,13 @@ create procedures that initialize an ASN.1 type. let rangeConstraint2RangeSet (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.RangeTypeConstraint<'v,'v>) st = - foldRangeTypeConstraint - (fun _ (e1:RangeSet<'v>) e2 b s -> e1.union e2, s) - (fun _ e1 e2 s -> e1.intersect e2, s) - (fun _ e s -> e.complement, s) - (fun _ e1 e2 s -> e1.difference e2, s) - (fun _ e s -> e,s) - (fun _ e1 e2 s -> e1.union e2, s) + foldRangeTypeConstraint + (fun _ (e1:RangeSet<'v>) e2 b s -> e1.union e2, s) + (fun _ e1 e2 s -> e1.intersect e2, s) + (fun _ e s -> e.complement, s) + (fun _ e1 e2 s -> e1.difference e2, s) + (fun _ e s -> e,s) + (fun _ e1 e2 s -> e1.union e2, s) (fun _ v s -> RangeSet<'v>.createFromSingleValue v ,s) (fun _ v1 v2 minIsIn maxIsIn s -> RangeSet<'v>.createFromValuePair v1 v2 minIsIn maxIsIn, s) (fun _ v1 minIsIn s -> RangeSet<'v>.createPosInfinite v1 minIsIn, s) @@ -46,13 +46,13 @@ let rangeConstraint2RangeSet (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.RangeTypeCons let genericConstraint2ValueSet (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.GenericConstraint<'v>) st = - foldGenericConstraint - (fun _ (e1:ValueSet<'v>) e2 b s -> e1.union e2, s) - (fun _ e1 e2 s -> e1.intersect e2, s) - (fun _ e s -> e.complement, s) - (fun _ e1 e2 s -> e1.difference e2, s) - (fun _ e s -> e,s) - (fun _ e1 e2 s -> e1.union e2, s) + foldGenericConstraint + (fun _ (e1:ValueSet<'v>) e2 b s -> e1.union e2, s) + (fun _ e1 e2 s -> e1.intersect e2, s) + (fun _ e s -> e.complement, s) + (fun _ e1 e2 s -> e1.difference e2, s) + (fun _ e s -> e,s) + (fun _ e1 e2 s -> e1.union e2, s) (fun _ v s -> ValueSet<'v>.createFromSingleValue v ,s) c st @@ -68,20 +68,20 @@ let objectIdConstraint2StringSet r (c:Asn1AcnAst.ObjectIdConstraint) = genericCo -let foldSizeRangeTypeConstraint (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.PosIntTypeConstraint) st = +let foldSizeRangeTypeConstraint (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.PosIntTypeConstraint) st = rangeConstraint2RangeSet r c st //SizeableSet let foldSizableConstraint (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.SizableTypeConstraint<'v>) st = - foldSizableTypeConstraint2 - (fun _ (e1:SizeableSet<'v>) e2 b s -> e1.union e2, s) - (fun _ e1 e2 s -> e1.intersect e2, s) - (fun _ e s -> e.complement, s) - (fun _ e1 e2 s -> e1.difference e2, s) - (fun _ e s -> e,s) - (fun _ e1 e2 s -> e1.union e2, s) + foldSizableTypeConstraint2 + (fun _ (e1:SizeableSet<'v>) e2 b s -> e1.union e2, s) + (fun _ e1 e2 s -> e1.intersect e2, s) + (fun _ e s -> e.complement, s) + (fun _ e1 e2 s -> e1.difference e2, s) + (fun _ e s -> e,s) + (fun _ e1 e2 s -> e1.union e2, s) (fun _ v s -> SizeableSet<'v>.createFromSingleValue v ,s) - (fun _ intCon s -> + (fun _ intCon s -> let sizeRange, ns = foldSizeRangeTypeConstraint r intCon s SizeableSet<'v>.createFromSizeRange sizeRange, ns) c @@ -96,22 +96,22 @@ let bitConstraint2Set r (c:Asn1AcnAst.BitStringConstraint) = foldSizableConstrai let ia5StringConstraint2Set (r:Asn1AcnAst.AstRoot) (c:Asn1AcnAst.IA5StringConstraint) (us0:State) = - foldStringTypeConstraint2 - (fun _ (e1:SizeableSet) e2 b s -> e1.union e2, s) - (fun _ e1 e2 s -> e1.intersect e2, s) - (fun _ e s -> e.complement, s) - (fun _ e1 e2 s -> e1.difference e2, s) - (fun _ e s -> e,s) - (fun _ e1 e2 s -> e1.union e2, s) + foldStringTypeConstraint2 + (fun _ (e1:SizeableSet) e2 b s -> e1.union e2, s) + (fun _ e1 e2 s -> e1.intersect e2, s) + (fun _ e s -> e.complement, s) + (fun _ e1 e2 s -> e1.difference e2, s) + (fun _ e s -> e,s) + (fun _ e1 e2 s -> e1.union e2, s) (fun _ v s -> SizeableSet.createFromSingleValue v ,s) - (fun _ intCon s -> + (fun _ intCon s -> let sizeRange, ns = foldSizeRangeTypeConstraint r intCon s SizeableSet.createFromSizeRange sizeRange, ns) - (fun _ alphcon s -> + (fun _ alphcon s -> //currently the alphabet constraints are ignored ... - Range2D ({sizeSet = Range_Universe; valueSet = SsUniverse}) , s) + Range2D ({sizeSet = Range_Universe; valueSet = SsUniverse}) , s) c - us0 + us0 type AnySet = @@ -123,7 +123,7 @@ type AnySet = | NulSet | BoolSet of ValueSet | EnumSet of ValueSet - | ObjIdSet of ValueSet + | ObjIdSet of ValueSet | SeqOfSet of SizeableSet and SequenceOfSet = { @@ -138,124 +138,75 @@ type SequenceOfSet with let rec anyConstraint2GenericSet (r:Asn1AcnAst.AstRoot) (erLoc:SrcLoc) (t:Asn1Type) (ac:Asn1AcnAst.AnyConstraint) st = match t.ActualType.Kind, ac with - | Integer o, Asn1AcnAst.IntegerTypeConstraint c -> + | Integer o, Asn1AcnAst.IntegerTypeConstraint c -> let set, ns = integerConstraint2BigIntSet r c st IntSet set, ns - | Real o, Asn1AcnAst.RealTypeConstraint c -> + | Real o, Asn1AcnAst.RealTypeConstraint c -> let set, ns = realConstraint2DoubleSet r c st RealSet set, ns - | IA5String o, Asn1AcnAst.IA5StringConstraint c -> + | IA5String o, Asn1AcnAst.IA5StringConstraint c -> let set, ns = ia5StringConstraint2Set r c st StrSet set, ns - | OctetString o, Asn1AcnAst.OctetStringConstraint c -> + | OctetString o, Asn1AcnAst.OctetStringConstraint c -> let set, ns = octetConstraint2Set r c st OctSet set, ns - | BitString o, Asn1AcnAst.BitStringConstraint c -> + | BitString o, Asn1AcnAst.BitStringConstraint c -> let set, ns = bitConstraint2Set r c st BitSet set, ns | NullType o, Asn1AcnAst.NullConstraint -> NulSet, st - | Boolean o, Asn1AcnAst.BoolConstraint c -> + | Boolean o, Asn1AcnAst.BoolConstraint c -> let set, ns = boolConstraint2BoolSet r c st BoolSet set, ns - | Enumerated o, Asn1AcnAst.EnumConstraint c -> + | Enumerated o, Asn1AcnAst.EnumConstraint c -> let set, ns = enumConstraint2StringSet r c st EnumSet set, ns - | ObjectIdentifier o, Asn1AcnAst.ObjectIdConstraint c -> + | ObjectIdentifier o, Asn1AcnAst.ObjectIdConstraint c -> let set, ns = objectIdConstraint2StringSet r c st ObjIdSet set, ns -// | Sequence o, Asn1AcnAst.SeqConstraint c -> -// let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.SeqValue) = VCBTrue //currently single value constraints are ignored. -// sequenceConstraint2ValidationCodeBlock r l t.id o.Asn1Children valToStrFunc c st -// | SequenceOf o, Asn1AcnAst.SequenceOfConstraint c -> sequenceOfConstraint2ValidationCodeBlock r l t.id o.baseInfo o.childType o.equalFunction c st -// | Choice o, Asn1AcnAst.ChoiceConstraint c -> -// let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.ChValue) = VCBTrue //currently single value constraints are ignored. -// choiceConstraint2ValidationCodeBlock r l t.id o.children valToStrFunc o.definitionOrRef c st | _ -> raise(SemanticError(erLoc, "Invalid combination of type/constraint type")) - - - - - - -//and sequenceOfConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (child:Asn1Type) (c:Asn1AcnAst.SequenceOfConstraint) st = -// foldSequenceOfTypeConstraint2 -// (fun (e1:SizeableSet<'v>) e2 b s -> e1.union e2, s) -// (fun e1 e2 s -> e1.intersect e2, s) -// (fun e s -> e.complement, s) -// (fun e1 e2 s -> e1.difference e2, s) -// (fun e s -> e,s) -// (fun e1 e2 s -> e1.union e2, s) -// (fun v s -> SizeableSet<'v>.createFromSingleValue v ,s) -// (fun intCon s -> -// let sizeRange, ns = foldSizeRangeTypeConstraint r intCon s -// SizeableSet<'v>.createFromSizeRange sizeRange, ns) -// (fun c loc s -> -// let fnc, ns = anyConstraint2GenericSet r loc child c s -// -// 0, s) -// c -// st - - - - - - - - - - - - - - - - - - -let getFuncName2 (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefintionOrReference) = +let getFuncName2 (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefinitionOrReference) = getFuncNameGeneric typeDefinition (lm.init.methodNameSuffix()) -let createInitFunctionCommon (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (o:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (defaultInitValue: String) initByAsn1Value (initTasFunction:CallerScope -> InitFunctionResult) automaticTestCases (initExpression:string) (initExpressionGlobal:string) (nonEmbeddedChildrenFuncs:InitFunction list) (user_aux_functions:(string*string) list) = +let createInitFunctionCommon (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (o:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) initByAsn1Value (initTasFunction:CallerScope -> InitFunctionResult) automaticTestCases (initExpression:string) (initExpressionGlobal:string) (nonEmbeddedChildrenFuncs:InitFunction list) (user_aux_functions:(string*string) list) = let funcName = getFuncName2 r lm typeDefinition let globalName = getFuncNameGeneric typeDefinition "_constant" - let p = lm.lg.getParamType o CommonTypes.Codec.Decode + let p = lm.lg.getParamType o CommonTypes.Codec.Decode let initTypeAssignment = lm.init.initTypeAssignment let initTypeAssignment_def = lm.init.initTypeAssignment_def - let varName = p.arg.p + let varName = p.arg.receiverId let sPtrPrefix = lm.lg.getPtrPrefix p.arg let sPtrSuffix = lm.lg.getPtrSuffix p.arg let sStar = lm.lg.getStar p.arg let initDef = lm.init.initTypeConstant_def let initBody = lm.init.initTypeConstant_body let tdName = lm.lg.getLongTypedefName typeDefinition - let initProcedure = + let initProcedure = match funcName with | None -> None - | Some funcName -> - match r.args.generateConstInitGlobals && globalName.IsSome with + | Some funcName -> + match r.args.generateConstInitGlobals && globalName.IsSome with | true -> let funcBody = lm.init.assignAny (lm.lg.getValue p.arg) globalName.Value tdName - let func = initTypeAssignment varName sPtrPrefix sPtrSuffix funcName tdName funcBody [] defaultInitValue + let func = initTypeAssignment varName sPtrPrefix sPtrSuffix funcName tdName funcBody [] initExpression let funcDef = initTypeAssignment_def varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) Some {InitProcedure0.funcName = funcName; def = funcDef; body=func} | false -> - let res = initTasFunction p + let res = initTasFunction p let lvars = res.localVariables |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> List.distinct - let func = initTypeAssignment varName sPtrPrefix sPtrSuffix funcName tdName res.funcBody lvars defaultInitValue - let funcDef = initTypeAssignment_def varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) + let func = initTypeAssignment varName sPtrPrefix sPtrSuffix funcName tdName res.funcBody lvars initExpression + let funcDef = initTypeAssignment_def varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) Some {InitProcedure0.funcName = funcName; def = funcDef; body=func} { initExpression = initExpression initExpressionGlobal = initExpressionGlobal initProcedure = initProcedure - initFunction = + initFunction = funcName |> Option.map(fun n -> {InitProcedure0.funcName = n; def = initDef tdName n initExpression; body=initBody tdName n initExpression}) - initGlobal = + initGlobal = globalName |> Option.map(fun n -> {|globalName = n; def = initDef tdName n initExpressionGlobal; body=initBody tdName n initExpressionGlobal|}) initTas = initTasFunction initByAsn1Value = initByAsn1Value @@ -264,78 +215,78 @@ let createInitFunctionCommon (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (o:Asn1A nonEmbeddedChildrenFuncs = nonEmbeddedChildrenFuncs } -let createIntegerInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) = +let createIntegerInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) = let initInteger = lm.init.initInteger - - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with | IntegerValue iv -> iv | _ -> raise(BugErrorException "UnexpectedValue") initInteger (lm.lg.getValue p.arg) vl let integerVals = EncodeDecodeTestCase.IntegerAutomaticTestCaseValues r t o - + let allCons = DastValidate2.getIntSimplifiedConstraints r o.isUnsigned o.AllCons - let isZeroAllowed = isValidValueRanged allCons 0I - let tasInitFunc (p:CallerScope) = + let isZeroAllowed = isValidValueRanged allCons 0I + let tasInitFunc (p:CallerScope) = match isZeroAllowed with - | false -> - match integerVals with - |x::_ -> {InitFunctionResult.funcBody = initInteger (lm.lg.getValue p.arg) x; localVariables=[]} + | false -> + match integerVals with + |x::_ -> {InitFunctionResult.funcBody = initInteger (lm.lg.getValue p.arg) x; localVariables=[]} | [] -> {InitFunctionResult.funcBody = initInteger (lm.lg.getValue p.arg) 0I; localVariables=[]} | true -> {InitFunctionResult.funcBody = initInteger (lm.lg.getValue p.arg) 0I; localVariables=[]} let constantInitExpression = match isZeroAllowed with - | false -> - match integerVals with + | false -> + match integerVals with |x::_ -> lm.lg.intValueToString x (o.intClass) | [] -> lm.lg.intValueToString 0I (o.intClass) | true -> lm.lg.intValueToString 0I (o.intClass) - - let testCaseFuncs = - integerVals |> - List.map (fun vl -> + + let testCaseFuncs = + integerVals |> + List.map (fun vl -> let initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initInteger (lm.lg.getValue p.arg) vl; localVariables=[]} ) {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] } ) - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] -let createRealInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) = +let createRealInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) = let initReal = lm.init.initReal - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with | RealValue iv -> iv | _ -> raise(BugErrorException "UnexpectedValue") initReal (lm.lg.getValue p.arg) vl let realVals = EncodeDecodeTestCase.RealAutomaticTestCaseValues r t o - let testCaseFuncs = - realVals |> - List.map (fun vl -> - let initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) vl; localVariables=[]}) + let testCaseFuncs = + realVals |> + List.map (fun vl -> + let initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) vl; localVariables=[]}) {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] } ) let isZeroAllowed = isValidValueRanged o.AllCons 0.0 - let tasInitFunc (p:CallerScope) = + let tasInitFunc (p:CallerScope) = match isZeroAllowed with - | false -> - match realVals with - | x::_ -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) x; localVariables=[]} + | false -> + match realVals with + | x::_ -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) x; localVariables=[]} | [] -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) 0.0; localVariables=[]} | true -> {InitFunctionResult.funcBody = initReal (lm.lg.getValue p.arg) 0.0; localVariables=[]} let constantInitExpression = match isZeroAllowed with - | false -> - match realVals with + | false -> + match realVals with |x::_ -> lm.lg.doubleValueToString x | [] -> lm.lg.doubleValueToString 0.0 | true -> lm.lg.doubleValueToString 0.0 - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] let fragmentationCases seqOfCase maxSize = [ @@ -348,212 +299,206 @@ let fragmentationCases seqOfCase maxSize = seqOfCase (16384I + 1I) seqOfCase (16384I + 150I) ] -let createIA5StringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.StringType ) (typeDefinition:TypeDefintionOrReference) = +let createIA5StringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.StringType ) (typeDefinition:TypeDefinitionOrReference) = let initIA5String = lm.init.initIA5String let initTestCaseIA5String = lm.init.initTestCaseIA5String let strTypeDef = lm.lg.getStrTypeDefinition o.typeDef - - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with - | StringValue iv -> + | StringValue iv -> iv | _ -> raise(BugErrorException "UnexpectedValue") - let tlLit = DAstVariables.converStringValue2TargetLangStringLiteral lm (int o.maxSize.uper) vl + let tlLit = DAstVariables.convertStringValue2TargetLangStringLiteral lm (int o.maxSize.uper) vl initIA5String (lm.lg.getValue p.arg) tlLit - let ii = t.id.SeqeuenceOfLevel + 1 + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii - //let visibleChars = o.uperCharSet |> Seq.filter(fun c -> not (System.Char.IsControl c)) let bAlpha = o.uperCharSet.Length < 128 let arrAsciiCodes = o.uperCharSet |> Array.map(fun x -> BigInteger (System.Convert.ToInt32 x)) - let testCaseFuncs = - let seqOfCase (nSize:BigInteger) = - let initTestCaseFunc (p:CallerScope) = + let testCaseFuncs = + let seqOfCase (nSize:BigInteger) = + let initTestCaseFunc (p:CallerScope) = let td = strTypeDef.longTypedefName2 (lm.lg.hasModules) (ToC p.modName) - let funcBody = initTestCaseIA5String p.arg.p (lm.lg.getAccess p.arg) (nSize) ((o.maxSize.uper+1I)) i td bAlpha arrAsciiCodes (BigInteger arrAsciiCodes.Length) false + let funcBody = initTestCaseIA5String (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (nSize) ((o.maxSize.uper+1I)) i td bAlpha arrAsciiCodes (BigInteger arrAsciiCodes.Length) false {InitFunctionResult.funcBody = funcBody; localVariables=[SequenceOfIndex (ii, None)]} {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvSizeableTypeValue nSize)] } seq { match o.minSize.uper = o.maxSize.uper with - | true -> yield seqOfCase o.minSize.uper - | false -> - yield seqOfCase o.minSize.uper + | true -> yield seqOfCase o.minSize.uper + | false -> + yield seqOfCase o.minSize.uper yield seqOfCase o.maxSize.uper match o.maxSize.uper > 65536I with //fragmentation cases | true -> yield! fragmentationCases seqOfCase o.maxSize.uper | false -> () } |> Seq.toList - let zero (p:CallerScope) = + let zero (p:CallerScope) = let td = strTypeDef.longTypedefName2 (lm.lg.hasModules) (ToC p.modName) - let funcBody = initTestCaseIA5String p.arg.p (lm.lg.getAccess p.arg) ( (o.maxSize.uper+1I)) ( (o.maxSize.uper+1I)) i td bAlpha arrAsciiCodes (BigInteger arrAsciiCodes.Length) true + let funcBody = initTestCaseIA5String (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) ( (o.maxSize.uper+1I)) ( (o.maxSize.uper+1I)) i td bAlpha arrAsciiCodes (BigInteger arrAsciiCodes.Length) true let lvars = lm.lg.init.zeroIA5String_localVars ii {InitFunctionResult.funcBody = funcBody; localVariables=lvars} let constantInitExpression = lm.lg.initializeString (int o.maxSize.uper) - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody zero testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody zero testCaseFuncs constantInitExpression constantInitExpression [] [] -let createOctetStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.OctetString ) (typeDefinition:TypeDefintionOrReference) (isValidFunction:IsValidFunction option) = +let createOctetStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.OctetString ) (typeDefinition:TypeDefinitionOrReference) (isValidFunction:IsValidFunction option) = let initFixSizeBitOrOctString_bytei = lm.init.initFixSizeBitOrOctString_bytei let initFixSizeBitOrOctString = lm.init.initFixSizeBitOrOctString let initFixVarSizeBitOrOctString = lm.init.initFixVarSizeBitOrOctString let initTestCaseOctetString = lm.init.initTestCaseOctetString - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let bytes = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let bytes = match v.ActualValue with | OctetStringValue iv -> iv | BitStringValue iv -> bitStringValueToByteArray (StringLoc.ByValue iv) |> Seq.toList | _ -> raise(BugErrorException "UnexpectedValue") - let arrsBytes = bytes |> List.mapi(fun i b -> initFixSizeBitOrOctString_bytei p.arg.p (lm.lg.getAccess p.arg) ((i + lm.lg.ArrayStartIndex).ToString()) (sprintf "%x" b)) + let arrsBytes = bytes |> List.mapi(fun i b -> initFixSizeBitOrOctString_bytei (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) ((i + lm.lg.ArrayStartIndex).ToString()) (sprintf "%x" b)) match o.isFixedSize with - | true -> initFixSizeBitOrOctString p.arg.p (lm.lg.getAccess p.arg) arrsBytes - | false -> initFixVarSizeBitOrOctString p.arg.p (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes - + | true -> initFixSizeBitOrOctString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) arrsBytes + | false -> initFixVarSizeBitOrOctString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes + let tdName = lm.lg.getLongTypedefName typeDefinition let constantInitExpression = match o.isFixedSize with - | true -> - match ST.lang with - | ProgrammingLanguage.Scala -> - (lm.lg.getLongTypedefName typeDefinition) + "(" + (lm.init.initFixSizeOctetString o.maxSize.uper (o.maxSize.uper = 0I)) + ")" - | _ -> - lm.init.initFixSizeOctetString o.maxSize.uper (o.maxSize.uper = 0I) - | false -> lm.init.initVarSizeOctetString o.minSize.uper o.maxSize.uper + | true -> lm.init.initFixSizeOctetString tdName o.maxSize.uper (o.maxSize.uper = 0I) + | false -> lm.init.initVarSizeOctetString tdName o.minSize.uper o.maxSize.uper let anonyms = - o.AllCons |> - List.map DastFold.getValueFromSizeableConstraint |> + o.AllCons |> + List.map DastFold.getValueFromSizeableConstraint |> List.collect id |> - List.map(fun (v,_) -> DAstVariables.printOctetStringValueAsCompoundLitteral lm "" o (v|>List.map(fun bl -> bl.Value))) + List.map(fun (v,_) -> DAstVariables.printOctetStringValueAsCompoundLiteral lm "" o (v|>List.map(fun bl -> bl.Value))) let tdName = lm.lg.getLongTypedefName typeDefinition let testCaseFuncs, tasInitFunc = match anonyms with | [] -> - let ii = t.id.SeqeuenceOfLevel + 1 + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii - let seqOfCase (nSize:BigInteger) = - let initTestCaseFunc (p:CallerScope) = - let funcBody = initTestCaseOctetString p.arg.p (lm.lg.getAccess p.arg) tdName nSize i (o.minSize.uper = o.maxSize.uper) false o.minSize.uper (nSize = 0I) + let seqOfCase (nSize:BigInteger) = + let initTestCaseFunc (p:CallerScope) = + let funcBody = initTestCaseOctetString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tdName nSize i (o.minSize.uper = o.maxSize.uper) false o.minSize.uper (nSize = 0I) {InitFunctionResult.funcBody = funcBody; localVariables=[SequenceOfIndex (ii, None)]} {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvSizeableTypeValue nSize)] } - let testCaseFuncs = + let testCaseFuncs = seq { match o.minSize.acn = o.maxSize.acn with | true -> yield seqOfCase o.minSize.acn - | false -> - yield seqOfCase o.minSize.acn - yield seqOfCase o.maxSize.acn + | false -> + yield seqOfCase o.minSize.acn + yield seqOfCase o.maxSize.acn match o.maxSize.acn > 65536I with //fragmentation cases | true -> yield! fragmentationCases seqOfCase o.maxSize.acn | false -> () } |> Seq.toList - let zero (p:CallerScope) = + let zero (p:CallerScope) = let isFixedSize = match t.getBaseType r with | None -> o.isFixedSize - | Some bs -> + | Some bs -> match bs.Kind with | Asn1AcnAst.OctetString bo -> bo.isFixedSize | _ -> raise(BugErrorException "UnexpectedType") - let funcBody = initTestCaseOctetString p.arg.p (lm.lg.getAccess p.arg) tdName o.maxSize.uper i (isFixedSize) true o.minSize.uper (o.maxSize.uper = 0I) + let funcBody = initTestCaseOctetString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tdName o.maxSize.uper i (isFixedSize) true o.minSize.uper (o.maxSize.uper = 0I) let lvars = lm.lg.init.zeroIA5String_localVars ii {InitFunctionResult.funcBody = funcBody; localVariables=lvars} testCaseFuncs, zero | _ -> - let ret = - anonyms |> + let ret = + anonyms |> List.map(fun (compLit) -> let initTestCaseFunc (p:CallerScope) = let ret = sprintf "%s%s%s;" (lm.lg.getValue p.arg) lm.lg.AssignOperator compLit {InitFunctionResult.funcBody = ret; localVariables=[]} {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) ret, ret.Head.initTestCaseFunc - - let maxArrLength = + + let maxArrLength = match t.Kind with | Asn1AcnAst.OctetString oS -> oS.maxSize.ToString() | _ -> "0" - createInitFunctionCommon r lm t typeDefinition "null" funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] -let createNullTypeInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.NullType) (typeDefinition:TypeDefintionOrReference) = +let createNullTypeInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.NullType) (typeDefinition:TypeDefinitionOrReference) = let initNull = lm.init.initNull - let funcBody (p:CallerScope) v = initNull (lm.lg.getValue p.arg) + let funcBody (p:CallerScope) v = initNull (lm.lg.getValue p.arg) let constantInitExpression = "0" - let testCaseFuncs = [{AutomaticTestCase.initTestCaseFunc = (fun p -> {InitFunctionResult.funcBody = initNull (lm.lg.getValue p.arg); localVariables=[]}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)]} ] - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody testCaseFuncs.Head.initTestCaseFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + let testCaseFuncs: AutomaticTestCase list = [{AutomaticTestCase.initTestCaseFunc = (fun p -> {InitFunctionResult.funcBody = initNull (lm.lg.getValue p.arg); localVariables=[]}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)]} ] + createInitFunctionCommon r lm t typeDefinition funcBody testCaseFuncs.Head.initTestCaseFunc testCaseFuncs constantInitExpression constantInitExpression [] [] -let createBitStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.BitString ) (typeDefinition:TypeDefintionOrReference) (isValidFunction:IsValidFunction option)= +let createBitStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.BitString ) (typeDefinition:TypeDefinitionOrReference) (isValidFunction:IsValidFunction option)= let initFixSizeBitOrOctString_bytei = lm.init.initFixSizeBitOrOctString_bytei let initFixSizeBitOrOctString = lm.init.initFixSizeBitOrOctString let initFixVarSizeBitOrOctString = lm.init.initFixVarSizeBitOrOctString let initTestCaseBitString = lm.init.initTestCaseBitString - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let bytes = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let bytes = match v.ActualValue with | BitStringValue iv -> bitStringValueToByteArray (StringLoc.ByValue iv) |> Seq.toList | OctetStringValue iv -> iv | _ -> raise(BugErrorException "UnexpectedValue") - let arrsBytes = bytes |> List.mapi(fun i b -> initFixSizeBitOrOctString_bytei p.arg.p (lm.lg.getAccess p.arg) ((i + lm.lg.ArrayStartIndex).ToString()) (sprintf "%x" b)) + let arrsBytes = bytes |> List.mapi(fun i b -> initFixSizeBitOrOctString_bytei (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) ((i + lm.lg.ArrayStartIndex).ToString()) (sprintf "%x" b)) match o.minSize.uper = o.maxSize.uper with - | true -> initFixSizeBitOrOctString p.arg.p (lm.lg.getAccess p.arg) arrsBytes - | false -> initFixVarSizeBitOrOctString p.arg.p (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes + | true -> initFixSizeBitOrOctString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) arrsBytes + | false -> initFixVarSizeBitOrOctString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes let anonyms = - o.AllCons |> - List.map DastFold.getValueFromSizeableConstraint |> + o.AllCons |> + List.map DastFold.getValueFromSizeableConstraint |> List.collect id |> - List.map(fun (v,_) -> DAstVariables.printBitStringValueAsCompoundLitteral lm "" o v.Value) + List.map(fun (v,_) -> DAstVariables.printBitStringValueAsCompoundLiteral lm "" o v.Value) let tdName = lm.lg.getLongTypedefName typeDefinition let testCaseFuncs, tasInitFunc = match anonyms with | [] -> - let ii = t.id.SeqeuenceOfLevel + 1 + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii - let seqOfCase (nSize:BigInteger) = - let initTestCaseFunc (p:CallerScope) = - let nSizeCeiled = if nSize % 8I = 0I then nSize else (nSize + (8I - nSize % 8I)) - let funcBody = initTestCaseBitString p.arg.p (lm.lg.getAccess p.arg) tdName nSize (nSizeCeiled) i (o.minSize.uper = o.maxSize.uper) false o.minSize.uper + let seqOfCase (nSize:BigInteger) = + let initTestCaseFunc (p:CallerScope) = + let nSizeCeiled = if nSize % 8I = 0I then nSize else (nSize + (8I - nSize % 8I)) + let funcBody = initTestCaseBitString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tdName nSize (nSizeCeiled) i (o.minSize.uper = o.maxSize.uper) false o.minSize.uper {InitFunctionResult.funcBody = funcBody; localVariables=[SequenceOfIndex (ii, None)]} {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvSizeableTypeValue nSize)] } - let testCaseFuncs = + let testCaseFuncs = seq { match o.minSize.acn = o.maxSize.acn with - | true -> yield seqOfCase o.minSize.acn - | false -> - yield seqOfCase o.minSize.acn - yield seqOfCase o.maxSize.acn + | true -> yield seqOfCase o.minSize.acn + | false -> + yield seqOfCase o.minSize.acn + yield seqOfCase o.maxSize.acn match o.maxSize.acn > 65536I with //fragmentation cases | true -> yield! fragmentationCases seqOfCase o.maxSize.acn | false -> () } |> Seq.toList - let zero (p:CallerScope) = + let zero (p:CallerScope) = let nSize = o.maxSize.uper - let nSizeCeiled = if nSize % 8I = 0I then nSize else (nSize + (8I - nSize % 8I)) + let nSizeCeiled = if nSize % 8I = 0I then nSize else (nSize + (8I - nSize % 8I)) let isFixedSize = match t.getBaseType r with | None -> o.isFixedSize - | Some bs -> + | Some bs -> match bs.Kind with | Asn1AcnAst.BitString bo -> bo.isFixedSize | _ -> raise(BugErrorException "UnexpectedType") - let funcBody = initTestCaseBitString p.arg.p (lm.lg.getAccess p.arg) tdName nSize (nSizeCeiled) i (isFixedSize) true o.minSize.uper - let lvars = lm.lg.init.zeroIA5String_localVars ii + let funcBody = initTestCaseBitString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tdName nSize (nSizeCeiled) i (isFixedSize) true o.minSize.uper + let lvars = lm.lg.init.zeroIA5String_localVars ii {InitFunctionResult.funcBody = funcBody; localVariables=lvars} testCaseFuncs, zero | _ -> - let ret = - anonyms |> + let ret = + anonyms |> List.map(fun compLit -> let retFunc (p:CallerScope) = let ret = sprintf "%s%s%s;" (lm.lg.getValue p.arg) lm.lg.AssignOperator compLit @@ -561,14 +506,14 @@ let createBitStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac {AutomaticTestCase.initTestCaseFunc = retFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) ret, ret.Head.initTestCaseFunc - let user_aux_functions = + let user_aux_functions = let funcName = getFuncNameGeneric typeDefinition "" - let p = lm.lg.getParamType t CommonTypes.Codec.Decode - let varName = p.arg.p + let p = lm.lg.getParamType t CommonTypes.Codec.Decode + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let typeDefName = (lm.lg.getLongTypedefName typeDefinition) - o.namedBitList |> - List.choose(fun z -> + o.namedBitList |> + List.choose(fun z -> match funcName with | Some funcName -> let nZeroBasedByteIndex = z.resolvedValue / 8I; @@ -578,21 +523,17 @@ let createBitStringInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac Some (sf_if, sf_body) | None -> None ) - + let constantInitExpression = match o.isFixedSize with - | true -> lm.init.initFixSizeBitString o.maxSize.uper (BigInteger o.MaxOctets) - | false -> lm.init.initVarSizeBitString o.minSize.uper o.maxSize.uper (BigInteger o.MaxOctets) - let constantInitExpression = - match ST.lang with - | ProgrammingLanguage.Scala -> tdName + "(" + constantInitExpression + ")" - | _ -> constantInitExpression - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] user_aux_functions + | true -> lm.init.initFixSizeBitString tdName o.maxSize.uper (BigInteger o.MaxOctets) + | false -> lm.init.initVarSizeBitString tdName o.minSize.uper o.maxSize.uper (BigInteger o.MaxOctets) + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] user_aux_functions -let createBooleanInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Boolean ) (typeDefinition:TypeDefintionOrReference) = +let createBooleanInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Boolean ) (typeDefinition:TypeDefinitionOrReference) = let initBoolean = lm.init.initBoolean - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with | BooleanValue iv -> iv | _ -> raise(BugErrorException "UnexpectedValue") @@ -600,48 +541,43 @@ let createBooleanInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnA - let testCaseFuncs = - EncodeDecodeTestCase.BooleanAutomaticTestCaseValues r t o |> + let testCaseFuncs = + EncodeDecodeTestCase.BooleanAutomaticTestCaseValues r t o |> List.map (fun vl -> {AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initBoolean (lm.lg.getValue p.arg) vl; localVariables = []}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) - let tasInitFunc (p:CallerScope) = + let tasInitFunc (p:CallerScope) = match isValidValueGeneric o.AllCons (=) false with | true -> {InitFunctionResult.funcBody = initBoolean (lm.lg.getValue p.arg) false; localVariables = []} | false -> {InitFunctionResult.funcBody = initBoolean (lm.lg.getValue p.arg) true; localVariables = []} let constantInitExpression = lm.lg.FalseLiteral - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] - - + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] - - - -let createObjectIdentifierInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.ObjectIdentifier ) (typeDefinition:TypeDefintionOrReference) iv = - let initObjectIdentifier_vali = lm.init.initObjectIdentifier_vali +let createObjectIdentifierInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.ObjectIdentifier ) (typeDefinition:TypeDefinitionOrReference) iv = + let initObjectIdentifier_valid = lm.init.initObjectIdentifier_valid let initObjectIdentifier = lm.init.initObjectIdentifier - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let bytes = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let bytes = match v.ActualValue with | ObjOrRelObjIdValue iv -> iv.Values |> List.map fst | _ -> raise(BugErrorException "UnexpectedValue") - let arrsBytes = bytes |> List.mapi(fun i b -> initObjectIdentifier_vali p.arg.p (lm.lg.getAccess p.arg) ((i+lm.lg.ArrayStartIndex).ToString()) b) - initObjectIdentifier p.arg.p (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes - let testCaseFuncs = - EncodeDecodeTestCase.ObjectIdentifierAutomaticTestCaseValues r t o |> - List.map (fun vl -> - {AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> - let arrsBytes = vl |> List.mapi(fun i b -> initObjectIdentifier_vali p.arg.p (lm.lg.getAccess p.arg) ((i+lm.lg.ArrayStartIndex).ToString()) b) - {InitFunctionResult.funcBody = initObjectIdentifier (p.arg.p) (lm.lg.getAccess p.arg) (BigInteger vl.Length) arrsBytes; localVariables = []}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) - - let tasInitFunc (p:CallerScope) = - {InitFunctionResult.funcBody = initObjectIdentifier (p.arg.p) (lm.lg.getAccess p.arg) 0I []; localVariables = []} + let arrsBytes = bytes |> List.mapi(fun i b -> initObjectIdentifier_valid (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) ((i+lm.lg.ArrayStartIndex).ToString()) b) + initObjectIdentifier (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (BigInteger arrsBytes.Length) arrsBytes + let testCaseFuncs = + EncodeDecodeTestCase.ObjectIdentifierAutomaticTestCaseValues r t o |> + List.map (fun vl -> + {AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> + let arrsBytes = vl |> List.mapi(fun i b -> initObjectIdentifier_valid (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) ((i+lm.lg.ArrayStartIndex).ToString()) b) + {InitFunctionResult.funcBody = initObjectIdentifier (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (BigInteger vl.Length) arrsBytes; localVariables = []}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) + + let tasInitFunc (p:CallerScope) = + {InitFunctionResult.funcBody = initObjectIdentifier (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) 0I []; localVariables = []} let constantInitExpression = lm.init.initObjectIdentifierAsExpr () - createInitFunctionCommon r lm t typeDefinition "createObjectIdentifierInitFunc" funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] -let createTimeTypeInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.TimeType ) (typeDefinition:TypeDefintionOrReference) iv = +let createTimeTypeInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.TimeType ) (typeDefinition:TypeDefinitionOrReference) iv = let init_Asn1LocalTime = lm.init.init_Asn1LocalTime let init_Asn1UtcTime = lm.init.init_Asn1UtcTime let init_Asn1LocalTimeWithTimeZone = lm.init.init_Asn1LocalTimeWithTimeZone @@ -650,50 +586,50 @@ let createTimeTypeInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac let init_Asn1Date_UtcTime = lm.init.init_Asn1Date_UtcTime let init_Asn1Date_LocalTimeWithTimeZone = lm.init.init_Asn1Date_LocalTimeWithTimeZone - let initByBalue (p:CallerScope) (iv:Asn1DateTimeValue) = + let initByValue (p:CallerScope) (iv:Asn1DateTimeValue) = match iv with - |Asn1LocalTimeValue tv -> init_Asn1LocalTime p.arg.p (lm.lg.getAccess p.arg) tv - |Asn1UtcTimeValue tv -> init_Asn1UtcTime p.arg.p (lm.lg.getAccess p.arg) tv - |Asn1LocalTimeWithTimeZoneValue (tv,tz) -> init_Asn1LocalTimeWithTimeZone p.arg.p (lm.lg.getAccess p.arg) tv tz - |Asn1DateValue dt -> init_Asn1Date p.arg.p (lm.lg.getAccess p.arg) dt - |Asn1Date_LocalTimeValue (dt,tv) -> init_Asn1Date_LocalTime p.arg.p (lm.lg.getAccess p.arg) dt tv - |Asn1Date_UtcTimeValue (dt,tv) -> init_Asn1Date_UtcTime p.arg.p (lm.lg.getAccess p.arg) dt tv - |Asn1Date_LocalTimeWithTimeZoneValue (dt,tv,tz)-> init_Asn1Date_LocalTimeWithTimeZone p.arg.p (lm.lg.getAccess p.arg) dt tv tz - - let funcBody (p:CallerScope) (v:Asn1ValueKind) = + |Asn1LocalTimeValue tv -> init_Asn1LocalTime (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tv + |Asn1UtcTimeValue tv -> init_Asn1UtcTime (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tv + |Asn1LocalTimeWithTimeZoneValue (tv,tz) -> init_Asn1LocalTimeWithTimeZone (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) tv tz + |Asn1DateValue dt -> init_Asn1Date (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) dt + |Asn1Date_LocalTimeValue (dt,tv) -> init_Asn1Date_LocalTime (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) dt tv + |Asn1Date_UtcTimeValue (dt,tv) -> init_Asn1Date_UtcTime (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) dt tv + |Asn1Date_LocalTimeWithTimeZoneValue (dt,tv,tz)-> init_Asn1Date_LocalTimeWithTimeZone (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) dt tv tz + + let funcBody (p:CallerScope) (v:Asn1ValueKind) = match v.ActualValue with - | TimeValue iv -> initByBalue p iv + | TimeValue iv -> initByValue p iv | _ -> raise(BugErrorException "UnexpectedValue") let atvs = EncodeDecodeTestCase.TimeTypeAutomaticTestCaseValues r t o - let testCaseFuncs = - atvs |> - List.map (fun vl -> - {AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> - {InitFunctionResult.funcBody = initByBalue p vl; localVariables = []}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) - - let tasInitFunc (p:CallerScope) = - {InitFunctionResult.funcBody = initByBalue p atvs.Head; localVariables = []} - let constantInitExpression = - match o.timeClass with + let testCaseFuncs = + atvs |> + List.map (fun vl -> + {AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> + {InitFunctionResult.funcBody = initByValue p vl; localVariables = []}); testCaseTypeIDsMap = Map.ofList [(t.id, TcvAnyValue)] }) + + let tasInitFunc (p:CallerScope) = + {InitFunctionResult.funcBody = initByValue p atvs.Head; localVariables = []} + let constantInitExpression = + match o.timeClass with |Asn1LocalTime _-> lm.init.init_Asn1LocalTimeExpr () |Asn1UtcTime _-> lm.init.init_Asn1UtcTimeExpr () |Asn1LocalTimeWithTimeZone _-> lm.init.init_Asn1LocalTimeWithTimeZoneExpr () - |Asn1Date _-> lm.init.init_Asn1DateExpr () + |Asn1Date -> lm.init.init_Asn1DateExpr () |Asn1Date_LocalTime _-> lm.init.init_Asn1Date_LocalTimeExpr () |Asn1Date_UtcTime _-> lm.init.init_Asn1Date_UtcTimeExpr () |Asn1Date_LocalTimeWithTimeZone _-> lm.init.init_Asn1Date_LocalTimeWithTimeZoneExpr () - createInitFunctionCommon r lm t typeDefinition "createTimeTypeInitFunc" funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody tasInitFunc testCaseFuncs constantInitExpression constantInitExpression [] [] let mergeMaps (m1:Map<'key,'value>) (m2:Map<'key,'value>) = Map.fold (fun (nm:Map<'key,'value>) key value -> match nm.ContainsKey key with false -> nm.Add(key,value) | true -> nm) m1 m2 - -let createEnumeratedInitFunc (r: Asn1AcnAst.AstRoot) (lm: LanguageMacros) (t: Asn1AcnAst.Asn1Type) (o: Asn1AcnAst.Enumerated) (typeDefinition: TypeDefintionOrReference) iv = + +let createEnumeratedInitFunc (r: Asn1AcnAst.AstRoot) (lm: LanguageMacros) (t: Asn1AcnAst.Asn1Type) (o: Asn1AcnAst.Enumerated) (typeDefinition: TypeDefinitionOrReference) iv = let initEnumerated = lm.init.initEnumerated - let enumClassName = + let enumClassName = match ST.lang with | ProgrammingLanguage.Scala -> match typeDefinition with @@ -701,148 +637,140 @@ let createEnumeratedInitFunc (r: Asn1AcnAst.AstRoot) (lm: LanguageMacros) (t: As | TypeDefinition t -> t.typedefName | _ -> "" - let getEnumBackendName (defOrRef: TypeDefintionOrReference option) (nm: Asn1AcnAst.NamedItem) = - let itemname = + let getEnumBackendName (defOrRef: TypeDefinitionOrReference option) (nm: Asn1AcnAst.NamedItem) = + let itemname = match ST.lang with | ProgrammingLanguage.Scala -> ToC nm.scala_name | _ -> (lm.lg.getNamedItemBackendName defOrRef nm) itemname - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with | EnumValue iv -> o.items |> Seq.find(fun x -> x.Name.Value = iv) | _ -> raise(BugErrorException "UnexpectedValue") initEnumerated (lm.lg.getValue p.arg) (getEnumBackendName (Some typeDefinition) vl) enumClassName - let testCaseFuncs = - EncodeDecodeTestCase.EnumeratedAutomaticTestCaseValues2 r t o |> - List.map (fun vl -> + let testCaseFuncs = + EncodeDecodeTestCase.EnumeratedAutomaticTestCaseValues2 r t o |> + List.map (fun vl -> { - AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initEnumerated (lm.lg.getValue p.arg) (getEnumBackendName (Some typeDefinition) vl) enumClassName; localVariables=[]}); - testCaseTypeIDsMap = Map.ofList [(t.id, (TcvEnumeratedValue vl.Name.Value))] + AutomaticTestCase.initTestCaseFunc = (fun (p:CallerScope) -> {InitFunctionResult.funcBody = initEnumerated (lm.lg.getValue p.arg) (getEnumBackendName (Some typeDefinition) vl) enumClassName; localVariables=[]}); + testCaseTypeIDsMap = Map.ofList [(t.id, (TcvEnumeratedValue vl.Name.Value))] }) let constantInitExpression = lm.lg.getNamedItemBackendName (Some typeDefinition) o.items.Head - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody testCaseFuncs.Head.initTestCaseFunc testCaseFuncs constantInitExpression constantInitExpression [] [] + createInitFunctionCommon r lm t typeDefinition funcBody testCaseFuncs.Head.initTestCaseFunc testCaseFuncs constantInitExpression constantInitExpression [] [] let getChildExpression (lm:LanguageMacros) (childType:Asn1Type) = match childType.initFunction.initFunction with - | None -> childType.initFunction.initExpression - | Some cn -> - match childType.isComplexType with - | false -> childType.initFunction.initExpression - | true -> sprintf "%s" cn.funcName + | Some cn when childType.isComplexType -> + match ST.lang with + | ProgrammingLanguage.Scala -> cn.funcName + (scalaInitMethSuffix childType.Kind) + | _ -> cn.funcName // TODO: Quid C ???? + | _ -> childType.initFunction.initExpression let getChildExpressionGlobal (lm:LanguageMacros) (childType:Asn1Type) = match childType.initFunction.initGlobal with - | None -> childType.initFunction.initExpressionGlobal - | Some cn -> - match childType.isComplexType with - | false -> childType.initFunction.initExpressionGlobal - | true -> sprintf "%s" cn.globalName - + | Some cn when childType.isComplexType -> cn.globalName + | _ -> childType.initFunction.initExpressionGlobal - -let createSequenceOfInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.SequenceOf ) (typeDefinition:TypeDefintionOrReference) (childType:Asn1Type) = +let createSequenceOfInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.SequenceOf ) (typeDefinition:TypeDefinitionOrReference) (childType:Asn1Type) = let initFixedSequenceOf = lm.init.initFixedSequenceOf let initVarSizeSequenceOf = lm.init.initVarSizeSequenceOf let initTestCaseSizeSequenceOf_innerItem = lm.init.initTestCaseSizeSequenceOf_innerItem let initTestCaseSizeSequenceOf = lm.init.initTestCaseSizeSequenceOf let initChildWithInitFunc = lm.init.initChildWithInitFunc - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let vl = + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let vl = match v.ActualValue with | SeqOfValue childVals -> - childVals |> - List.mapi(fun i chv -> + childVals |> + List.mapi(fun i chv -> let new_arg = lm.lg.getArrayItem p.arg ((i+lm.lg.ArrayStartIndex).ToString()) childType.isIA5String let ret = childType.initFunction.initByAsn1Value ({p with arg = new_arg}) chv.kind match lm.lg.supportsStaticVerification with | false -> ret | true when i>0 -> ret - | true -> + | true -> // in the first array we have to emit a pragma Annotate false_positive, otherwise gnatprove emit an error - let pragma = lm.init.initSequence_pragma p.arg.p + let pragma = lm.init.initSequence_pragma (p.arg.joined lm.lg) ret + pragma ) | _ -> raise(BugErrorException "UnexpectedValue") match o.isFixedSize with | true -> initFixedSequenceOf vl - | false -> initVarSizeSequenceOf p.arg.p (lm.lg.getAccess p.arg) (BigInteger vl.Length) vl + | false -> initVarSizeSequenceOf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (BigInteger vl.Length) vl - let ii = t.id.SeqeuenceOfLevel + 1 - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) + let ii = t.id.SequenceOfLevel + 1 + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) let testCaseFuncs = - let seqOfCase (childTestCases : AutomaticTestCase list) (nSize:BigInteger) = - //let len = childType.initFunction.automaticTestCases.Length - //let childTestCases = childType.initFunction.automaticTestCases |> Seq.take (min (int nSize) len) |> Seq.toList //|> - //List.map(fun fnc -> fnc.initTestCaseFunc ({p with arg = p.arg.getArrayItem l i childType.isIA5String})) + let seqOfCase (childTestCases : AutomaticTestCase list) (nSize:BigInteger) = match childTestCases with - | [] -> - let initTestCaseFunc (p:CallerScope) = + | [] -> + let initTestCaseFunc (p:CallerScope) = {InitFunctionResult.funcBody = ""; localVariables = []} {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.ofList [(t.id, TcvSizeableTypeValue nSize)] } - | atc::[] -> - let initTestCaseFunc (p:CallerScope) = + | atc::[] -> + let initTestCaseFunc (p:CallerScope) = let childCase = atc.initTestCaseFunc ({p with arg = lm.lg.getArrayItem p.arg i childType.isIA5String}) - let funcBody = initTestCaseSizeSequenceOf p.arg.p (lm.lg.getAccess p.arg) None nSize (o.minSize.uper = o.maxSize.uper) [childCase.funcBody] false i + let funcBody = initTestCaseSizeSequenceOf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) None nSize (o.minSize.uper = o.maxSize.uper) [childCase.funcBody] false i {InitFunctionResult.funcBody = funcBody; localVariables= (SequenceOfIndex (ii, None))::childCase.localVariables } let combinedTestCase = atc.testCaseTypeIDsMap.Add(t.id, TcvSizeableTypeValue nSize) {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = combinedTestCase } | _ -> - let initTestCaseFunc (p:CallerScope) = - let arrsInnerItems, childLocalVars = - childTestCases |> - List.mapi(fun idx atc -> + let initTestCaseFunc (p:CallerScope) = + let arrsInnerItems, childLocalVars = + childTestCases |> + List.mapi(fun idx atc -> let sChildItem = atc.initTestCaseFunc ({p with arg = lm.lg.getArrayItem p.arg i childType.isIA5String}) let funcBody = initTestCaseSizeSequenceOf_innerItem (idx=0) (idx = childTestCases.Length-1) idx.AsBigInt sChildItem.funcBody i (BigInteger childTestCases.Length) (funcBody, (SequenceOfIndex (ii, None))::sChildItem.localVariables)) |> List.unzip - let funcBody = initTestCaseSizeSequenceOf p.arg.p (lm.lg.getAccess p.arg) None nSize (o.minSize.uper = o.maxSize.uper) arrsInnerItems true i + let funcBody = initTestCaseSizeSequenceOf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) None nSize (o.minSize.uper = o.maxSize.uper) arrsInnerItems true i {InitFunctionResult.funcBody = funcBody; localVariables= (SequenceOfIndex (ii, None))::(childLocalVars |> List.collect id)} let combinedTestCase = let thisCase = Map.ofList [(t.id, TcvSizeableTypeValue nSize)] childTestCases |> List.fold(fun (newMap:Map) atc -> mergeMaps newMap atc.testCaseTypeIDsMap) thisCase {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = combinedTestCase } match r.args.generateAutomaticTestCases with - | true -> + | true -> let seqOfCase_aux (nSize:BigInteger) = match nSize > 0I with | true -> let totalChildAtcs = childType.initFunction.automaticTestCases.Length - let childTestCases = childType.initFunction.automaticTestCases + let childTestCases = childType.initFunction.automaticTestCases let test_case_bundles = int (totalChildAtcs.AsBigInt / nSize) let last_test_case_bundle_size = int (totalChildAtcs.AsBigInt % nSize) seq { for i in [1..test_case_bundles] do let bund_cases = childTestCases |> Seq.skip ((i-1) * (int nSize)) |> Seq.take (int nSize) |> Seq.toList yield seqOfCase bund_cases nSize - + if (last_test_case_bundle_size > 0) then let last_bund_cases = childTestCases |> Seq.skip (test_case_bundles * (int nSize)) |> Seq.take (last_test_case_bundle_size) |> Seq.toList yield seqOfCase last_bund_cases nSize } |> Seq.toList | false -> [] - + seq { match o.minSize.acn = o.maxSize.acn with | true -> yield! seqOfCase_aux o.minSize.acn - | false -> - yield! seqOfCase_aux o.maxSize.acn - yield! seqOfCase_aux o.minSize.acn + | false -> + yield! seqOfCase_aux o.maxSize.acn + yield! seqOfCase_aux o.minSize.acn match o.maxSize.acn > 65536I with //fragmentation cases | true -> yield! (fragmentationCases seqOfCase_aux o.maxSize.acn |> List.collect id) | false -> () } |> Seq.toList - | fase -> [] + | false -> [] let initTasFunction, nonEmbeddedChildrenFuncs = let initTasFunction (p:CallerScope) = let initCountValue = Some o.minSize.uper let chp = {p with arg = lm.lg.getArrayItem p.arg i childType.isIA5String} - let childInitRes_funcBody, childInitRes_localVariables = + let childInitRes_funcBody, childInitRes_localVariables = match childType.initFunction.initProcedure with | None -> let childInitRes = childType.initFunction.initTas chp @@ -852,52 +780,43 @@ let createSequenceOfInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let isFixedSize = match t.getBaseType r with | None -> o.isFixedSize - | Some bs -> + | Some bs -> match bs.Kind with | Asn1AcnAst.SequenceOf bo -> bo.isFixedSize | _ -> raise(BugErrorException "UnexpectedType") - let funcBody = initTestCaseSizeSequenceOf p.arg.p (lm.lg.getAccess p.arg) initCountValue o.maxSize.uper (isFixedSize) [childInitRes_funcBody] false i + let funcBody = initTestCaseSizeSequenceOf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) initCountValue o.maxSize.uper (isFixedSize) [childInitRes_funcBody] false i {InitFunctionResult.funcBody = funcBody; localVariables= (SequenceOfIndex (ii, None))::childInitRes_localVariables } let nonEmbeddedChildrenFuncs = match childType.initFunction.initProcedure with | None -> [] | Some _ when r.args.generateConstInitGlobals -> [] | Some _ -> [childType.initFunction] - + initTasFunction, nonEmbeddedChildrenFuncs - let initParams = - match o.isFixedSize with - | true -> $"(Array.fill({o.maxSize}){{{extractDefaultInitValue childType.Kind}}})" - | false -> $"({o.minSize}, Array.fill({o.maxSize}){{{extractDefaultInitValue childType.Kind}}})" - - let initVal = - match typeDefinition with - | TypeDefinition t -> t.typedefName - | ReferenceToExistingDefinition r -> r.typedefName - + initParams - let childInitExpr = getChildExpression lm childType let childInitGlobal = getChildExpressionGlobal lm childType - let constantInitExpression childExpr = + let constantInitExpression childExpr = match o.isFixedSize with - | true -> lm.init.initFixSizeSequenceOfExpr o.maxSize.uper childExpr - | false -> lm.init.initVarSizeSequenceOfExpr o.minSize.uper o.maxSize.uper childExpr - createInitFunctionCommon r lm t typeDefinition initVal funcBody initTasFunction testCaseFuncs (constantInitExpression childInitExpr) (constantInitExpression childInitGlobal) nonEmbeddedChildrenFuncs [] + | true -> lm.init.initFixSizeSequenceOfExpr (typeDefinition.longTypedefName2 lm.lg.hasModules) o.maxSize.uper childExpr + | false -> lm.init.initVarSizeSequenceOfExpr (typeDefinition.longTypedefName2 lm.lg.hasModules) o.minSize.uper o.maxSize.uper childExpr + let initExpr = constantInitExpression childInitExpr + let initExprGlob = constantInitExpression childInitGlobal + createInitFunctionCommon r lm t typeDefinition funcBody initTasFunction testCaseFuncs initExpr initExprGlob nonEmbeddedChildrenFuncs [] -let createSequenceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (children:SeqChildInfo list) = +let createSequenceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (children:SeqChildInfo list) = let initSequence = lm.init.initSequence let initSequence_optionalChild = lm.init.initSequence_optionalChild let initTestCase_sequence_child = lm.init.initTestCase_sequence_child let initTestCase_sequence_child_opt = lm.init.initTestCase_sequence_child_opt let initChildWithInitFunc = lm.init.initChildWithInitFunc let initSequence_emptySeq = lm.init.initSequence_emptySeq - let initByAsn1ValueFnc (p:CallerScope) (v:Asn1ValueKind) = + let initByAsn1ValueFnc (p:CallerScope) (v:Asn1ValueKind) = - let childrenRet = + let childrenRet = match v.ActualValue with - | SeqValue iv -> + | SeqValue iv -> children |> List.choose(fun seqChild -> match seqChild with @@ -906,84 +825,75 @@ let createSequenceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn | None -> match seqChild.Optionality with | None -> None - | Some _ -> Some (initSequence_optionalChild p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName seqChild) "0" "") + | Some _ -> Some (initSequence_optionalChild (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName seqChild) "0" "") | Some chv -> - let chContent = seqChild.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName seqChild) seqChild.Type.isIA5String false}) chv.Value.kind + let chContent = seqChild.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName seqChild) seqChild.Type.isIA5String seqChild.Optionality.IsSome}) chv.Value.kind match seqChild.Optionality with | None -> Some chContent - | Some _ -> Some (initSequence_optionalChild p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName seqChild) "1" chContent) + | Some _ -> Some (initSequence_optionalChild (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName seqChild) "1" chContent) | AcnChild _ -> None) | _ -> raise(BugErrorException "UnexpectedValue") initSequence childrenRet - let testCaseFuncs = - let asn1Children = - children |> - List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) |> - List.filter(fun z -> - match z.Type.Kind with + let testCaseFuncs = + let asn1Children = + children |> + List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) |> + List.filter(fun z -> + match z.Type.Kind with | NullType _ -> match z.Optionality with Some Asn1AcnAst.AlwaysPresent -> true | _ -> false | _ -> true) |> List.filter(fun z -> match z.Optionality with Some Asn1AcnAst.AlwaysAbsent -> false | _ -> true) - - - let optChildCount = - children |> - List.filter(fun c -> - match c.Optionality with - | Some (Asn1AcnAst.Optional opt) when opt.acnPresentWhen.IsSome -> true - | _ -> false - ) |> Seq.length - let handleChild (ch:Asn1Child) = + let handleChild (ch:Asn1Child) = let len = ch.Type.initFunction.automaticTestCases.Length - ch.Type.initFunction.automaticTestCases |> - List.collect(fun atc -> - let presentFunc = - let initTestCaseFunc (p:CallerScope) = - let chContent = atc.initTestCaseFunc {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false} - let funcBody = initTestCase_sequence_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent.funcBody ch.Optionality.IsSome + ch.Type.initFunction.automaticTestCases |> + List.collect(fun atc -> + let presentFunc = + let initTestCaseFunc (p:CallerScope) = + let chContent = atc.initTestCaseFunc {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String ch.Optionality.IsSome} + let funcBody = initTestCase_sequence_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent.funcBody ch.Optionality.IsSome {InitFunctionResult.funcBody = funcBody; localVariables = chContent.localVariables } let combinedTestCase = match atc.testCaseTypeIDsMap.ContainsKey ch.Type.id with | true -> atc.testCaseTypeIDsMap | false -> atc.testCaseTypeIDsMap.Add(ch.Type.id, TcvAnyValue) {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = combinedTestCase } - let nonPresenceFunc = - let initTestCaseFunc (p:CallerScope) = - let funcBody = initTestCase_sequence_child_opt p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) + let nonPresenceFunc = + let initTestCaseFunc (p:CallerScope) = + let funcBody = initTestCase_sequence_child_opt (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) {InitFunctionResult.funcBody = funcBody; localVariables = [] } {AutomaticTestCase.initTestCaseFunc = initTestCaseFunc; testCaseTypeIDsMap = Map.empty } match ch.Optionality with | None -> [presentFunc] - | Some (Asn1AcnAst.Optional opt) -> [presentFunc; nonPresenceFunc] - | Some (Asn1AcnAst.AlwaysAbsent) -> [nonPresenceFunc] + | Some (Asn1AcnAst.Optional opt) -> [presentFunc; nonPresenceFunc] + | Some (Asn1AcnAst.AlwaysAbsent) -> [nonPresenceFunc] | Some (Asn1AcnAst.AlwaysPresent) -> [presentFunc] ) let generateCases (children : Asn1Child list) : AutomaticTestCase list= let childrenATCs = - children |> - List.map(fun c -> + children |> + List.map(fun c -> let childAtcs = handleChild c |> Seq.toArray (c, childAtcs, childAtcs.Length)) |> List.filter(fun (_,_,ln) -> ln > 0) match childrenATCs with | [] -> [] | _ -> - let (_,_,mxAtcs) = childrenATCs |> List.maxBy(fun (_,_,len) -> len) + let (_,_,mxAtcs) = childrenATCs |> List.maxBy(fun (_,_,len) -> len) let tesCases = [0 .. mxAtcs - 1] |> List.map(fun seqTestCaseIndex -> - let children_ith_testCase = - childrenATCs |> - List.map(fun (c,childCases,ln) -> childCases.[seqTestCaseIndex % ln]) + let children_ith_testCase = + childrenATCs |> + List.map(fun (c,childCases,ln) -> childCases.[seqTestCaseIndex % ln]) match children_ith_testCase with | [] -> raise(BugErrorException "") | c1::[] -> c1 | c1::cs -> cs |> List.fold(fun (st:AutomaticTestCase) (cur:AutomaticTestCase) -> - let combineFnc (p:CallerScope) = + let combineFnc (p:CallerScope) = let partA = st.initTestCaseFunc p let partB = cur.initTestCaseFunc p let funcBody = [partA.funcBody; partB.funcBody] |> Seq.StrJoin "\n" @@ -994,46 +904,45 @@ let createSequenceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn tesCases match r.args.generateAutomaticTestCases with - | true -> generateCases asn1Children - | false -> [] - let initTasFunction, nonEmbeddedChildrenFuncs = - let handleChild (p:CallerScope) (ch:Asn1Child) : (InitFunctionResult*InitFunction option) = - let nonEmbeddedChildrenFunc = - match lm.lg.initMetod with + | true -> generateCases asn1Children + | false -> [] + let initTasFunction, nonEmbeddedChildrenFuncs = + let handleChild (p:CallerScope) (ch:Asn1Child) : (InitFunctionResult*InitFunction option) = + let nonEmbeddedChildrenFunc = + match lm.lg.initMethod with | Procedure when r.args.generateConstInitGlobals -> None | _ -> Some ch.Type.initFunction - let presentFunc (defaultValue : Asn1AcnAst.Asn1Value option) = + let presentFunc (defaultValue : Asn1AcnAst.Asn1Value option) = + let chP = {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String ch.Optionality.IsSome} match defaultValue with | None -> match ch.Type.initFunction.initProcedure with | None -> - match ch.Type.typeDefintionOrReference with + match ch.Type.typeDefinitionOrReference with | ReferenceToExistingDefinition rf when (not rf.definedInRtl) -> - let fncName = (ch.Type.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules) + (lm.init.methodNameSuffix()) - let chP = {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false} + let fncName = (ch.Type.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules) + (lm.init.methodNameSuffix()) let chContent = initChildWithInitFunc (lm.lg.getPointer chP.arg) (fncName) - let funcBody = initTestCase_sequence_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome + let funcBody = initTestCase_sequence_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome {InitFunctionResult.funcBody = funcBody; localVariables = [] }, nonEmbeddedChildrenFunc | _ -> let fnc = ch.Type.initFunction.initTas - let chContent = fnc {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false} - let funcBody = initTestCase_sequence_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent.funcBody ch.Optionality.IsSome + let chContent = fnc chP + let funcBody = initTestCase_sequence_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent.funcBody ch.Optionality.IsSome {InitFunctionResult.funcBody = funcBody; localVariables = chContent.localVariables }, None - + | Some initProc -> - let chP = {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false} let chContent = initChildWithInitFunc (lm.lg.getPointer chP.arg) (initProc.funcName) - let funcBody = initTestCase_sequence_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome + let funcBody = initTestCase_sequence_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome {InitFunctionResult.funcBody = funcBody; localVariables = [] }, nonEmbeddedChildrenFunc | Some dv -> let fnc = ch.Type.initFunction.initByAsn1Value - let chContent = fnc {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false} (mapValue dv).kind - let funcBody = initTestCase_sequence_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome + let chContent = fnc chP (mapValue dv).kind + let funcBody = initTestCase_sequence_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) chContent ch.Optionality.IsSome {InitFunctionResult.funcBody = funcBody; localVariables = [] }, nonEmbeddedChildrenFunc - - - let nonPresenceFunc () = - let funcBody = initTestCase_sequence_child_opt p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) + + + let nonPresenceFunc () = + let funcBody = initTestCase_sequence_child_opt (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName ch) {InitFunctionResult.funcBody = funcBody; localVariables = [] }, None match ch.Optionality with | None -> presentFunc None @@ -1043,119 +952,83 @@ let createSequenceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn let asn1Children = children |> List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) let initTasFunction (p:CallerScope) = match asn1Children with - | [] -> - let initEmpytSeq = initSequence_emptySeq p.arg.p - {InitFunctionResult.funcBody = initEmpytSeq; localVariables = []} + | [] -> + let initEmptySeq = initSequence_emptySeq (p.arg.joined lm.lg) + {InitFunctionResult.funcBody = initEmptySeq; localVariables = []} | _ -> - asn1Children |> + asn1Children |> List.fold(fun (cr) ch -> let chResult, _ = handleChild p ch let newFuncBody = cr.funcBody + "\n" + chResult.funcBody {InitFunctionResult.funcBody = newFuncBody; localVariables = cr.localVariables@chResult.localVariables} ) {InitFunctionResult.funcBody = ""; localVariables = []} - let dummyScope = {CallerScope.modName = ""; arg = VALUE "dummy"} + let dummyScope = {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} let nonEmbeddedChildrenFuncs = asn1Children |> List.choose(fun ch -> handleChild dummyScope ch |> snd) initTasFunction, nonEmbeddedChildrenFuncs - let constantInitExpression getChildExpr = - let nonEmptyChildren = - children |> + let constantInitExpression getChildExpr = + let nonEmptyChildren = + children |> List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) |> - List.map (fun c -> + List.map (fun c -> let childName = lm.lg.getAsn1ChildBackendName c - let childExp = getChildExpr lm c.Type - let exprMethodCall = - match ST.lang with - | ProgrammingLanguage.Scala -> - scalaInitMethSuffix c.Type.Kind - | _ -> "" - lm.init.initSequenceChildExpr childName (childExp + exprMethodCall)) + let childExp = getChildExpr lm c.Type + lm.init.initSequenceChildExpr childName childExp c.Optionality.IsSome) let arrsOptionalChildren = - children |> + children |> List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) |> - List.choose (fun c -> - match c.Optionality with + List.choose (fun c -> + match c.Optionality with | None -> None | Some (Asn1AcnAst.Optional opt) -> Some (lm.init.initSequenceOptionalChildExpr (lm.lg.getAsn1ChildBackendName c) 1I) | Some (Asn1AcnAst.AlwaysAbsent) -> Some (lm.init.initSequenceOptionalChildExpr (lm.lg.getAsn1ChildBackendName c) 0I) | Some (Asn1AcnAst.AlwaysPresent) -> Some (lm.init.initSequenceOptionalChildExpr (lm.lg.getAsn1ChildBackendName c) 1I) ) + let tdName = (typeDefinition.longTypedefName2 lm.lg.hasModules) match nonEmptyChildren with - | [] -> lm.lg.getEmptySequenceInitExpression () - | _ -> lm.init.initSequenceExpr nonEmptyChildren arrsOptionalChildren - - let optChildrenString: String = // opt children will be first in scala - let optionalChildrenDefaultInit = - children |> - List.choose(fun c -> match c with Asn1Child x -> Some x | _ -> None) |> - List.choose(fun c -> - match c.Optionality with - | Some (Asn1AcnAst.Optional _) | Some (Asn1AcnAst.AlwaysPresent) | Some (Asn1AcnAst.AlwaysAbsent) -> Some("true") - | _ -> None - ) - if optionalChildrenDefaultInit.Length > 0 then - match typeDefinition with - | ReferenceToExistingDefinition referenceToExistingDefinition -> referenceToExistingDefinition.typedefName + "_exist(" + String.Join(", ", optionalChildrenDefaultInit) + "), " - | TypeDefinition typeDefinition -> typeDefinition.typedefName + "_exist(" + String.Join(", ", optionalChildrenDefaultInit) + "), " - else - "" - - let extractAsn1Types: Asn1TypeKind list = - children |> - List.choose(fun c -> match c with Asn1Child x -> Some x.Type.Kind | _ -> None) |> - List.map(fun k -> resolveReferenceType k) + | [] -> lm.lg.getEmptySequenceInitExpression tdName + | _ -> lm.init.initSequenceExpr tdName (lm.lg.getSequenceTypeDefinition o.typeDef).exist nonEmptyChildren arrsOptionalChildren - let defaultParamListForScala: String = - match ST.lang with - | ProgrammingLanguage.Scala -> - match typeDefinition with - | TypeDefinition td -> - td.typedefName + "(" + optChildrenString + - match extractAsn1Types with - | [] -> "" - | x -> ( x |> List.map (fun c -> extractDefaultInitValue c) |> List.reduce (fun c1 c2 -> c1 + ", " + c2)) - + ")" - | ReferenceToExistingDefinition r -> "TODO" - | _ -> "" - - createInitFunctionCommon r lm t typeDefinition defaultParamListForScala initByAsn1ValueFnc - initTasFunction testCaseFuncs (constantInitExpression getChildExpression) - (constantInitExpression getChildExpressionGlobal) nonEmbeddedChildrenFuncs [] + let init = constantInitExpression getChildExpression + let initGlob = constantInitExpression getChildExpressionGlobal + createInitFunctionCommon r lm t typeDefinition initByAsn1ValueFnc + initTasFunction testCaseFuncs + init initGlob nonEmbeddedChildrenFuncs [] -let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (children:ChChildInfo list) = +let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (children:ChChildInfo list) = let initTestCase_choice_child = lm.init.initTestCase_choice_child let initChildWithInitFunc = lm.init.initChildWithInitFunc let initChoice = lm.init.initChoice - let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules - let funcBody (p:CallerScope) (v:Asn1ValueKind) = - let childrenOut = + let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules + let funcBody (p:CallerScope) (v:Asn1ValueKind) = + let childrenOut = match v.ActualValue with - | ChValue iv -> - children |> - List.choose(fun chChild -> + | ChValue iv -> + children |> + List.choose(fun chChild -> match chChild.Name.Value = iv.name with | false -> None | true -> - let sChildTypeName = chChild.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules + let sChildTypeName = chChild.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules let sChoiceTypeName = typeDefinition.longTypedefName2 lm.lg.hasModules let sChildName = (lm.lg.getAsn1ChChildBackendName chChild) let sChildTempVarName = (ToC chChild.chType.id.AsString) + "_tmp" - let chContent = + let chContent = match lm.lg.init.choiceComponentTempInit with | false -> chChild.chType.initFunction.initByAsn1Value ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName chChild) chChild.chType.isIA5String}) iv.Value.kind | true -> - chChild.chType.initFunction.initByAsn1Value ({CallerScope.modName = t.id.ModName; arg = VALUE sChildTempVarName}) iv.Value.kind - Some (initChoice p.arg.p (lm.lg.getAccess p.arg) chContent (lm.lg.presentWhenName (Some typeDefinition) chChild) sChildName sChildTypeName sChoiceTypeName sChildTempVarName (extractDefaultInitValue chChild.chType.Kind) lm.lg.init.choiceComponentTempInit) - ) + chChild.chType.initFunction.initByAsn1Value ({CallerScope.modName = t.id.ModName; arg = Selection.valueEmptyPath sChildTempVarName}) iv.Value.kind + Some (initChoice (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) chContent (lm.lg.presentWhenName (Some typeDefinition) chChild) sChildName sChildTypeName sChoiceTypeName sChildTempVarName (extractDefaultInitValue chChild.chType.Kind) lm.lg.init.choiceComponentTempInit) + ) | _ -> raise(BugErrorException "UnexpectedValue") childrenOut |> Seq.head - let testCaseFuncs = - let handleChild (ch:ChChildInfo) = + let testCaseFuncs = + let handleChild (ch:ChChildInfo) = let sChildID (p:CallerScope) = match ST.lang with | ProgrammingLanguage.Scala -> (lm.lg.presentWhenName (Some typeDefinition) ch) @@ -1164,23 +1037,23 @@ let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs let len = ch.chType.initFunction.automaticTestCases.Length let sChildName = (lm.lg.getAsn1ChChildBackendName ch) - let sChildTypeDef = ch.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules + let sChildTypeDef = ch.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules let sChildTempVarName = (ToC ch.chType.id.AsString) + "_tmp" - ch.chType.initFunction.automaticTestCases (*|> Seq.take (min 5 len)*) |> Seq.toList |> - List.map(fun atc -> + ch.chType.initFunction.automaticTestCases |> Seq.toList |> + List.map(fun atc -> let fnc = atc.initTestCaseFunc - let presentFunc (p:CallerScope) = + let presentFunc (p:CallerScope) = let childContent_funcBody, childContent_localVariables = let childContent = match ST.lang with - | ProgrammingLanguage.Scala -> + | ProgrammingLanguage.Scala -> match lm.lg.init.choiceComponentTempInit with | false -> fnc {p with arg = lm.lg.getChChild p.arg sChildTempVarName ch.chType.isIA5String} - | true -> fnc {p with arg = VALUE (sChildName + "_tmp")} + | true -> fnc {p with arg = Selection.valueEmptyPath (sChildName + "_tmp")} | _ -> match lm.lg.init.choiceComponentTempInit with - | false -> fnc {p with arg = lm.lg.getChChild p.arg sChildName ch.chType.isIA5String} - | true -> fnc {p with arg = VALUE (sChildName + "_tmp")} + | false -> fnc {p with arg = lm.lg.getChChild p.arg sChildName ch.chType.isIA5String} + | true -> fnc {p with arg = Selection.valueEmptyPath (sChildName + "_tmp")} childContent.funcBody, childContent.localVariables let sChildTempDefaultInit = @@ -1188,7 +1061,7 @@ let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs | ProgrammingLanguage.Scala -> sChildTypeDef + (lm.init.methodNameSuffix()) + "()" | _ -> (extractDefaultInitValue ch.chType.Kind) - let funcBody = initTestCase_choice_child p.arg.p (lm.lg.getAccess p.arg) (childContent_funcBody) (sChildID p) sChildName sChildTypeDef typeDefinitionName sChildTempVarName sChildTempDefaultInit + let funcBody = initTestCase_choice_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (childContent_funcBody) (sChildID p) sChildName sChildTypeDef typeDefinitionName sChildTempVarName sChildTempDefaultInit {InitFunctionResult.funcBody = funcBody; localVariables = childContent_localVariables} let combinedTestCase = match atc.testCaseTypeIDsMap.ContainsKey ch.chType.id with @@ -1197,7 +1070,7 @@ let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs {AutomaticTestCase.initTestCaseFunc = presentFunc; testCaseTypeIDsMap = combinedTestCase } ) match r.args.generateAutomaticTestCases with - | true -> + | true -> children |> //if some alternatives have restricted to always ABSENT (via WITH COMPONENTS constraint) then do not produce a test case for them. List.filter (fun c -> c.Optionality.IsNone || c.Optionality = (Some Asn1AcnAst.Asn1ChoiceOptionality.ChoiceAlwaysPresent)) |> @@ -1206,20 +1079,20 @@ let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs let initTasFunction (p:CallerScope) = - let handleChild (ch:ChChildInfo) = + let handleChild (ch:ChChildInfo) = let sChildName = (lm.lg.getAsn1ChChildBackendName ch) - let sChildTypeDef = ch.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules + let sChildTypeDef = ch.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules let sChildTempVarName = (ToC ch.chType.id.AsString) + "_tmp" let chp = {p with arg = lm.lg.getChChild p.arg (match ST.lang with | ProgrammingLanguage.Scala -> sChildTempVarName | _ -> sChildName) ch.chType.isIA5String} - let sChildID = (lm.lg.presentWhenName (Some typeDefinition) ch) - let childContent_funcBody, childContent_localVariables = + let sChildID = (lm.lg.presentWhenName (Some typeDefinition) ch) + let childContent_funcBody, childContent_localVariables = match ch.chType.initFunction.initProcedure with | None -> let fnc = ch.chType.initFunction.initTas - let childContent = + let childContent = match lm.lg.init.choiceComponentTempInit with | false -> fnc chp - | true -> fnc {p with arg = VALUE (sChildName + "_tmp")} + | true -> fnc {p with arg = Selection.valueEmptyPath (sChildName + "_tmp")} childContent.funcBody, childContent.localVariables | Some initProc -> match lm.lg.init.choiceComponentTempInit with @@ -1229,43 +1102,37 @@ let createChoiceInitFunc (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs initChildWithInitFunc sChildTempVarName initProc.funcName, [] | _ -> initChildWithInitFunc (lm.lg.getPointer chp.arg) initProc.funcName, [] - | true -> initChildWithInitFunc (sChildName + "_tmp") initProc.funcName, [] - let funcBody = initChoice p.arg.p (lm.lg.getAccess p.arg) childContent_funcBody sChildID sChildName sChildTypeDef typeDefinitionName sChildTempVarName (extractDefaultInitValue ch.chType.Kind) lm.lg.init.choiceComponentTempInit + | true -> initChildWithInitFunc (sChildName + "_tmp") initProc.funcName, [] + let funcBody = initChoice (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childContent_funcBody sChildID sChildName sChildTypeDef typeDefinitionName sChildTempVarName (extractDefaultInitValue ch.chType.Kind) lm.lg.init.choiceComponentTempInit {InitFunctionResult.funcBody = funcBody; localVariables = childContent_localVariables} match children with | x::_ -> handleChild x | _ -> {InitFunctionResult.funcBody = ""; localVariables = []} - - let nonEmbeddedChildrenFuncs = - children |> List.choose(fun ch -> + + let nonEmbeddedChildrenFuncs = + children |> List.choose(fun ch -> match ch.chType.initFunction.initProcedure with | None -> None | Some _ when r.args.generateConstInitGlobals -> None | Some _ -> Some ch.chType.initFunction) - let constantInitExpression getChildExp = - children |> - List.map (fun c -> + let constantInitExpression getChildExp = + children |> + List.map (fun c -> let childName = lm.lg.getAsn1ChChildBackendName c let presentWhenName = lm.lg.presentWhenName (Some typeDefinition) c - + let childExp = getChildExp lm c.chType - lm.init.initChoiceExpr childName presentWhenName childExp ) |> + lm.init.initChoiceExpr childName presentWhenName childExp) |> List.head - createInitFunctionCommon r lm t typeDefinition o.defaultInitVal funcBody initTasFunction testCaseFuncs (constantInitExpression getChildExpression) (constantInitExpression getChildExpressionGlobal) nonEmbeddedChildrenFuncs [] + createInitFunctionCommon r lm t typeDefinition funcBody initTasFunction testCaseFuncs (constantInitExpression getChildExpression) (constantInitExpression getChildExpressionGlobal) nonEmbeddedChildrenFuncs [] -let createReferenceType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (baseType:Asn1Type) = +let createReferenceType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o :Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (baseType:Asn1Type) = let initChildWithInitFunc = lm.init.initChildWithInitFunc let nonEmbeddedChildrenFuncs = [] - (* - let moduleName, typeDefinitionName = - let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let typeDef = lm.lg.getTypeDefinition t1.FT_TypeDefintion - typeDef.programUnit, typeDef.typeName -*) - let moduleName, typeDefinitionName = + let moduleName, typeDefinitionName = match typeDefinition with | ReferenceToExistingDefinition refToExist -> match refToExist.programUnit with @@ -1274,37 +1141,41 @@ let createReferenceType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst | TypeDefinition tdDef -> match tdDef.baseType with | None -> ToC t.id.ModName, tdDef.typedefName - | Some refToExist -> + | Some refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName | None -> ToC t.id.ModName, refToExist.typedefName - + let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let t1WithExtensios = o.resolvedType; + let t1WithExtensions = o.resolvedType; let bs = baseType.initFunction - match TypesEquivalence.uperEquivalence t1 t1WithExtensios with - | false -> - createInitFunctionCommon r lm t typeDefinition (extractDefaultInitValue baseType.Kind) bs.initByAsn1Value bs.initTas bs.automaticTestCases bs.initExpression bs.initExpressionGlobal bs.nonEmbeddedChildrenFuncs [] + match TypesEquivalence.uperEquivalence t1 t1WithExtensions with + | false -> + createInitFunctionCommon r lm t typeDefinition bs.initByAsn1Value bs.initTas bs.automaticTestCases bs.initExpression bs.initExpressionGlobal bs.nonEmbeddedChildrenFuncs [] | true -> match t.isComplexType with | true -> - let baseFncName, baseGlobaleName = + let baseFncName, baseGlobalName = let funcName = typeDefinitionName + (lm.init.methodNameSuffix()) let globalName = typeDefinitionName + "_constant" match lm.lg.hasModules with | false -> funcName, globalName - | true -> + | true -> match t.id.ModName = o.modName.Value with | true -> funcName, globalName | false -> moduleName + "." + funcName, moduleName + "." + globalName - let constantInitExpression = baseFncName - let constantInitExpressionGlobal = baseGlobaleName + let constantInitExpression = + match ST.lang with + | ProgrammingLanguage.Scala -> + baseFncName + (scalaInitMethSuffix baseType.Kind) + | _ -> baseFncName + let constantInitExpressionGlobal = baseGlobalName let initTasFunction (p:CallerScope) = let funcBody = initChildWithInitFunc (lm.lg.getPointer p.arg) baseFncName {InitFunctionResult.funcBody = funcBody; localVariables = []} - createInitFunctionCommon r lm t typeDefinition (extractDefaultInitValue baseType.Kind) bs.initByAsn1Value initTasFunction bs.automaticTestCases constantInitExpression constantInitExpressionGlobal nonEmbeddedChildrenFuncs [] + createInitFunctionCommon r lm t typeDefinition bs.initByAsn1Value initTasFunction bs.automaticTestCases constantInitExpression constantInitExpressionGlobal nonEmbeddedChildrenFuncs [] | false -> - createInitFunctionCommon r lm t typeDefinition (extractDefaultInitValue baseType.Kind) bs.initByAsn1Value bs.initTas bs.automaticTestCases bs.initExpression bs.initExpressionGlobal bs.nonEmbeddedChildrenFuncs [] + createInitFunctionCommon r lm t typeDefinition bs.initByAsn1Value bs.initTas bs.automaticTestCases bs.initExpression bs.initExpressionGlobal bs.nonEmbeddedChildrenFuncs [] diff --git a/BackendAst/DAstProgramUnit.fs b/BackendAst/DAstProgramUnit.fs index faed10770..147c60d49 100644 --- a/BackendAst/DAstProgramUnit.fs +++ b/BackendAst/DAstProgramUnit.fs @@ -11,9 +11,9 @@ open DAstUtilFunctions open Language -let private getTypeDependencies (t:Asn1Type) : (TypeAssignmentInfo list ) +let private getTypeDependencies (t:Asn1Type) : (TypeAssignmentInfo list ) = - let prms = t.acnParameters |> List.choose(fun z -> match z.asn1Type with AcnGenericTypes.AcnPrmRefType (mdName,tsName) -> Some ({TypeAssignmentInfo.modName = mdName.Value; tasName = tsName.Value}) | _ -> None ) + let prms = t.acnParameters |> List.choose(fun z -> match z.asn1Type with AcnGenericTypes.AcnPrmRefType (mdName,tsName) -> Some ({TypeAssignmentInfo.modName = mdName.Value; tasName = tsName.Value}) | _ -> None ) DastFold.foldAsn1Type t () @@ -38,12 +38,12 @@ let private getTypeDependencies (t:Asn1Type) : (TypeAssignmentInfo list ) let private getImportedModules (files: Asn1File list) (t:Asn1Type) = - let rec getImportedModules_aux (t:Asn1Type) = + let rec getImportedModules_aux (t:Asn1Type) = seq { yield t.moduleName match t.Kind with | SequenceOf seqOf -> yield! getImportedModules_aux seqOf.childType - | Sequence seq -> + | Sequence seq -> for c in seq.children do match c with | Asn1Child c -> yield! getImportedModules_aux c.Type @@ -60,7 +60,7 @@ let private getImportedModules (files: Asn1File list) (t:Asn1Type) = getImportedModules_aux t let rec private getTypeDependencies2 (t:Asn1Type) : (TypeAssignmentInfo list ) = - let prms = t.acnParameters |> List.choose(fun z -> match z.asn1Type with AcnGenericTypes.AcnPrmRefType (mdName,tsName) -> Some ({TypeAssignmentInfo.modName = mdName.Value; tasName = tsName.Value}) | _ -> None ) + let prms = t.acnParameters |> List.choose(fun z -> match z.asn1Type with AcnGenericTypes.AcnPrmRefType (mdName,tsName) -> Some ({TypeAssignmentInfo.modName = mdName.Value; tasName = tsName.Value}) | _ -> None ) match t.Kind with | Integer _ -> prms | Real _ -> prms @@ -71,29 +71,29 @@ let rec private getTypeDependencies2 (t:Asn1Type) : (TypeAssignmentInfo list ) | Boolean _ -> prms | Enumerated _ -> prms | ObjectIdentifier _ -> prms - | SequenceOf sqof -> prms@(getTypeDependencies2 sqof.childType) + | SequenceOf sqof -> prms@(getTypeDependencies2 sqof.childType) | Sequence children -> prms@(children.Asn1Children |> List.collect (fun ch -> getTypeDependencies2 ch.Type)) | Choice children -> prms@(children.children |> List.collect (fun ch -> getTypeDependencies2 ch.chType)) | ReferenceType ref -> ref.AsTypeAssignmentInfo::prms | TimeType _ -> prms let internal sortTypes (typesToSort: Asn1Type list) (imports :TypeAssignmentInfo list) = - let allNodes = - typesToSort |> - List.choose( fun tas -> + let allNodes = + typesToSort |> + List.choose( fun tas -> match tas.typeAssignmentInfo with | Some (TypeAssignmentInfo tasInfo) -> Some ( (tasInfo, getTypeDependencies2 tas )) - | Some (ValueAssignmentInfo _) + | Some (ValueAssignmentInfo _) | None -> raise (BugErrorException "All TypeAssignments must have tasInfo") ) let independentNodes = allNodes |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map(fun (n,l) -> n) let dependentNodes = allNodes |> List.filter(fun (_,list) -> not (List.isEmpty list) ) - let sortedTypeAss = - DoTopologicalSort (imports @ independentNodes) dependentNodes - (fun cyclicTasses -> + let sortedTypeAss = + DoTopologicalSort (imports @ independentNodes) dependentNodes + (fun cyclicTasses -> match cyclicTasses with | [] -> BugErrorException "Impossible" | (m1,deps) ::_ -> - let printTas (md:TypeAssignmentInfo, deps: TypeAssignmentInfo list) = + let printTas (md:TypeAssignmentInfo, deps: TypeAssignmentInfo list) = sprintf "Type assignment '%s.%s' depends on : %s" md.modName md.tasName (deps |> List.map(fun z -> "'" + z.modName + "." + z.tasName + "'") |> Seq.StrJoin ", ") let cycTasses = cyclicTasses |> List.map printTas |> Seq.StrJoin "\n\tand\n" SemanticError(emptyLocation, sprintf "Cyclic Types detected:\n%s\n" cycTasses) ) @@ -104,11 +104,11 @@ let internal sortTypes (typesToSort: Asn1Type list) (imports :TypeAssignmentInfo let internal createProgramUnits (args:CommandLineSettings) (files: Asn1File list) (lm:LanguageMacros) = match lm.lg.hasModules with - | false -> + | false -> files |> - List.map(fun f -> + List.map(fun f -> let modulesSet = f.Modules |> List.map(fun x -> x.Name.Value) |> Set.ofList - let fileTases = + let fileTases = seq { for m in f.Modules do for tas in m.TypeAssignments do @@ -117,10 +117,10 @@ let internal createProgramUnits (args:CommandLineSettings) (files: Asn1File list let fileValueAssignments = f.Modules |> List.collect(fun m -> m.ValueAssignments) let tasSet = Map.ofList fileTases let fileTypes = fileTases |> List.map snd |> List.map(fun t -> t.Type) - let valueAssignments = f.Modules |> Seq.collect(fun v -> v.ValueAssignments) + let valueAssignments = f.Modules |> Seq.collect(fun v -> v.ValueAssignments) let thisFileModules = f.Modules |> List.map(fun x -> x.Name.Value) let importedModules = - f.Modules |> + f.Modules |> Seq.collect(fun m -> m.Imports) |> Seq.filter(fun m -> not (thisFileModules |> Seq.exists ((=) m.Name.Value) )) |> Seq.toList @@ -129,95 +129,89 @@ let internal createProgramUnits (args:CommandLineSettings) (files: Asn1File list importedModules |> List.map(fun imp -> let impFile = files |> Seq.find(fun f -> f.Modules |> Seq.exists (fun md -> md.Name.Value = imp.Name.Value) ) - impFile.FileNameWithoutExtension) |> + impFile.FileNameWithoutExtension) |> Seq.distinct |> Seq.toList - let importedTypes = + let importedTypes = importedModules |> - Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value} )) |> + Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value} )) |> Seq.distinct |> Seq.toList - let sortedTypes = - sortTypes fileTypes importedTypes |> - List.choose(fun ref -> + let sortedTypes = + sortTypes fileTypes importedTypes |> + List.choose(fun ref -> match tasSet.TryFind ref with | Some vl -> Some vl - | None -> None (*raise(SemanticError(emptyLocation, sprintf "Type assignment %s.%s cannot be resolved within progam unit %s" ref.modName ref.tasName f.FileNameWithoutExtension))*) + | None -> None (*raise(SemanticError(emptyLocation, sprintf "Type assignment %s.%s cannot be resolved within program unit %s" ref.modName ref.tasName f.FileNameWithoutExtension))*) ) - let mappingFunctionsModules = sortedTypes |> List.map(fun t -> GetMySelfAndChildren t.Type |> List.map(fun q -> q.MappingFunctionsModules) |> List.collect id) |> List.collect id + let mappingFunctionsModules = sortedTypes |> List.map(fun t -> GetMySelfAndChildren t.Type |> List.map(fun q -> q.MappingFunctionsModules) |> List.collect id) |> List.collect id let importedUserModules = mappingFunctionsModules@(args.mappingFunctionsModule |> Option.toList) |> List.distinct - let specFileName = f.FileNameWithoutExtension + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention - let bodyFileName = f.FileNameWithoutExtension+"."+lm.lg.BodyExtention - let testcase_specFileName = f.FileNameWithoutExtension+"_auto_tcs"+ lm.lg.SpecNameSuffix+"."+lm.lg.SpecExtention - let testcase_bodyFileName = f.FileNameWithoutExtension+"_auto_tcs."+lm.lg.BodyExtention + let specFileName = f.FileNameWithoutExtension + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension + let bodyFileName = f.FileNameWithoutExtension+"."+lm.lg.BodyExtension + let testcase_specFileName = f.FileNameWithoutExtension+"_auto_tcs"+ lm.lg.SpecNameSuffix+"."+lm.lg.SpecExtension + let testcase_bodyFileName = f.FileNameWithoutExtension+"_auto_tcs."+lm.lg.BodyExtension let testcase_name = f.FileNameWithoutExtension+"_auto_tcs" {ProgramUnit.name = f.FileNameWithoutExtension; specFileName = specFileName; bodyFileName=bodyFileName; sortedTypeAssignments = sortedTypes; valueAssignments = fileValueAssignments; importedProgramUnits = importedProgramUnits; testcase_specFileName=testcase_specFileName; testcase_bodyFileName=testcase_bodyFileName; testcase_name=testcase_name; importedTypes= []; importedUserModules=importedUserModules}) - | true -> - let typesMap = - files |> + | true -> + let typesMap = + files |> List.collect(fun f -> f.Modules) |> List.collect(fun m -> - m.TypeAssignments |> List.map(fun tas -> tas.AsTypeAssignmentInfo m.Name.Value, tas) + m.TypeAssignments |> List.map(fun tas -> tas.AsTypeAssignmentInfo m.Name.Value, tas) ) |> Map.ofList files |> List.collect(fun f -> f.Modules |> List.map (fun m -> f,m)) |> List.map(fun (f,m) -> - let moduTypes = m.TypeAssignments |> List.map(fun x -> x.Type) + let moduleTypes = m.TypeAssignments |> List.map(fun x -> x.Type) let valueAssignments = m.ValueAssignments - - let importedTypes = + + let importedTypes = m.Imports |> - Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value})) |> - Seq.distinct |> Seq.toList - let sortedTypes = sortTypes moduTypes importedTypes |> List.filter(fun z -> z.modName = m.Name.Value) |> List.map(fun ref -> typesMap.[ref]) + Seq.collect(fun imp -> imp.Types |> List.map (fun impType ->{TypeAssignmentInfo.modName = imp.Name.Value; tasName = impType.Value})) |> + Seq.distinct |> Seq.toList + let sortedTypes = sortTypes moduleTypes importedTypes |> List.filter(fun z -> z.modName = m.Name.Value) |> List.map(fun ref -> typesMap.[ref]) - //debud start + //debug start //sortedTypes |> Seq.iter(fun tas -> printfn "%s\t%d\n" tas.Name.Value tas.Name.Location.srcLine) //debug end let depTypesFromOtherModules = - sortedTypes |> + sortedTypes |> List.collect (fun t -> getTypeDependencies t.Type) |> - List.filter (fun t -> t.modName <> m.Name.Value) - let importedProgramUnitsFromVases = - valueAssignments |> + List.filter (fun t -> t.modName <> m.Name.Value) + let importedProgramUnitsFromVases = + valueAssignments |> List.collect(fun z -> getImportedModules files z.Type) |> List.filter(fun z -> ToC z <> ToC m.Name.Value) |> List.map (fun z -> ToC z) - (*List.choose(fun z -> - match z.Type.Kind with - |ReferenceType ref -> - match ref.baseInfo.modName.Value = m.Name.Value with - | true -> None - | false -> Some (ToC ref.baseInfo.modName.Value) - | _ -> None)*) - let importedProgramUnitsFromTasses = + + let importedProgramUnitsFromTasses = depTypesFromOtherModules |> Seq.map(fun ti -> ToC ti.modName) |> Seq.distinct |> Seq.toList let importedProgramUnits = importedProgramUnitsFromTasses@importedProgramUnitsFromVases |> Seq.distinct |> Seq.toList - let importedTypes = - depTypesFromOtherModules |> - List.collect(fun ts -> + let importedTypes = + depTypesFromOtherModules |> + List.collect(fun ts -> let t = typesMap.[ts] let allTypes = GetMySelfAndChildren t.Type - - - let aaa = - allTypes |> - List.choose (fun t -> - let rtlPrimitve = + + + let aaa = + allTypes |> + List.choose (fun t -> + let rtlPrimitive = match t.Kind with - | Integer _ - | Real _ - | Boolean _ + | Integer _ + | Real _ + | Boolean _ | NullType _ -> true | _ -> false - getFuncNameGeneric2 t.typeDefintionOrReference) |> - //getFuncNameGeneric2 args t.tasInfo t.inheritInfo rtlPrimitve t.typeDefintionOrReference) |> + getFuncNameGeneric2 t.typeDefinitionOrReference) |> + //getFuncNameGeneric2 args t.tasInfo t.inheritInfo rtlPrimitive t.typeDefinitionOrReference) |> List.map(fun td -> (ToC ts.modName) + "." + td) |> List.distinct aaa) |> List.distinct @@ -225,10 +219,10 @@ let internal createProgramUnits (args:CommandLineSettings) (files: Asn1File list let mappingFunctionsModules = sortedTypes |> List.map(fun t -> GetMySelfAndChildren t.Type |> List.map(fun q -> q.MappingFunctionsModules) |> List.collect id) |> List.collect id |> List.distinct let importedUserModules = mappingFunctionsModules@(args.mappingFunctionsModule |> Option.toList) |> List.distinct - let specFileName = ToC (m.Name.Value.ToLower()) + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention - let bodyFileName = ToC (m.Name.Value.ToLower()) + "." + lm.lg.BodyExtention - let testcase_specFileName = ToC (m.Name.Value.ToLower()) + "_auto_tcs" + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention - let testcase_bodyFileName = ToC (m.Name.Value.ToLower()) + "_auto_tcs." + lm.lg.BodyExtention + let specFileName = ToC (m.Name.Value.ToLower()) + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension + let bodyFileName = ToC (m.Name.Value.ToLower()) + "." + lm.lg.BodyExtension + let testcase_specFileName = ToC (m.Name.Value.ToLower()) + "_auto_tcs" + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension + let testcase_bodyFileName = ToC (m.Name.Value.ToLower()) + "_auto_tcs." + lm.lg.BodyExtension //let importedProgramUnits = m.Imports |> List.map (fun im -> ToC im.Name.Value) let testcase_name = ToC (m.Name.Value.ToLower()+"_auto_tcs") {ProgramUnit.name = ToC m.Name.Value; specFileName = specFileName; bodyFileName=bodyFileName; sortedTypeAssignments = sortedTypes; valueAssignments = valueAssignments; importedProgramUnits = importedProgramUnits; testcase_specFileName=testcase_specFileName; testcase_bodyFileName=testcase_bodyFileName; testcase_name=testcase_name; importedTypes= importedTypes; importedUserModules=importedUserModules}) diff --git a/BackendAst/DAstTypeDefinition.fs b/BackendAst/DAstTypeDefinition.fs index 68052af55..7fb4aaa65 100644 --- a/BackendAst/DAstTypeDefinition.fs +++ b/BackendAst/DAstTypeDefinition.fs @@ -12,7 +12,7 @@ open Asn1Fold open Language -let getIntererTypeByClass (lm:LanguageMacros) intClass = +let getIntegerTypeByClass (lm:LanguageMacros) intClass = match intClass with | ASN1SCC_Int8 (_) -> lm.typeDef.Declare_Int8 | ASN1SCC_Int16 (_) -> lm.typeDef.Declare_Int16 @@ -25,22 +25,22 @@ let getIntererTypeByClass (lm:LanguageMacros) intClass = | ASN1SCC_UInt64 (_) -> lm.typeDef.Declare_UInt64 | ASN1SCC_UInt (_) -> lm.typeDef.Declare_PosInteger -let getRealTypeByClass (lm:LanguageMacros) realClass = +let getRealTypeByClass (lm:LanguageMacros) realClass = match realClass with | ASN1SCC_REAL -> lm.typeDef.Declare_Real | ASN1SCC_FP32 -> lm.typeDef.Declare_Real32 | ASN1SCC_FP64 -> lm.typeDef.Declare_Real64 - + let createInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (us:State) = - let declare_Integer = getIntererTypeByClass lm o.intClass + let declare_Integer = getIntegerTypeByClass lm o.intClass let rtlModuleName = if lm.typeDef.rtlModuleName().IsEmptyOrNull then None else (Some (lm.typeDef.rtlModuleName ())) - let defineSubType = lm.typeDef.Define_SubType + let defineSubType = lm.typeDef.Define_SubType let define_SubType_int_range = lm.typeDef.Define_SubType_int_range - let getNewRange soInheritParentTypePackage sInheritParentType = + let getNewRange soInheritParentTypePackage sInheritParentType = match o.uperRange with | Concrete(a,b) -> Some (define_SubType_int_range soInheritParentTypePackage sInheritParentType (Some a) (Some b)) | NegInf (b) -> Some (define_SubType_int_range soInheritParentTypePackage sInheritParentType None (Some b)) @@ -54,46 +54,25 @@ let createInteger (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1T let baseType = declare_Integer() let typedefBody = defineSubType td.typeName None baseType (getNewRange None baseType) None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName (getNewRange otherProgramUnit subDef.typeName) None Some typedefBody - (* - let rec hasSameClasWithBase (t:Asn1AcnAst.Asn1Type) = - match t.inheritInfo with - | None -> false - | Some inhInf -> - let baseMod = r.GetModuleByName inhInf.modName.AsLoc - let baseTas = baseMod.GetTypeAssignmentByName inhInf.tasName.AsLoc r - match baseTas.Type.Kind with - | Asn1AcnAst.Integer bo -> bo.intClass = o.intClass - | Asn1AcnAst.ReferenceType br -> hasSameClasWithBase br.resolvedType - | _ -> false - match hasSameClasWithBase t with - | true -> - let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName (getNewRange otherProgramUnit subDef.typeName) None - Some typedefBody - | false -> - let baseType = declare_Integer() - let typedefBody = defineSubType td.typeName None baseType (getNewRange None baseType) None - Some typedefBody - *) | PrimitiveReference2RTL -> None | PrimitiveReference2OtherType -> None let createBoolean (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (us:State) = - let getRtlTypeName = lm.typeDef.Declare_BooleanNoRTL + let getRtlTypeName = lm.typeDef.Declare_BooleanNoRTL let defineSubType = lm.typeDef.Define_SubType let rtlModuleName = if lm.typeDef.rtlModuleName().IsEmptyOrNull then None else (Some (lm.typeDef.rtlModuleName ())) let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> let baseType = getRtlTypeName() let typedefBody = defineSubType td.typeName rtlModuleName baseType None None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName None None Some typedefBody @@ -108,11 +87,11 @@ let createReal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> let baseType = getRtlTypeName() let typedefBody = defineSubType td.typeName None baseType None None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName None None Some typedefBody @@ -120,17 +99,17 @@ let createReal (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type | PrimitiveReference2OtherType -> None let createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (us:State) = - let getRtlTypeName = lm.typeDef.Declare_ObjectIdentifierNoRTL + let getRtlTypeName = lm.typeDef.Declare_ObjectIdentifierNoRTL let defineSubType = lm.typeDef.Define_SubType let rtlModuleName = if lm.typeDef.rtlModuleName().IsEmptyOrNull then None else (Some (lm.typeDef.rtlModuleName ())) let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> let baseType = getRtlTypeName() let typedefBody = defineSubType td.typeName rtlModuleName baseType None None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName None None Some typedefBody @@ -139,28 +118,28 @@ let createObjectIdentifier (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn let createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (us:State) = - - let getRtlTypeName = + + let getRtlTypeName = match o.timeClass with - |Asn1LocalTime _ -> lm.typeDef.Declare_Asn1LocalTimeNoRTL - |Asn1UtcTime _ -> lm.typeDef.Declare_Asn1UtcTimeNoRTL - |Asn1LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1LocalTimeWithTimeZoneNoRTL - |Asn1Date -> lm.typeDef.Declare_Asn1DateNoRTL - |Asn1Date_LocalTime _ -> lm.typeDef.Declare_Asn1Date_LocalTimeNoRTL - |Asn1Date_UtcTime _ -> lm.typeDef.Declare_Asn1Date_UtcTimeNoRTL - |Asn1Date_LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1Date_LocalTimeWithTimeZoneNoRTL - + |Asn1LocalTime _ -> lm.typeDef.Declare_Asn1LocalTimeNoRTL + |Asn1UtcTime _ -> lm.typeDef.Declare_Asn1UtcTimeNoRTL + |Asn1LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1LocalTimeWithTimeZoneNoRTL + |Asn1Date -> lm.typeDef.Declare_Asn1DateNoRTL + |Asn1Date_LocalTime _ -> lm.typeDef.Declare_Asn1Date_LocalTimeNoRTL + |Asn1Date_UtcTime _ -> lm.typeDef.Declare_Asn1Date_UtcTimeNoRTL + |Asn1Date_LocalTimeWithTimeZone _ -> lm.typeDef.Declare_Asn1Date_LocalTimeWithTimeZoneNoRTL + let defineSubType = lm.typeDef.Define_SubType let rtlModuleName = if lm.typeDef.rtlModuleName().IsEmptyOrNull then None else (Some (lm.typeDef.rtlModuleName ())) let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> let baseType = getRtlTypeName() let typedefBody = defineSubType td.typeName rtlModuleName baseType None None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName None None Some typedefBody @@ -169,17 +148,17 @@ let createTimeType (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1 let createNull (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (us:State) = - let getRtlTypeName = lm.typeDef.Declare_NullNoRTL + let getRtlTypeName = lm.typeDef.Declare_NullNoRTL let defineSubType = lm.typeDef.Define_SubType let rtlModuleName = if lm.typeDef.rtlModuleName().IsEmptyOrNull then None else (Some (lm.typeDef.rtlModuleName ())) let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> let baseType = getRtlTypeName() let typedefBody = defineSubType td.typeName rtlModuleName baseType None None Some typedefBody - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) let typedefBody = defineSubType td.typeName otherProgramUnit subDef.typeName None None Some typedefBody @@ -193,13 +172,13 @@ let createString (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1T let td = lm.lg.getStrTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_ia5string td (o.minSize.uper) (o.maxSize.uper) ((o.maxSize.uper + 1I)) arrnAlphaChars - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_ia5string td (o.minSize.uper) (o.maxSize.uper) ((o.maxSize.uper + 1I)) arrnAlphaChars + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_ia5string td subDef otherProgramUnit - Some completeDefintion + let completeDefinition = define_subType_ia5string td subDef otherProgramUnit + Some completeDefinition | NonPrimitiveReference2OtherType -> None let createOctetString (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (us:State) = @@ -207,13 +186,13 @@ let createOctetString (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst. let define_new_octet_string = lm.typeDef.Define_new_octet_string let define_subType_octet_string = lm.typeDef.Define_subType_octet_string match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_octet_string td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_octet_string td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_octet_string td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) - Some completeDefintion + let completeDefinition = define_subType_octet_string td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) + Some completeDefinition | NonPrimitiveReference2OtherType -> None @@ -222,33 +201,33 @@ let createBitString (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.As let td = lm.lg.getSizeableTypeDefinition o.typeDef let define_new_bit_string = lm.typeDef.Define_new_bit_string let define_named_bit = lm.typeDef.Define_new_bit_string_named_bit - + let define_subType_bit_string = lm.typeDef.Define_subType_bit_string match td.kind with - | NonPrimitiveNewTypeDefinition -> - let nblist = - o.namedBitList |> + | NonPrimitiveNewTypeDefinition -> + let nblist = + o.namedBitList |> List.filter(fun nb -> nb.resolvedValue < 64I) |> List.map(fun nb -> - let hexValue = + let hexValue = let aa = int nb.resolvedValue let hexVal = ((uint64 1) <<< aa) hexVal.ToString("X") let sComment = sprintf "(1 << %A)" nb.resolvedValue define_named_bit td (ToC (nb.Name.Value.ToUpper())) hexValue sComment ) - let completeDefintion = define_new_bit_string td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) (BigInteger o.MaxOctets) nblist - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + let completeDefinition = define_new_bit_string td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) (BigInteger o.MaxOctets) nblist + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_bit_string td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) - Some completeDefintion + let completeDefinition = define_subType_bit_string td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) + Some completeDefinition | NonPrimitiveReference2OtherType -> None let createEnumerated (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (us:State) = - let td = lm.lg.getEnmTypeDefintion o.typeDef + let td = lm.lg.getEnumTypeDefinition o.typeDef let define_new_enumerated_item = lm.typeDef.Define_new_enumerated_item let define_new_enumerated_item_macro = lm.typeDef.Define_new_enumerated_item_macro let define_new_enumerated = lm.typeDef.Define_new_enumerated @@ -260,34 +239,34 @@ let createEnumerated (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.A let nIndexMax = BigInteger ((Seq.length o.items)-1) match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_enumerated td arrsEnumNames arrsEnumNamesAndValues nIndexMax macros - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_enumerated td arrsEnumNames arrsEnumNamesAndValues nIndexMax macros + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_enumerated td subDef otherProgramUnit - Some completeDefintion + let completeDefinition = define_subType_enumerated td subDef otherProgramUnit + Some completeDefinition | NonPrimitiveReference2OtherType -> None -let internal getChildDefinition (childDefinition:TypeDefintionOrReference) = +let internal getChildDefinition (childDefinition:TypeDefinitionOrReference) = match childDefinition with | TypeDefinition td -> Some (td.typedefBody ()) | ReferenceToExistingDefinition ref -> None -let createSequenceOf (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (childDefinition:TypeDefintionOrReference) (us:State) = +let createSequenceOf (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (childDefinition:TypeDefinitionOrReference) (us:State) = let define_new_sequence_of = lm.typeDef.Define_new_sequence_of let define_subType_sequence_of = lm.typeDef.Define_subType_sequence_of let td = lm.lg.getSizeableTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_sequence_of td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) (childDefinition.longTypedefName2 lm.lg.hasModules) (getChildDefinition childDefinition) - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_sequence_of td (o.minSize.uper) (o.maxSize.uper) (o.minSize.uper = o.maxSize.uper) (childDefinition.longTypedefName2 lm.lg.hasModules) (getChildDefinition childDefinition) + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_sequence_of td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) (getChildDefinition childDefinition) - Some completeDefintion + let completeDefinition = define_subType_sequence_of td subDef otherProgramUnit (o.minSize.uper = o.maxSize.uper) (getChildDefinition childDefinition) + Some completeDefinition | NonPrimitiveReference2OtherType -> None @@ -299,41 +278,41 @@ let createSequence (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1 let define_subType_sequence = lm.typeDef.Define_subType_sequence let define_new_sequence_save_pos_child = lm.typeDef.Define_new_sequence_save_pos_child - + let children = allchildren |> List.choose (fun c -> match c with Asn1Child z -> Some z | _ -> None) let optionalChildren = children |> List.choose(fun c -> match c.Optionality with Some _ -> Some c | None -> None) let optChildNames = optionalChildren |> List.map(fun c -> lm.lg.getAsn1ChildBackendName c) - let childldrenCompleteDefintions = children |> List.choose (fun c -> getChildDefinition c.Type.typeDefintionOrReference) + let childrenCompleteDefinitions = children |> List.choose (fun c -> getChildDefinition c.Type.typeDefinitionOrReference) let td = lm.lg.getSequenceTypeDefinition o.typeDef let arrsNullFieldsSavePos = let getBackendName ci = - match ci with + match ci with | AcnChild z -> z.c_name | Asn1Child z -> lm.lg.getAsn1ChildBackendName z match o.acnProperties.postEncodingFunction.IsNone && o.acnProperties.preDecodingFunction.IsNone with | true -> [] - | false -> - allchildren |> + | false -> + allchildren |> List.choose (fun c -> if c.savePosition then Some (getBackendName c) else None ) |> List.map(fun childName -> define_new_sequence_save_pos_child td childName o.acnMaxSizeInBits) - let arrsChildren = + let arrsChildren = match r.args.handleEmptySequences && lm.lg.requiresHandlingOfEmptySequences && children.IsEmpty with - | true -> [define_new_sequence_child "dummy" "int"] //define a dummy child for empty sequences - | false -> children |> List.map (fun o -> define_new_sequence_child (lm.lg.getAsn1ChildBackendName o) (o.Type.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules)) + | true -> [define_new_sequence_child "dummy" "int" false] //define a dummy child for empty sequences + | false -> children |> List.map (fun o -> define_new_sequence_child (lm.lg.getAsn1ChildBackendName o) (o.Type.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules) o.Optionality.IsSome) let arrsOptionalChildren = optionalChildren |> List.map(fun c -> define_new_sequence_child_bit (lm.lg.getAsn1ChildBackendName c)) match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_sequence td arrsChildren arrsOptionalChildren childldrenCompleteDefintions arrsNullFieldsSavePos - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_sequence td arrsChildren arrsOptionalChildren childrenCompleteDefinitions arrsNullFieldsSavePos + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_sequence td subDef otherProgramUnit arrsOptionalChildren - Some completeDefintion + let completeDefinition = define_subType_sequence td subDef otherProgramUnit arrsOptionalChildren + Some completeDefinition | NonPrimitiveReference2OtherType -> None @@ -346,20 +325,20 @@ let createChoice (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Ty let td = lm.lg.getChoiceTypeDefinition o.typeDef - let childldrenCompleteDefintions = children |> List.choose (fun c -> getChildDefinition c.chType.typeDefintionOrReference) + let childldrenCompleteDefinitions = children |> List.choose (fun c -> getChildDefinition c.chType.typeDefinitionOrReference) let arrsPresent = children |> List.map(fun c -> lm.lg.presentWhenName None c) - let arrsChildren = children |> List.map (fun o -> define_new_choice_child (lm.lg.getAsn1ChChildBackendName o) (o.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules) (lm.lg.presentWhenName None o)) + let arrsChildren = children |> List.map (fun o -> define_new_choice_child (lm.lg.getAsn1ChChildBackendName o) (o.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules) (lm.lg.presentWhenName None o)) let arrsCombined = List.map2 (fun x y -> x + "(" + y + ")") arrsPresent arrsChildren let nIndexMax = BigInteger ((Seq.length children)-1) match td.kind with - | NonPrimitiveNewTypeDefinition -> - let completeDefintion = define_new_choice td (lm.lg.choiceIDForNone us.typeIdsSet t.id) (lm.lg.presentWhenName None children.Head) arrsChildren arrsPresent arrsCombined nIndexMax childldrenCompleteDefintions - Some completeDefintion - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewTypeDefinition -> + let completeDefinition = define_new_choice td (lm.lg.choiceIDForNone us.typeIdsSet t.id) (lm.lg.presentWhenName None children.Head) arrsChildren arrsPresent arrsCombined nIndexMax childldrenCompleteDefinitions + Some completeDefinition + | NonPrimitiveNewSubTypeDefinition subDef -> let otherProgramUnit = if td.programUnit = subDef.programUnit then None else (Some subDef.programUnit) - let completeDefintion = define_subType_choice td subDef otherProgramUnit - Some completeDefintion + let completeDefinition = define_subType_choice td subDef otherProgramUnit + Some completeDefinition | NonPrimitiveReference2OtherType -> None @@ -371,14 +350,14 @@ let createInteger_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst. let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createReal_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (us:State) = @@ -386,14 +365,14 @@ let createReal_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1 let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createObjectIdentifier_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (us:State) = @@ -401,14 +380,14 @@ let createObjectIdentifier_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} @@ -417,14 +396,14 @@ let createTimeType_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} @@ -433,14 +412,14 @@ let createBoolean_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.A let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createNull_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (us:State) = @@ -448,14 +427,14 @@ let createNull_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1 let programUnit = ToC t.id.ModName let td = lm.lg.typeDef o.typeDef match td.kind with - | PrimitiveNewTypeDefinition -> + | PrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | PrimitiveNewSubTypeDefinition subDef -> + | PrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | PrimitiveReference2RTL -> + | PrimitiveReference2RTL -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = true} - | PrimitiveReference2OtherType -> + | PrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createOctetString_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (us:State) = @@ -463,12 +442,12 @@ let createOctetString_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnA let programUnit = ToC t.id.ModName let td = lm.lg.getSizeableTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} @@ -477,54 +456,54 @@ let createBitString_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs let programUnit = ToC t.id.ModName let td = lm.lg.getSizeableTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} - + let createString_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (us:State) = let aaa = createString r lm t o us let programUnit = ToC t.id.ModName let td = lm.lg.getStrTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createEnumerated_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (us:State) = let aaa = createEnumerated r lm t o us let programUnit = ToC t.id.ModName - let td = lm.lg.getEnmTypeDefintion o.typeDef + let td = lm.lg.getEnumTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} -let createSequenceOf_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (childDefinition:TypeDefintionOrReference) (us:State) = +let createSequenceOf_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (childDefinition:TypeDefinitionOrReference) (us:State) = let aaa = createSequenceOf r lm t o childDefinition us let programUnit = ToC t.id.ModName let td = lm.lg.getSizeableTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} @@ -533,12 +512,12 @@ let createSequence_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.A let programUnit = ToC t.id.ModName let td = lm.lg.getSequenceTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createChoice_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (children:ChChildInfo list) (us:State) = @@ -546,18 +525,18 @@ let createChoice_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn let programUnit = ToC t.id.ModName let td = lm.lg.getChoiceTypeDefinition o.typeDef match td.kind with - | NonPrimitiveNewTypeDefinition -> + | NonPrimitiveNewTypeDefinition -> TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=None} - | NonPrimitiveNewSubTypeDefinition subDef -> + | NonPrimitiveNewSubTypeDefinition subDef -> let baseType = {ReferenceToExistingDefinition.programUnit = (if subDef.programUnit = programUnit then None else Some subDef.programUnit); typedefName=subDef.typeName ; definedInRtl = false} TypeDefinition {TypeDefinition.typedefName = td.typeName; typedefBody = (fun () -> aaa.Value); baseType=Some baseType} - | NonPrimitiveReference2OtherType -> + | NonPrimitiveReference2OtherType -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = (if td.programUnit = programUnit then None else Some td.programUnit); typedefName= td.typeName; definedInRtl = false} let createReferenceType_u (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (baseType:Asn1Type ) (us:State) = match o.encodingOptions with - | None -> baseType.typeDefintionOrReference - | Some _ -> baseType.typeDefintionOrReference + | None -> baseType.typeDefinitionOrReference + | Some _ -> baseType.typeDefinitionOrReference + - diff --git a/BackendAst/DAstTypeDefinition2.fs b/BackendAst/DAstTypeDefinition2.fs index da195bf07..e978bc265 100644 --- a/BackendAst/DAstTypeDefinition2.fs +++ b/BackendAst/DAstTypeDefinition2.fs @@ -10,28 +10,28 @@ open DAst open DAstUtilFunctions (* -type TypeDefintionOrReference = +type TypeDefinitionOrReference = /// indicates that no extra type definition is required (e.g. INTEGER without constraints or type reference type without new constraints) - | ReferenceToExistingDefinition of ReferenceToExistingDefinition + | ReferenceToExistingDefinition of ReferenceToExistingDefinition /// indicates that a new type is defined - | TypeDefinition of TypeDefinition + | TypeDefinition of TypeDefinition examples A ::= INTEGER -> {TypeDefinition.typedefName = "A"; typedefBody="typedef A Asn1SInt"} - + C ::= SEQUENCE { -> {TypeDefinition.typedefName = "C"; typedefBody="typedef struct{ ... }"} - a1 INTEGER -> {ReferenceToExistingDefinition.programUnit="adaasn1rtl"; typedefName="Asn1Int"} + a1 INTEGER -> {ReferenceToExistingDefinition.programUnit="adaasn1rtl"; typedefName="Asn1Int"} a2 A -> {ReferenceToExistingDefinition.programUnit=None; typedefName="A"} //program unit is none since the type being referenced is in the same module as the referenced type a3 A(1..20) -> {TypeDefinition.typedefName = "C_a3"; typedefBody = "SUBTYPE C_a3 is A range 0..15"} } - - + + Type Assignment ? / \ No Yes --> New type definition with typedefname = Type Assignement Name - | + | (=> Composite Type Child) | | @@ -40,30 +40,30 @@ type TypeDefintionOrReference = Yes (Int,Real,Bool, Null) No (Octet, bit, IA5String, Enumerated, Sequence, Sequence Of, choice) | | (has extra range?) (Is reference Type with no extra constraint) - / \ / \ + / \ / \ / \ / \ Yes No Yes No | | | | New Subtype Reference to Reference to New Type - Definition with Existing Existing Definition with - typedef name = Definition Definition name = + Definition with Existing Existing Definition with + typedef name = Definition Definition name = parent type typedefName + child Name (The existing definition parent type typedefName + child Name and with base type the referneced type may be the base or base type in RTL definition in RTL or the base type if this is - a referenced type) + a referenced type) *) //let getPotentialTypedefName (r:AstRoot) (t:Asn1Type) (potentialTypedefName:string) = -// t.newTypeDefName - +// t.newTypeDefName + + + - - /// Called before visiting a choice or sequence or sequence of children diff --git a/BackendAst/DAstUPer.fs b/BackendAst/DAstUPer.fs index 6095601e0..f5e6cb669 100644 --- a/BackendAst/DAstUPer.fs +++ b/BackendAst/DAstUPer.fs @@ -22,56 +22,86 @@ let callBaseTypeFunc (lm:LanguageMacros) = lm.uper.call_base_type_func let sparkAnnotations (lm:LanguageMacros) = lm.uper.sparkAnnotations -let nestChildItems (lm:LanguageMacros) (codec:CommonTypes.Codec) children = +let nestChildItems (lm:LanguageMacros) (codec:CommonTypes.Codec) children = DAstUtilFunctions.nestItems lm.isvalid.JoinItems2 children +let adaptArgument (lm: LanguageMacros) (codec: CommonTypes.Codec) (p: CallerScope): string * string option = + // For Copy decoding kind, the return expression is the variable in which we save the decoding result + match codec with + | Encode -> lm.lg.getValue p.arg, None + | Decode -> + match lm.lg.decodingKind with + | InPlace -> lm.lg.getPointer p.arg, None + | Copy -> + let res = p.arg.asIdentifier + res, Some res + +let adaptArgumentPtr (lm: LanguageMacros) (codec: CommonTypes.Codec) (p: CallerScope): string * string option = + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let res = p.arg.asIdentifier + res, Some res + | _ -> lm.lg.getPointer p.arg, None + +let adaptArgumentValue (lm: LanguageMacros) (codec: CommonTypes.Codec) (p: CallerScope): string * string option = + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let res = p.arg.asIdentifier + res, Some res + | _ -> lm.lg.getValue p.arg, None + +let joinedOrAsIdentifier (lm: LanguageMacros) (codec: CommonTypes.Codec) (p: CallerScope) : string * string option = + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let resExpr = p.arg.asIdentifier + resExpr, Some resExpr + | _ -> p.arg.joined lm.lg, None //TODO -//1.Decode functions (and perhaps encode function) muct check if the decode value is within the constraints (currently, implemented only for Integers and for case IntUnconstraintMax ) +//1.Decode functions (and perhaps encode function) must check if the decode value is within the constraints (currently, implemented only for Integers and for case IntUnconstrainedMax ) //2.Fragmentation -let internal createUperFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (funcBody_e:ErroCode->CallerScope -> (UPERFuncBodyResult option)) soSparkAnnotations (us:State) = - let typeDef = lm.lg.getTypeDefinition t.FT_TypeDefintion - let funcName = getFuncName r lm codec t.id typeDef - let errCodeName = ToC ("ERR_UPER" + (codec.suffix.ToUpper()) + "_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) +let internal createUperFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (funcBody_e:ErrorCode->CallerScope -> (UPERFuncBodyResult option)) soSparkAnnotations (us:State) = + let typeDef = lm.lg.getTypeDefinition t.FT_TypeDefinition + let funcName = getFuncName r lm codec t.id typeDef + let errCodeName = ToC ("ERR_UPER" + (codec.suffix.ToUpper()) + "_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName None let soInitFuncName = getFuncNameGeneric typeDefinition (lm.init.methodNameSuffix()) let EmitTypeAssignment = lm.uper.EmitTypeAssignment let EmitTypeAssignment_def = lm.uper.EmitTypeAssignment_def - let EmitTypeAssignment_def_err_code = lm.uper.EmitTypeAssignment_def_err_code + let EmitTypeAssignment_def_err_code = lm.uper.EmitTypeAssignment_def_err_code let funcBody = (funcBody_e errCode) - let p = lm.lg.getParamType t codec - let topLevAcc = lm.lg.getAccess p.arg - let varName = p.arg.p + let p = lm.lg.getParamType t codec + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let isValidFuncName = match isValidFunc with None -> None | Some f -> f.funcName - let sInitilialExp = "" - let func, funcDef = + let sInitialExp = "" + let func, funcDef = match funcName with | None -> None, None - | Some funcName -> - let content = funcBody p - let bodyResult_funcBody, errCodes, bodyResult_localVariables, bBsIsUnreferenced, bVarNameIsUnreferenced = - match content with - | None -> - let emtyStatement = lm.lg.emtyStatement - emtyStatement, [], [], true, isValidFuncName.IsNone + | Some funcName -> + let content = funcBody p + let bodyResult_funcBody, errCodes, bodyResult_localVariables, bBsIsUnreferenced, bVarNameIsUnreferenced = + match content with + | None -> + let emptyStatement = lm.lg.emptyStatement + emptyStatement, [], [], true, isValidFuncName.IsNone | Some bodyResult -> bodyResult.funcBody, bodyResult.errCodes, bodyResult.localVariables, bodyResult.bBsIsUnReferenced, bodyResult.bValIsUnReferenced let lvars = bodyResult_localVariables |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct - let func = Some(EmitTypeAssignment varName sStar funcName isValidFuncName (lm.lg.getLongTypedefName typeDefinition) lvars bodyResult_funcBody soSparkAnnotations sInitilialExp (t.uperMaxSizeInBits = 0I) bBsIsUnreferenced bVarNameIsUnreferenced soInitFuncName codec) - + let func = Some(EmitTypeAssignment varName sStar funcName isValidFuncName (lm.lg.getLongTypedefName typeDefinition) lvars bodyResult_funcBody soSparkAnnotations sInitialExp (t.uperMaxSizeInBits = 0I) bBsIsUnreferenced bVarNameIsUnreferenced soInitFuncName codec) + //let errCodes = bodyResult.errCodes let errCodStr = errCodes |> List.map(fun x -> (EmitTypeAssignment_def_err_code x.errCodeName) (BigInteger x.errCodeValue)) let funcDef = Some(EmitTypeAssignment_def varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) errCodStr (t.uperMaxSizeInBits = 0I) (BigInteger (ceil ((double t.uperMaxSizeInBits)/8.0))) ( t.uperMaxSizeInBits) soSparkAnnotations (t.uperMaxSizeInBits = 0I) codec) func, funcDef - let ret = + let ret = { UPerFunction.funcName = funcName - func = func + func = func funcDef = funcDef funcBody = funcBody funcBody_e = funcBody_e @@ -80,7 +110,7 @@ let internal createUperFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (code let getIntDecFuncSuffix (intClass:Asn1AcnAst.IntegerClass) = match intClass with - | Asn1AcnAst.ASN1SCC_Int8 _ -> "Int8" + | Asn1AcnAst.ASN1SCC_Int8 _ -> "Int8" | Asn1AcnAst.ASN1SCC_Int16 _ -> "Int16" | Asn1AcnAst.ASN1SCC_Int32 _ -> "Int32" | Asn1AcnAst.ASN1SCC_Int64 _ -> "" @@ -92,8 +122,8 @@ let getIntDecFuncSuffix (intClass:Asn1AcnAst.IntegerClass) = | Asn1AcnAst.ASN1SCC_UInt _ -> "" let castPp (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) codec pp (intClass:Asn1AcnAst.IntegerClass) encFuncBits = - match codec with - | CommonTypes.Encode -> + match codec with + | CommonTypes.Encode -> match intClass with | Asn1AcnAst.ASN1SCC_Int8 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_Integer())) | Asn1AcnAst.ASN1SCC_Int16 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_Integer())) @@ -101,46 +131,46 @@ let castPp (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) codec pp (intClass:Asn1Acn | Asn1AcnAst.ASN1SCC_Int32 _ -> if encFuncBits = 32 && r.args.integerSizeInBytes = 4I then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_Integer())) | Asn1AcnAst.ASN1SCC_Int64 _ -> if encFuncBits = 64 then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_Integer())) | Asn1AcnAst.ASN1SCC_Int _ -> pp - | Asn1AcnAst.ASN1SCC_UInt8 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) - | Asn1AcnAst.ASN1SCC_UInt16 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) -// | Asn1AcnAst.ASN1SCC_UInt32 _ when r.args.integerSizeInBytes <> 4I -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) - | Asn1AcnAst.ASN1SCC_UInt32 _ -> if encFuncBits = 32 && r.args.integerSizeInBytes = 4I then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) - | Asn1AcnAst.ASN1SCC_UInt64 _ -> if encFuncBits = 64 then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) + | Asn1AcnAst.ASN1SCC_UInt8 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) + | Asn1AcnAst.ASN1SCC_UInt16 _ -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) +// | Asn1AcnAst.ASN1SCC_UInt32 _ when r.args.integerSizeInBytes <> 4I -> (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) + | Asn1AcnAst.ASN1SCC_UInt32 _ -> if encFuncBits = 32 && r.args.integerSizeInBytes = 4I then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) + | Asn1AcnAst.ASN1SCC_UInt64 _ -> if encFuncBits = 64 then pp else (lm.lg.castExpression pp (lm.typeDef.Declare_PosInteger())) | Asn1AcnAst.ASN1SCC_UInt _ -> pp | CommonTypes.Decode -> pp -let getIntfuncBodyByCons (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (uperRange:BigIntegerUperRange) errLoc (intClass:Asn1AcnAst.IntegerClass) (cons: IntegerTypeConstraint list) (allCons: IntegerTypeConstraint list) (errCode:ErroCode) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg +let getIntfuncBodyByCons (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (uperRange:BigIntegerUperRange) errLoc (intClass:Asn1AcnAst.IntegerClass) (cons: IntegerTypeConstraint list) (allCons: IntegerTypeConstraint list) (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p - let IntNoneRequired = lm.uper.IntNoneRequired - let IntFullyConstraintPos = lm.uper.IntFullyConstraintPos - let IntFullyConstraint = lm.uper.IntFullyConstraint - let IntSemiConstraintPos = lm.uper.IntSemiConstraintPos - let IntSemiConstraint = lm.uper.IntSemiConstraint - let IntUnconstraint = lm.uper.IntUnconstraint - let IntUnconstraintMax = lm.uper.IntUnconstraintMax - let IntRootExt = lm.uper.IntRootExt - let IntRootExt2 = lm.uper.IntRootExt2 - let rootCons = cons |> List.choose(fun x -> match x with RangeRootConstraint(_, a) |RangeRootConstraint2(_, a,_) -> Some(x) |_ -> None) + let IntNoneRequired = lm.uper.IntNoneRequired + let IntFullyConstraintPos = lm.uper.IntFullyConstraintPos + let IntFullyConstraint = lm.uper.IntFullyConstraint + let IntSemiConstraintPos = lm.uper.IntSemiConstraintPos + let IntSemiConstraint = lm.uper.IntSemiConstraint + let IntUnconstrained = lm.uper.IntUnconstrained + let IntUnconstrainedMax = lm.uper.IntUnconstrainedMax + let IntRootExt = lm.uper.IntRootExt + let IntRootExt2 = lm.uper.IntRootExt2 + let rootCons = cons |> List.choose(fun x -> match x with RangeRootConstraint(_, a) |RangeRootConstraint2(_, a,_) -> Some(x) |_ -> None) - let checkExp = + let checkExp = //match (DastValidate2.createIntegerFunctionByCons r l isUnsigned allCons) with //| None -> None //| Some expFunc -> Some (expFunc p) None - let sSsuffix = getIntDecFuncSuffix intClass + let suffix = getIntDecFuncSuffix intClass let castPp encFuncBits = castPp r lm codec pp intClass encFuncBits let IntBod uperRange extCon = match uperRange with | Concrete(min, max) when min=max -> IntNoneRequired (lm.lg.getValue p.arg) min errCode.errCodeName codec, codec=Decode, true - | Concrete(min, max) when intClass.IsPositive && (not extCon) -> IntFullyConstraintPos (castPp ((int r.args.integerSizeInBytes)*8)) min max (GetNumberOfBitsForNonNegativeInteger (max-min)) sSsuffix errCode.errCodeName codec, false, false - | Concrete(min, max) -> IntFullyConstraint (castPp ((int r.args.integerSizeInBytes)*8)) min max (GetNumberOfBitsForNonNegativeInteger (max-min)) sSsuffix errCode.errCodeName codec, false, false + | Concrete(min, max) when intClass.IsPositive && (not extCon) -> IntFullyConstraintPos (castPp ((int r.args.integerSizeInBytes)*8)) min max (GetNumberOfBitsForNonNegativeInteger (max-min)) suffix errCode.errCodeName codec, false, false + | Concrete(min, max) -> IntFullyConstraint (castPp ((int r.args.integerSizeInBytes)*8)) min max (GetNumberOfBitsForNonNegativeInteger (max-min)) suffix errCode.errCodeName codec, false, false | PosInf(a) when a>=0I && (not extCon) -> IntSemiConstraintPos pp a errCode.errCodeName codec, false, false | PosInf(a) -> IntSemiConstraint pp a errCode.errCodeName codec, false, false - | NegInf(max) -> IntUnconstraintMax pp max checkExp errCode.errCodeName codec, false, false - | Full -> IntUnconstraint pp errCode.errCodeName false codec, false, false + | NegInf(max) -> IntUnconstrainedMax pp max checkExp errCode.errCodeName codec, false, false + | Full -> IntUnconstrained pp errCode.errCodeName false codec, false, false let getValueByConstraint uperRange = match uperRange with @@ -148,51 +178,51 @@ let getIntfuncBodyByCons (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Commo | PosInf(a) -> a | NegInf(b) -> b | Full -> 0I - let funcBodyContent, bValIsUnReferenced, bBsIsUnReferenced = + let funcBodyContent, bValIsUnReferenced, bBsIsUnReferenced = match rootCons with | [] -> IntBod uperRange false - | (RangeRootConstraint (_, a))::rest -> + | (RangeRootConstraint (_, a))::rest -> let uperR = uPER.getIntTypeConstraintUperRange [a] errLoc let cc,_ = DastValidate2.integerConstraint2ValidationCodeBlock r lm intClass a 0 - let cc = DastValidate2.ValidationBlockAsStringExpr (cc p) + let cc = DastValidate2.ValidationBlockAsStringExpr (cc p) //let cc = DAstValidate.foldRangeCon l (fun v -> v.ToString()) (fun v -> v.ToString()) p a let rootBody, _,_ = IntBod uperR true IntRootExt pp (getValueByConstraint uperR) cc rootBody errCode.errCodeName codec, false, false - | (RangeRootConstraint2(_,a,_))::rest -> + | (RangeRootConstraint2(_,a,_))::rest -> let uperR = uPER.getIntTypeConstraintUperRange [a] errLoc //let cc = DAstValidate.foldRangeCon l (fun v -> v.ToString()) (fun v -> v.ToString()) p a let cc,_ = DastValidate2.integerConstraint2ValidationCodeBlock r lm intClass a 0 - let cc = DastValidate2.ValidationBlockAsStringExpr (cc p) + let cc = DastValidate2.ValidationBlockAsStringExpr (cc p) let rootBody, _,_ = IntBod uperR true - IntRootExt2 pp (getValueByConstraint uperR) cc rootBody errCode.errCodeName codec, false, false + IntRootExt2 pp (getValueByConstraint uperR) cc rootBody errCode.errCodeName codec, false, false | _ -> raise(BugErrorException "") - Some({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=bValIsUnReferenced; bBsIsUnReferenced=bBsIsUnReferenced}) - + Some({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=bValIsUnReferenced; bBsIsUnReferenced=bBsIsUnReferenced; resultExpr=resultExpr}) + -let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = +let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = getIntfuncBodyByCons r lm codec o.uperRange t.Location (o.intClass) o.cons o.AllCons errCode p let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> funcBody e p) soSparkAnnotations us -let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = +let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p let Boolean = lm.uper.Boolean let funcBodyContent = Boolean pp errCode.errCodeName codec - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) - + createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us let castRPp = DAstEqual.castRPp -let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = +let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = let sSuffix = match o.getClass r.args with | ASN1SCC_REAL -> "" @@ -200,25 +230,25 @@ let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonT | ASN1SCC_FP64 -> "" - let funcBody (errCode:ErroCode) (p:CallerScope) = - let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg - let castPp = castRPp lm codec (o.getClass r.args) pp + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgument lm codec p + let castPp = castRPp lm codec (o.getClass r.args) pp let Real = lm.uper.Real let funcBodyContent = Real castPp sSuffix errCode.errCodeName codec - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - let pp = lm.lg.getPointer p.arg - let ObjectIdentifier = +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgumentPtr lm codec p + let ObjectIdentifier = if o.relativeObjectId then lm.uper.RelativeOID else lm.uper.ObjectIdentifier let funcBodyContent = ObjectIdentifier pp errCode.errCodeName codec - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us @@ -233,41 +263,41 @@ let getTimeSubTypeByClass (tc) = |Asn1Date_LocalTimeWithTimeZone _ -> "Asn1DateTimeWithTimeZone" -let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - let pp = lm.lg.getPointer p.arg +let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let pp, resultExpr = adaptArgumentPtr lm codec p let TimeType = lm.uper.Time let funcBodyContent = TimeType pp (getTimeSubTypeByClass o.timeClass) errCode.errCodeName codec - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us - - -let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = None +let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let pp, _ = adaptArgument lm codec p + match codec, lm.lg.decodingKind with + | Decode, Copy -> + Some ({UPERFuncBodyResult.funcBody = lm.uper.Null_declare pp; errCodes = []; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=Some pp}) + | _ -> None let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc funcBody soSparkAnnotations us - -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - //let pp = match codec with CommonTypes.Encode -> p.arg.getValue l | CommonTypes.Decode -> p.arg.getPointer l +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = let Enumerated = lm.uper.Enumerated let Enumerated_item = lm.uper.Enumerated_item - let typeDef0 = lm.lg.getEnmTypeDefintion o.typeDef + let typeDef0 = lm.lg.getEnumTypeDefinition o.typeDef let td = typeDef0.longTypedefName2 lm.lg.hasModules (ToC p.modName) - //let typeDefinitionName = typeDefinition.longTypedefName l //getTypeDefinitionName t.id.tasInfo typeDefinition + let pp, resultExpr = adaptArgumentValue lm codec p let nMin = 0I let nMax = BigInteger(Seq.length o.items) - 1I let nLastItemIndex = nMax - let items = - o.items |> List.mapi(fun i itm -> Enumerated_item (lm.lg.getValue p.arg) (lm.lg.getNamedItemBackendName (Some typeDefinition) itm) (BigInteger i) nLastItemIndex codec) + let items = + o.items |> List.mapi(fun i itm -> Enumerated_item pp (lm.lg.getNamedItemBackendName (Some typeDefinition) itm) (BigInteger i) nLastItemIndex codec) let nBits = (GetNumberOfBitsForNonNegativeInteger (nMax-nMin)) let sFirstItemName = lm.lg.getNamedItemBackendName (Some typeDefinition) o.items.Head - //o.items.Head.getBackendName (Some typeDefinition) l - let funcBodyContent = Enumerated (lm.lg.getValue p.arg) td items nMin nMax nBits errCode.errCodeName nLastItemIndex sFirstItemName codec - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + let funcBodyContent = Enumerated pp td items nMin nMax nBits errCode.errCodeName nLastItemIndex sFirstItemName codec + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us @@ -302,11 +332,11 @@ let FragmentationParts (size:BigInteger) = { nBlocks64K = nBlocks64K; has48KBlock = has48KBlock; has32KBlock = has32KBlock; has16KBlock = has16KBlock; nRemainingItemsVar = nRemainingItemsVar} -let handleFixedSizeFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:CommonTypes.Codec) (errCode:ErroCode) ii uperMaxSizeInBits (fixSize:BigInteger) internalItem_funcBody nIntItemMaxSize bIsBitStringType bIsAsciiString= +let handleFixedSizeFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:CommonTypes.Codec) (errCode:ErrorCode) ii uperMaxSizeInBits (fixSize:BigInteger) internalItem_funcBody nIntItemMaxSize bIsBitStringType bIsAsciiString= let fixedSize_Fragmentation_sqf_64K = lm.uper.FixedSize_Fragmentation_sqf_64K let fixedSize_Fragmentation_sqf_small_block = lm.uper.FixedSize_Fragmentation_sqf_small_block let fixedSize_Fragmentation_sqf_remaining = lm.uper.FixedSize_Fragmentation_sqf_remaining - let fixedSize_Fragmentation_sqf = lm.uper.FixedSize_Fragmentation_sqf + let fixedSize_Fragmentation_sqf = lm.uper.FixedSize_Fragmentation_sqf let sRemainingItemsVar = sprintf "%s%d" "nRemainingItemsVar" ii let sCurBlockSize = sprintf "%s%d" "nCurBlockSize" ii let sBlockIndex = sprintf "%s%d" "nBlockIndex" ii @@ -316,19 +346,19 @@ let handleFixedSizeFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:Comm let r = FragmentationParts fixSize //let nBlocks64K = fixSize / C64K let parts = - let part = fixedSize_Fragmentation_sqf_64K p.arg.p (lm.lg.getAccess p.arg) sCurOffset sCurBlockSize sBlockIndex r.nBlocks64K internalItem_funcBody sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec + let part = fixedSize_Fragmentation_sqf_64K (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) sCurOffset sCurBlockSize sBlockIndex r.nBlocks64K internalItem_funcBody sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec [part] - let smallBlockParts = + let smallBlockParts = [(r.has48KBlock, lm.lg.toHex 195, C48K);(r.has32KBlock, lm.lg.toHex 194, C32K);(r.has16KBlock, lm.lg.toHex 193, C16K)] |> //0xC3, 0xC2, 0xC1 List.filter (fun (a,_,_) -> a) |> - List.map (fun (_, sBlockId, nBlockSize) -> fixedSize_Fragmentation_sqf_small_block p.arg.p (lm.lg.getAccess p.arg) internalItem_funcBody nBlockSize sBlockId sCurOffset sCurBlockSize sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec) + List.map (fun (_, sBlockId, nBlockSize) -> fixedSize_Fragmentation_sqf_small_block (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) internalItem_funcBody nBlockSize sBlockId sCurOffset sCurBlockSize sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec) let parts = parts@smallBlockParts let bRemainingItemsWithinByte = r.nRemainingItemsVar <= C_127 let parts= match r.nRemainingItemsVar > 0I with | true -> - let part = fixedSize_Fragmentation_sqf_remaining p.arg.p (lm.lg.getAccess p.arg) internalItem_funcBody bRemainingItemsWithinByte r.nRemainingItemsVar sCurOffset sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec + let part = fixedSize_Fragmentation_sqf_remaining (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) internalItem_funcBody bRemainingItemsWithinByte r.nRemainingItemsVar sCurOffset sBLI sRemainingItemsVar bIsBitStringType errCode.errCodeName codec parts@[part] | false -> parts @@ -340,9 +370,9 @@ let handleFixedSizeFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:Comm let fragmentationVars = fragmentationVars |> List.addIf (lm.lg.uper.requires_sBlockIndex) (createLv sBlockIndex) //let fragmentationVars = fragmentationVars |> List.addIf (l = C) (lv) let singleNestedPart = nestChildItems lm codec parts |> Option.toList - fixedSize_Fragmentation_sqf p.arg.p (lm.lg.getAccess p.arg) singleNestedPart fixSize bIsAsciiString codec, fragmentationVars + fixedSize_Fragmentation_sqf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) singleNestedPart fixSize bIsAsciiString codec, fragmentationVars -let handleFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:CommonTypes.Codec) (errCode:ErroCode) ii uperMaxSizeInBits (minSize:BigInteger) (maxSize:BigInteger) internalItem_funcBody nIntItemMaxSize bIsBitStringType bIsAsciiString= +let handleFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:CommonTypes.Codec) (errCode:ErrorCode) ii uperMaxSizeInBits (minSize:BigInteger) (maxSize:BigInteger) internalItem_funcBody nIntItemMaxSize bIsBitStringType bIsAsciiString= match minSize = maxSize with | true -> handleFixedSizeFragmentation lm p codec errCode ii uperMaxSizeInBits minSize internalItem_funcBody nIntItemMaxSize bIsBitStringType bIsAsciiString @@ -364,10 +394,10 @@ let handleFragmentation (lm:LanguageMacros) (p:CallerScope) (codec:CommonTypes.C let fragmentationVars = fragmentationVars |> List.addIf (codec = Encode && lm.lg.uper.requires_sBLJ) (createLv sBLJ) let fragmentationVars = fragmentationVars |> List.addIf (codec = Encode) (createLv sBlockIndex) let fragmentationVars = fragmentationVars |> List.addIf (codec = Decode && minSize <> maxSize) (createLv sLengthTmp) - fragmentation p.arg.p (lm.lg.getAccess p.arg) internalItem_funcBody nIntItemMaxSize ( minSize) ( maxSize) uperMaxSizeInBits (minSize <> maxSize) errCode.errCodeName sRemainingItemsVar sCurBlockSize sBlockIndex sCurOffset sBLJ sBLI sLengthTmp bIsBitStringType bIsAsciiString codec, fragmentationVars + fragmentation (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) internalItem_funcBody nIntItemMaxSize ( minSize) ( maxSize) uperMaxSizeInBits (minSize <> maxSize) errCode.errCodeName sRemainingItemsVar sCurBlockSize sBlockIndex sCurOffset sBLJ sBLI sLengthTmp bIsBitStringType bIsAsciiString codec, fragmentationVars -let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let ii = t.id.SeqeuenceOfLevel + 1 +let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii let lv = SequenceOfIndex (ii, None) let charIndex = @@ -378,53 +408,63 @@ let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Co match o.minSize.uper = o.maxSize.uper with | true -> [] | false -> [lm.lg.uper.createLv "nStringLength"] - let funcBody (errCode:ErroCode) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = let td0 = lm.lg.getStrTypeDefinition o.typeDef let td = td0.longTypedefName2 lm.lg.hasModules (ToC p.modName) let InternalItem_string_no_alpha = lm.uper.InternalItem_string_no_alpha let InternalItem_string_with_alpha = lm.uper.InternalItem_string_with_alpha let str_FixedSize = lm.uper.str_FixedSize let str_VarSize = lm.uper.str_VarSize - let typeDefinitionName = lm.lg.getLongTypedefName typeDefinition//getTypeDefinitionName t.id.tasInfo typeDefinition + let typeDefinitionName = lm.lg.getLongTypedefName typeDefinition let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (o.uperCharSet.Length-1)) let internalItem = match o.uperCharSet.Length = 128 with - | true -> InternalItem_string_no_alpha p.arg.p errCode.errCodeName i codec - | false -> + | true -> InternalItem_string_no_alpha (p.arg.joined lm.lg) errCode.errCodeName i codec + | false -> let nBits = GetNumberOfBitsForNonNegativeInteger (BigInteger (o.uperCharSet.Length-1)) let arrAsciiCodes = o.uperCharSet |> Array.map(fun x -> BigInteger (System.Convert.ToInt32 x)) - InternalItem_string_with_alpha p.arg.p errCode.errCodeName td i (BigInteger (o.uperCharSet.Length-1)) arrAsciiCodes (BigInteger (o.uperCharSet.Length)) nBits codec + InternalItem_string_with_alpha (p.arg.joined lm.lg) errCode.errCodeName td i (BigInteger (o.uperCharSet.Length-1)) arrAsciiCodes (BigInteger (o.uperCharSet.Length)) nBits codec let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.uper - o.minSize.uper)) - let funcBodyContent,localVariables = + let initExpr = + match codec, lm.lg.decodingKind with + | Decode, Copy -> Some (lm.lg.initializeString (int o.maxSize.uper)) + | _ -> None + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let funcBodyContent,localVariables = match o.minSize with - | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> str_FixedSize p.arg.p typeDefinitionName i internalItem ( o.minSize.uper) nBits nBits 0I codec , lv::charIndex@nStringLength - | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> str_VarSize p.arg.p typeDefinitionName i internalItem ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits nBits nBits 0I codec , lv::charIndex@nStringLength - | _ -> - let funcBodyContent,localVariables = handleFragmentation lm p codec errCode ii ( o.uperMaxSizeInBits) o.minSize.uper o.maxSize.uper internalItem nBits false true - let localVariables = localVariables |> List.addIf (lm.lg.uper.requires_IA5String_i || o.maxSize.uper<>o.minSize.uper) (lv) + | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> + str_FixedSize pp typeDefinitionName i internalItem o.minSize.uper nBits nBits 0I initExpr codec, lv::charIndex@nStringLength + | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> + str_VarSize pp typeDefinitionName i internalItem o.minSize.uper o.maxSize.uper nSizeInBits nBits nBits 0I initExpr codec, lv::charIndex@nStringLength + | _ -> + let funcBodyContent,localVariables = handleFragmentation lm p codec errCode ii o.uperMaxSizeInBits o.minSize.uper o.maxSize.uper internalItem nBits false true + let localVariables = localVariables |> List.addIf (lm.lg.uper.requires_IA5String_i || o.maxSize.uper<>o.minSize.uper) lv funcBodyContent, charIndex@localVariables - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} + let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us -let createOctetStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = - let ii = id.SeqeuenceOfLevel + 1; +let createOctetStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = + let ii = id.SequenceOfLevel + 1; let i = sprintf "i%d" ii - let lv = SequenceOfIndex (id.SeqeuenceOfLevel + 1, None) + let lv = SequenceOfIndex (id.SequenceOfLevel + 1, None) - let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules //getTypeDefinitionName t.id.tasInfo typeDefinition + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg let InternalItem_oct_str = lm.uper.InternalItem_oct_str - let fixedSize = lm.uper.octect_FixedSize - let varSize = lm.uper.octect_VarSize + let fixedSize = lm.uper.octet_FixedSize + let varSize = lm.uper.octet_VarSize let nIntItemMaxSize = 8I - let internalItem = InternalItem_oct_str p.arg.p (lm.lg.getAccess p.arg) i errCode.errCodeName codec + let internalItem = InternalItem_oct_str pp access i errCode.errCodeName codec let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (maxSize - minSize)) - let funcBodyContent, localVariables = + let funcBodyContent, localVariables = let nStringLength = match isFixedSize, codec with | true , _ -> [] @@ -432,21 +472,21 @@ let createOctetStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros | false, Decode -> [lm.lg.uper.count_var] match minSize with - | _ when maxSize < 65536I && isFixedSize -> fixedSize p.arg.p (lm.lg.getAccess p.arg) minSize codec , (if false then lv::nStringLength else nStringLength) - | _ when maxSize < 65536I && (not isFixedSize) -> varSize p.arg.p (lm.lg.getAccess p.arg) (minSize) ( maxSize) nSizeInBits errCode.errCodeName codec , (if false then lv::nStringLength else nStringLength) - | _ -> - let funcBodyContent,localVariables = handleFragmentation lm p codec errCode ii ( uperMaxSizeInBits) minSize maxSize internalItem nIntItemMaxSize false false + | _ when maxSize < 65536I && isFixedSize -> fixedSize td pp access minSize codec, (if false then lv::nStringLength else nStringLength) + | _ when maxSize < 65536I && (not isFixedSize) -> varSize td pp access minSize maxSize nSizeInBits errCode.errCodeName codec, (if false then lv::nStringLength else nStringLength) + | _ -> + let funcBodyContent,localVariables = handleFragmentation lm p codec errCode ii uperMaxSizeInBits minSize maxSize internalItem nIntItemMaxSize false false let localVariables = localVariables |> List.addIf (lm.lg.uper.requires_IA5String_i || (not isFixedSize)) (lv) funcBodyContent, localVariables - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - createOctetStringFunction_funcBody r lm codec t.id typeDefinition o.isFixedSize o.uperMaxSizeInBits o.minSize.uper o.maxSize.uper (errCode:ErroCode) (p:CallerScope) + let funcBody (errCode:ErrorCode) (p:CallerScope) = + createOctetStringFunction_funcBody r lm codec t.id typeDefinition o.isFixedSize o.uperMaxSizeInBits o.minSize.uper o.maxSize.uper (errCode:ErrorCode) (p:CallerScope) let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us @@ -454,61 +494,68 @@ let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec: (* -let createBitStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = +let createBitStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = lm.lg.uper.createBitStringFunction (handleFragmentation lm) codec id typeDefinition isFixedSize uperMaxSizeInBits minSize maxSize errCode p *) -let createBitStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = +let createBitStringFunction_funcBody (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = let bitString_FixSize = lm.uper.bitString_FixSize let bitString_VarSize = lm.uper.bitString_VarSize - let ii = id.SeqeuenceOfLevel + 1; - let i = sprintf "i%d" (id.SeqeuenceOfLevel + 1) + let ii = id.SequenceOfLevel + 1; + let i = sprintf "i%d" (id.SequenceOfLevel + 1) let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (maxSize - minSize)) - let internalItem = lm.uper.InternalItem_bit_str p.arg.p i errCode.errCodeName codec - let iVar = SequenceOfIndex (id.SeqeuenceOfLevel + 1, None) + let internalItem = lm.uper.InternalItem_bit_str (p.arg.joined lm.lg) i errCode.errCodeName codec + let iVar = SequenceOfIndex (id.SequenceOfLevel + 1, None) + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg - let funcBodyContent, localVariables = + let funcBodyContent, localVariables = let nStringLength = match isFixedSize, codec with | true , _ -> [] | false, Encode -> [] | false, Decode -> [lm.lg.uper.count_var] - + match minSize with - | _ when maxSize < 65536I && isFixedSize -> bitString_FixSize p.arg.p (lm.lg.getAccess p.arg) (minSize) errCode.errCodeName codec , nStringLength - | _ when maxSize < 65536I && (not isFixedSize) -> bitString_VarSize p.arg.p (lm.lg.getAccess p.arg) (minSize) (maxSize) errCode.errCodeName nSizeInBits codec, nStringLength - | _ -> + | _ when maxSize < 65536I && isFixedSize -> bitString_FixSize td pp access minSize errCode.errCodeName codec, nStringLength + | _ when maxSize < 65536I && (not isFixedSize) -> bitString_VarSize td pp access minSize maxSize errCode.errCodeName nSizeInBits codec, nStringLength + | _ -> let funcBodyContent, fragmentationLvars = handleFragmentation lm p codec errCode ii uperMaxSizeInBits minSize maxSize internalItem 1I true false let fragmentationLvars = fragmentationLvars |> List.addIf ((not isFixedSize) && lm.lg.uper.requires_sBLJ) (iVar) (funcBodyContent,fragmentationLvars) - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (us:State) = - let funcBody (errCode:ErroCode) (p:CallerScope) = - createBitStringFunction_funcBody r lm codec t.id typeDefinition o.isFixedSize o.uperMaxSizeInBits o.minSize.uper o.maxSize.uper (errCode:ErroCode) (p:CallerScope) + let funcBody (errCode:ErrorCode) (p:CallerScope) = + createBitStringFunction_funcBody r lm codec t.id typeDefinition o.isFixedSize o.uperMaxSizeInBits o.minSize.uper o.maxSize.uper (errCode:ErrorCode) (p:CallerScope) let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc (fun e p -> Some (funcBody e p)) soSparkAnnotations us -//let get - -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = let fixedSize = lm.uper.seqOf_FixedSize let varSize = lm.uper.seqOf_VarSize - let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules //getTypeDefinitionName t.id.tasInfo typeDefinition + let td = typeDefinition.longTypedefName2 lm.lg.hasModules let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (o.maxSize.uper - o.minSize.uper)) let nIntItemMaxSize = ( child.uperMaxSizeInBits) - let baseFuncName = match baseTypeUperFunc with None -> None | Some baseFunc -> baseFunc.funcName - let funcBody (errCode:ErroCode) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = + match baseFuncName with | None -> - let ii = t.id.SeqeuenceOfLevel + 1 + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg + // `childInitExpr` is used to initialize the array of elements in which we will write their decoded values + // It is only meaningful for "Copy" decoding kind, since InPlace will directly modify `p`'s array + let childInitExpr = DAstInitialize.getChildExpression lm child + + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii let lv = lm.lg.uper.seqof_lv t.id o.minSize.uper o.maxSize.uper @@ -518,116 +565,146 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:C | false, Encode -> [] | false, Decode -> [lm.lg.uper.count_var] - let chFunc = child.getUperFunction codec - let internalItem = + let internalItem = chFunc.funcBody ({p with arg = lm.lg.getArrayItem p.arg i child.isIA5String}) - - match internalItem with - | None -> - match o.minSize with - | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> None - | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> - let funcBody = varSize p.arg.p (lm.lg.getAccess p.arg) typeDefinitionName i "" ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits ( child.uperMinSizeInBits) nIntItemMaxSize 0I errCode.errCodeName codec - Some ({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = lv@nStringLength; bValIsUnReferenced=false; bBsIsUnReferenced=false}) - | _ -> - let funcBody, localVariables = handleFragmentation lm p codec errCode ii ( o.uperMaxSizeInBits) o.minSize.uper o.maxSize.uper "" nIntItemMaxSize false false - Some ({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false}) - | Some internalItem -> + | None -> + match o.minSize with + | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> None + | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> + let funcBody = varSize pp access td i "" ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits ( child.uperMinSizeInBits) nIntItemMaxSize 0I childInitExpr errCode.errCodeName codec + Some ({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = lv@nStringLength; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) + | _ -> + let funcBody, localVariables = handleFragmentation lm p codec errCode ii ( o.uperMaxSizeInBits) o.minSize.uper o.maxSize.uper "" nIntItemMaxSize false false + Some ({UPERFuncBodyResult.funcBody = funcBody; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) + | Some internalItem -> let childErrCodes = internalItem.errCodes - let ret,localVariables = + let ret,localVariables = match o.minSize with - | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> fixedSize p.arg.p typeDefinitionName i internalItem.funcBody ( o.minSize.uper) ( child.uperMinSizeInBits) nIntItemMaxSize 0I codec, nStringLength - | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> varSize p.arg.p (lm.lg.getAccess p.arg) typeDefinitionName i internalItem.funcBody ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits ( child.uperMinSizeInBits) nIntItemMaxSize 0I errCode.errCodeName codec , nStringLength + | _ when o.maxSize.uper < 65536I && o.maxSize.uper=o.minSize.uper -> fixedSize pp td i internalItem.funcBody ( o.minSize.uper) ( child.uperMinSizeInBits) nIntItemMaxSize 0I childInitExpr codec, nStringLength + | _ when o.maxSize.uper < 65536I && o.maxSize.uper<>o.minSize.uper -> varSize pp access td i internalItem.funcBody ( o.minSize.uper) ( o.maxSize.uper) nSizeInBits ( child.uperMinSizeInBits) nIntItemMaxSize 0I childInitExpr errCode.errCodeName codec , nStringLength | _ -> handleFragmentation lm p codec errCode ii ( o.uperMaxSizeInBits) o.minSize.uper o.maxSize.uper internalItem.funcBody nIntItemMaxSize false false - Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childErrCodes; localVariables = lv@(localVariables@internalItem.localVariables); bValIsUnReferenced=false; bBsIsUnReferenced=false}) + Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childErrCodes; localVariables = lv@(localVariables@internalItem.localVariables); bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) | Some baseFuncName -> - let funcBodyContent = callBaseTypeFunc lm (lm.lg.getPointer p.arg) baseFuncName codec - Some ({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false}) + let pp, resultExpr = adaptArgumentPtr lm codec p + let funcBodyContent = callBaseTypeFunc lm pp baseFuncName codec + Some ({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc funcBody soSparkAnnotations us +type private SequenceChildStmt = { + body: string option + lvs: LocalVariable list + errCodes: ErrorCode list +} +type private SequenceChildResult = { + presenceBit: string option + stmt: SequenceChildStmt option + resultExpr: string option +} - -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (us:State) = +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (us:State) = // stg macros let sequence_presence_bit = lm.uper.sequence_presence_bit let sequence_presence_bit_fix = lm.uper.sequence_presence_bit_fix let sequence_mandatory_child = lm.uper.sequence_mandatory_child let sequence_optional_child = lm.uper.sequence_optional_child let sequence_default_child = lm.uper.sequence_default_child - //let baseFuncName = match baseTypeUperFunc with None -> None | Some baseFunc -> baseFunc.funcName - - let funcBody (errCode:ErroCode) (p:CallerScope) = -// match baseFuncName with -// | None -> - let nonAcnChildren = children |> List.choose(fun c -> match c with Asn1Child c -> Some c | AcnChild _ -> None) - let localVariables = - match nonAcnChildren |> Seq.exists(fun x -> x.Optionality.IsSome) with - | true when lm.lg.uper.requires_presenceBit && codec = CommonTypes.Decode -> [(FlagLocalVariable ("presenceBit", None))] - | _ -> [] - let printPresenceBit (child:Asn1Child) = - match ST.lang with - | ProgrammingLanguage.Scala -> + let sequence_build = lm.uper.sequence_build + + let td = typeDefinition.longTypedefName2 lm.lg.hasModules + + let funcBody (errCode:ErrorCode) (p:CallerScope) = + let nonAcnChildren = children |> List.choose(fun c -> match c with Asn1Child c -> Some c | AcnChild _ -> None) + let localVariables = + match nonAcnChildren |> Seq.exists(fun x -> x.Optionality.IsSome) with + | true when codec = CommonTypes.Decode && lm.lg.uper.requires_presenceBit -> [(FlagLocalVariable ("presenceBit", None))] + | _ -> [] + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let access = lm.lg.getAccess p.arg + + let handleChild (child:Asn1Child): SequenceChildResult = + let childName = lm.lg.getAsn1ChildBackendName child + let childTypeDef = child.Type.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules + let chFunc = child.Type.getUperFunction codec + let newArg = lm.lg.getSeqChild p.arg childName child.Type.isIA5String child.Optionality.IsSome + let newArg = if lm.lg.usesWrappedOptional && newArg.isOptional && codec = Encode then newArg.asLast else newArg + let childP = {p with arg = newArg} + let childContentResult = chFunc.funcBody childP + let existVar = + match codec, lm.lg.decodingKind with + | Decode, Copy -> Some (ToC (child._c_name + "_exist")) + | _ -> None + let presenceBit = + let absent, present = + match ST.lang with + | Scala -> "false", "true" + | _ -> "0", "1" + // please note that in decode, macro uper_sequence_presence_bit_fix + // calls macro uper_sequence_presence_bit (i.e. behaves like optional) + let seq_presence_bit_fix (value: string) = + sequence_presence_bit_fix pp access childName existVar errCode.errCodeName value codec + match child.Optionality with + | None -> None + | Some Asn1AcnAst.AlwaysAbsent -> Some (seq_presence_bit_fix absent) + | Some Asn1AcnAst.AlwaysPresent -> Some (seq_presence_bit_fix present) + | Some (Asn1AcnAst.Optional opt) -> Some (sequence_presence_bit pp access childName existVar errCode.errCodeName codec) + + match childContentResult with + | None -> + // Copy-decoding expects to have a result expression (even if unused), so we pick the initExpression + let childResultExpr = + match codec, lm.lg.decodingKind with + | Decode, Copy -> Some child.Type.initFunction.initExpression + | _ -> None + {presenceBit=presenceBit; stmt=None; resultExpr=childResultExpr} + | Some childContent -> + let childBody, child_localVariables = match child.Optionality with - | None -> None - | Some Asn1AcnAst.AlwaysAbsent -> Some (sequence_presence_bit_fix p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName "false" codec) // please note that in decode, macro uper_sequence_presence_bit_fix - | Some Asn1AcnAst.AlwaysPresent -> Some (sequence_presence_bit_fix p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName "true" codec) // calls macro uper_sequence_presence_bit (i.e. behaves like optional) - | Some (Asn1AcnAst.Optional opt) -> Some (sequence_presence_bit p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName codec) - | _ -> - match child.Optionality with - | None -> None - | Some Asn1AcnAst.AlwaysAbsent -> Some (sequence_presence_bit_fix p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName "0" codec) // please note that in decode, macro uper_sequence_presence_bit_fix - | Some Asn1AcnAst.AlwaysPresent -> Some (sequence_presence_bit_fix p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName "1" codec) // calls macro uper_sequence_presence_bit (i.e. behaves like optional) - | Some (Asn1AcnAst.Optional opt) -> Some (sequence_presence_bit p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) errCode.errCodeName codec) - let handleChild (child:Asn1Child) = - let chFunc = child.Type.getUperFunction codec - let ch_arg = lm.lg.getSeqChild p.arg - let childContentResult = chFunc.funcBody ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) - match childContentResult with - | None -> None - | Some childContent -> - let childBody, child_localVariables = - match child.Optionality with - | None -> Some (sequence_mandatory_child (lm.lg.getAsn1ChildBackendName child) childContent.funcBody codec) , childContent.localVariables - | Some Asn1AcnAst.AlwaysAbsent -> - match codec with - | CommonTypes.Encode -> None, [] - | CommonTypes.Decode -> Some (sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody codec) , childContent.localVariables - | Some Asn1AcnAst.AlwaysPresent -> - match codec with - | CommonTypes.Encode -> Some childContent.funcBody, childContent.localVariables - | CommonTypes.Decode -> Some (sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody codec), childContent.localVariables - | Some (Asn1AcnAst.Optional opt) -> - match opt.defaultValue with - | None -> Some (sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody codec), childContent.localVariables - | Some v -> - let defInit= child.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) (mapValue v).kind - Some (sequence_default_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody defInit codec), childContent.localVariables - Some (childBody, child_localVariables, childContent.errCodes) - - let presenseBits = nonAcnChildren |> List.choose printPresenceBit - let childrenStatements0 = nonAcnChildren |> List.choose handleChild - let childrenStatements = childrenStatements0 |> List.choose(fun (s,_,_) -> s) - let childrenLocalvars = childrenStatements0 |> List.collect(fun (_,s,_) -> s) - let childrenErrCodes = childrenStatements0 |> List.collect(fun (_,_,s) -> s) - let seqContent = (presenseBits@childrenStatements) |> nestChildItems lm codec - match seqContent with - | None -> None - | Some ret -> Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced=false; bBsIsUnReferenced=(o.uperMaxSizeInBits = 0I)}) -// | Some baseFuncName -> -// let funcBodyContent = callBaseTypeFunc l (p.arg.getPointer l) baseFuncName codec -// Some ({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []}) - + | None -> Some (sequence_mandatory_child childName childContent.funcBody codec) , childContent.localVariables + | Some Asn1AcnAst.AlwaysAbsent -> + match codec with + | CommonTypes.Encode -> None, [] + | CommonTypes.Decode -> Some (sequence_optional_child pp access childName childContent.funcBody existVar childContent.resultExpr childTypeDef codec), childContent.localVariables + | Some Asn1AcnAst.AlwaysPresent -> + if lm.lg.usesWrappedOptional then + Some (sequence_optional_child pp access childName childContent.funcBody existVar childContent.resultExpr childTypeDef codec), childContent.localVariables + else + match codec with + | CommonTypes.Encode -> Some childContent.funcBody, childContent.localVariables + | CommonTypes.Decode -> Some (sequence_optional_child pp access childName childContent.funcBody existVar childContent.resultExpr childTypeDef codec), childContent.localVariables + | Some (Asn1AcnAst.Optional opt) -> + match opt.defaultValue with + | None -> Some (sequence_optional_child pp access childName childContent.funcBody existVar childContent.resultExpr childTypeDef codec), childContent.localVariables + | Some v -> + let defInit= child.Type.initFunction.initByAsn1Value childP (mapValue v).kind + Some (sequence_default_child pp access childName childContent.funcBody existVar childContent.resultExpr childTypeDef defInit codec), childContent.localVariables + {presenceBit=presenceBit; stmt=Some {body=childBody; lvs=child_localVariables; errCodes=childContent.errCodes}; resultExpr=childContent.resultExpr} + + let childrenStatements00 = nonAcnChildren |> List.map handleChild + let presenceBits = childrenStatements00 |> List.choose (fun s -> s.presenceBit) + let childrenStatements0 = childrenStatements00 |> List.choose(fun s -> s.stmt) + let childrenStatements = childrenStatements0 |> List.choose(fun s -> s.body) + let childrenLocalVars = childrenStatements0 |> List.collect(fun s -> s.lvs) + let childrenErrCodes = childrenStatements0 |> List.collect(fun s -> s.errCodes) + let childrenResultExpr = childrenStatements00 |> List.choose(fun s -> s.resultExpr) + // If we are Decoding with Copy decoding kind, then all children `resultExpr` must be defined as well (i.e. we must have the same number of `resultExpr` as children) + assert (resultExpr.IsNone || childrenResultExpr.Length = nonAcnChildren.Length) + let seqBuild = resultExpr |> Option.map (fun res -> sequence_build res td childrenResultExpr) |> Option.toList + let seqContent = (presenceBits@childrenStatements@seqBuild) |> nestChildItems lm codec + match seqContent with + | None -> None + | Some ret -> Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalVars; bValIsUnReferenced=false; bBsIsUnReferenced=(o.uperMaxSizeInBits = 0I); resultExpr=resultExpr}) + let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition None isValidFunc funcBody soSparkAnnotations us -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (us:State) = +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (baseTypeUperFunc : UPerFunction option) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (us:State) = // stg macros let choice_child = lm.uper.choice_child let choice = lm.uper.choice @@ -639,124 +716,112 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Commo | CommonTypes.Encode -> [] | CommonTypes.Decode -> [(Asn1SIntLocalVariable (sChoiceIndexName, None))] - let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules //getTypeDefinitionName t.id.tasInfo typeDefinition + let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules - let funcBody (errCode:ErroCode) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = let td0 = lm.lg.getChoiceTypeDefinition o.typeDef let td = td0.longTypedefName2 lm.lg.hasModules (ToC p.modName) + + let handleChild (nIndexSizeInBits: BigInteger) (i: int) (child: ChChildInfo): string * LocalVariable list * ErrorCode list = + let chFunc = child.chType.getUperFunction codec + let uperChildRes = + match lm.lg.uper.catd with + | false -> chFunc.funcBody ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) + | true when codec = CommonTypes.Decode -> chFunc.funcBody ({p with arg = Selection.valueEmptyPath ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) + | true -> chFunc.funcBody ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) + let sChildName = (lm.lg.getAsn1ChChildBackendName child) + let sChildTypeDef = child.chType.typeDefinitionOrReference.longTypedefName2 lm.lg.hasModules + let isSequence = isSequenceForJVMelseFalse child.chType.Kind + let isEnum = isEnumForJVMelseFalse child.chType.Kind + let sChildInitExpr = child.chType.initFunction.initExpression + let sChoiceTypeName = typeDefinitionName + + let mk_choice_child (childContent: string): string = + choice_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some typeDefinition) child) (BigInteger i) nIndexSizeInBits (BigInteger (children.Length - 1)) childContent sChildName sChildTypeDef sChoiceTypeName sChildInitExpr isSequence isEnum codec + + match uperChildRes with + | None -> + let childContent = + match lm.lg.uper.catd with + | false -> lm.lg.createSingleLineComment "no encoding/decoding is required" + | true when codec=Decode -> + let childp = ({p with arg = Selection.valueEmptyPath ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) + match child.chType.ActualType.Kind with + | NullType _ -> uper_a.decode_nullType childp.arg.receiverId + | Sequence _ -> uper_a.decode_empty_sequence_emptySeq childp.arg.receiverId + | _ -> lm.lg.createSingleLineComment "no encoding/decoding is required" + | true -> lm.lg.createSingleLineComment "no encoding/decoding is required" + mk_choice_child childContent, [], [] + | Some childContent -> + mk_choice_child childContent.funcBody, childContent.localVariables, childContent.errCodes + match baseFuncName with | None -> let nIndexSizeInBits = (GetNumberOfBitsForNonNegativeInteger (BigInteger (children.Length - 1))) - let childrenContent3 = - children |> - List.mapi(fun i child -> - let chFunc = child.chType.getUperFunction codec - let uperChildRes = - match lm.lg.uper.catd with - | false -> chFunc.funcBody ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) - | true when codec = CommonTypes.Decode -> chFunc.funcBody ({p with arg = VALUE ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) - | true -> chFunc.funcBody ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) - let sChildName = (lm.lg.getAsn1ChChildBackendName child) - let sChildTypeDef = child.chType.typeDefintionOrReference.longTypedefName2 lm.lg.hasModules //child.chType.typeDefinition.typeDefinitionBodyWithinSeq - let isSequence = isSequenceForJVMelseFalse child.chType.Kind - let isEnum = isEnumForJVMelseFalse child.chType.Kind - let isOctetString = isOctetStringForJVMelseFalse child.chType.Kind - let sChildInitExpr = child.chType.initFunction.initExpression - let exprMethodCall = - match ST.lang with - | Scala -> - match isSequence || sChildInitExpr.Equals("null") || isEnum || isOctetString with - | true -> "" - | false -> scalaInitMethSuffix child.chType.Kind - | _ -> "" - let sChoiceTypeName = typeDefinitionName - match uperChildRes with - | None -> - let childContent = - match lm.lg.uper.catd with - | false -> lm.lg.createSingleLineComment "no encoding/decoding is required" - | true when codec=Decode -> - let childp = ({p with arg = VALUE ((lm.lg.getAsn1ChChildBackendName child) + "_tmp")}) - match child.chType.ActualType.Kind with - | NullType _ -> uper_a.decode_nullType childp.arg.p - | Sequence _ -> uper_a.decode_empty_sequence_emptySeq childp.arg.p - | _ -> lm.lg.createSingleLineComment "no encoding/decoding is required" - | true -> lm.lg.createSingleLineComment "no encoding/decoding is required" - choice_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some typeDefinition) child) (BigInteger i) nIndexSizeInBits (BigInteger (children.Length - 1)) childContent sChildName sChildTypeDef sChoiceTypeName (sChildInitExpr + exprMethodCall) isSequence isEnum codec, [], [] - | Some childContent -> - choice_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some typeDefinition) child) (BigInteger i) nIndexSizeInBits (BigInteger (children.Length - 1)) childContent.funcBody sChildName sChildTypeDef sChoiceTypeName (sChildInitExpr + exprMethodCall) isSequence isEnum codec, childContent.localVariables, childContent.errCodes ) + let childrenContent3 = children |> List.mapi (handleChild nIndexSizeInBits) let childrenContent = childrenContent3 |> List.map(fun (s,_,_) -> s) let childrenLocalvars = childrenContent3 |> List.collect(fun (_,s,_) -> s) let childrenErrCodes = childrenContent3 |> List.collect(fun (_,_,s) -> s) - - let ret = choice p.arg.p (lm.lg.getAccess p.arg) childrenContent (BigInteger (children.Length - 1)) sChoiceIndexName errCode.errCodeName td nIndexSizeInBits codec - Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced=false; bBsIsUnReferenced=false}) + let pp, resultExpr = joinedOrAsIdentifier lm codec p + let ret = choice pp (lm.lg.getAccess p.arg) childrenContent (BigInteger (children.Length - 1)) sChoiceIndexName errCode.errCodeName td nIndexSizeInBits codec + Some ({UPERFuncBodyResult.funcBody = ret; errCodes = errCode::childrenErrCodes; localVariables = localVariables@childrenLocalvars; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) | Some baseFuncName -> - let funcBodyContent = callBaseTypeFunc lm (lm.lg.getPointer p.arg) baseFuncName codec - Some ({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false}) + let pp, resultExpr = adaptArgumentPtr lm codec p + let funcBodyContent = callBaseTypeFunc lm pp baseFuncName codec + Some ({UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr}) let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) createUperFunction r lm codec t typeDefinition baseTypeUperFunc isValidFunc funcBody soSparkAnnotations us - - (* -let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeId :ReferenceToType) (td:FE_TypeDefinition) = -match typeId.tasInfo with -| None -> None -| Some _ -> Some (td.typeName + codec.suffix) - - *) - -let createReferenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = -(* - let moduleName, typeDefinitionName0 = - let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let typeDef = lm.lg.getTypeDefinition t1.FT_TypeDefintion - typeDef.programUnit, typeDef.typeName - let baseTypeDefinitionName = - match lm.lg.hasModules with - | false -> typeDefinitionName0 - | true -> - match t.id.ModName = o.modName.Value with - | true -> typeDefinitionName0 - | false -> moduleName + "." + typeDefinitionName0 - let baseFncName = baseTypeDefinitionName + codec.suffix -*) - +let createReferenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = let baseTypeDefinitionName, baseFncName = getBaseFuncName lm typeDefinition o t.id "" codec - match o.encodingOptions with - | None -> + match o.encodingOptions with + | None -> let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let t1WithExtensios = o.resolvedType; - match TypesEquivalence.uperEquivalence t1 t1WithExtensios with + let t1WithExtensions = o.resolvedType; + match TypesEquivalence.uperEquivalence t1 t1WithExtensions with | true -> let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) - let funcBody (errCode:ErroCode) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = match (baseType.getUperFunction codec).funcBody p with - | Some _ -> - let funcBodyContent = callBaseTypeFunc lm (lm.lg.getParamValue t p.arg codec) baseFncName codec - Some {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + | Some _ -> + let pp, resultExpr = + let str = lm.lg.getParamValue t p.arg codec + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let toc = ToC str + toc, Some toc + | _ -> str, None + let funcBodyContent = callBaseTypeFunc lm pp baseFncName codec + Some {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false ; resultExpr=resultExpr} | None -> None - createUperFunction r lm codec t typeDefinition None isValidFunc funcBody soSparkAnnotations us - | false -> + createUperFunction r lm codec t typeDefinition None isValidFunc funcBody soSparkAnnotations us + | false -> baseType.getUperFunction codec, us - | Some opts -> + | Some opts -> let octet_string_containing_func = lm.uper.octet_string_containing_func let bit_string_containing_func = lm.uper.bit_string_containing_func let soSparkAnnotations = Some(sparkAnnotations lm (lm.lg.getLongTypedefName typeDefinition) codec) - let funcBody (errCode:ErroCode) (p:CallerScope) = + let funcBody (errCode:ErrorCode) (p:CallerScope) = match (baseType.getUperFunction codec).funcBody p with - | Some _ -> + | Some _ -> + let pp, resultExpr = + let str = lm.lg.getParamValue t p.arg codec + match codec, lm.lg.decodingKind with + | Decode, Copy -> + let toc = ToC str + toc, Some toc + | _ -> str, None let nBits = GetNumberOfBitsForNonNegativeInteger (opts.maxSize.uper - opts.minSize.uper) let sReqBytesForUperEncoding = sprintf "%s_REQUIRED_BYTES_FOR_ENCODING" baseTypeDefinitionName let sReqBitForUperEncoding = sprintf "%s_REQUIRED_BITS_FOR_ENCODING" baseTypeDefinitionName - let funcBodyContent = + let funcBodyContent = match opts.octOrBitStr with - | ContainedInOctString -> octet_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding nBits opts.minSize.uper opts.maxSize.uper codec - | ContainedInBitString -> bit_string_containing_func (lm.lg.getParamValue t p.arg codec) baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding nBits opts.minSize.uper opts.maxSize.uper codec - Some {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false} + | ContainedInOctString -> octet_string_containing_func pp baseFncName sReqBytesForUperEncoding nBits opts.minSize.uper opts.maxSize.uper codec + | ContainedInBitString -> bit_string_containing_func pp baseFncName sReqBytesForUperEncoding sReqBitForUperEncoding nBits opts.minSize.uper opts.maxSize.uper codec + Some {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = []; bValIsUnReferenced=false; bBsIsUnReferenced=false; resultExpr=resultExpr} | None -> None createUperFunction r lm codec t typeDefinition None isValidFunc funcBody soSparkAnnotations us - + diff --git a/BackendAst/DAstUtilFunctions.fs b/BackendAst/DAstUtilFunctions.fs index 43f6ad761..5459a1d30 100644 --- a/BackendAst/DAstUtilFunctions.fs +++ b/BackendAst/DAstUtilFunctions.fs @@ -10,78 +10,80 @@ open DAst open Language let getAccessFromScopeNodeList (ReferenceToType nodes) (childTypeIsString: bool) (lm:LanguageMacros) (pVal : CallerScope) = - let handleNode zeroBasedSeqeuenceOfLevel (pVal : CallerScope) (n:ScopeNode) (childTypeIsString: bool) = + let handleNode zeroBasedSequenceOfLevel (pVal : CallerScope) (n:ScopeNode) (childTypeIsString: bool) = match n with | MD _ | TA _ | PRM _ | VA _ -> raise(BugErrorException "getAccessFromScopeNodeList") - | SEQ_CHILD chName -> [], {pVal with arg = lm.lg.getSeqChild pVal.arg (ToC chName) childTypeIsString false} - | CH_CHILD (chName,pre_name, chParent) -> + | SEQ_CHILD (chName, chOpt) -> [], {pVal with arg = lm.lg.getSeqChild pVal.arg (ToC chName) childTypeIsString chOpt} + | CH_CHILD (chName,pre_name, chParent) -> let chChildIsPresent = match ST.lang with - | Scala -> sprintf "%s.isInstanceOf[%s.%s_PRESENT]" pVal.arg.p chParent pre_name - | _ -> sprintf "%s%skind %s %s_PRESENT" pVal.arg.p (lm.lg.getAccess pVal.arg) lm.lg.eqOp pre_name + | Scala -> sprintf "%s.isInstanceOf[%s.%s_PRESENT]" (pVal.arg.joined lm.lg) chParent pre_name + | _ -> sprintf "%s%skind %s %s_PRESENT" (pVal.arg.joined lm.lg) (lm.lg.getAccess pVal.arg) lm.lg.eqOp pre_name [chChildIsPresent], {pVal with arg = lm.lg.getChChild pVal.arg (ToC chName) childTypeIsString} - | SQF -> - let curIdx = sprintf "i%d" (zeroBasedSeqeuenceOfLevel + 1) - + | SQF -> + let curIdx = sprintf "i%d" (zeroBasedSequenceOfLevel + 1) [], {pVal with arg = lm.lg.getArrayItem pVal.arg curIdx childTypeIsString} match nodes with - | (MD md)::(TA tas)::(PRM prm)::[] -> ({CallerScope.modName = pVal.modName; arg = VALUE (ToC (md + "_" + tas + "_" + prm))}, []) + | (MD md)::(TA tas)::(PRM prm)::[] -> ({CallerScope.modName = pVal.modName; arg = Selection.valueEmptyPath (ToC (md + "_" + tas + "_" + prm))}, []) | (MD md)::(TA tas):: xs -> let length = Seq.length xs - let ret = - xs |> - List.fold(fun (curPath, curCheckExp, zeroBasedSeqeuenceOfLevel, idx) n -> - let chekPath, newPath = handleNode zeroBasedSeqeuenceOfLevel curPath n (childTypeIsString && idx=length) - let zeroBasedSeqeuenceOfLevel = match n with SQF -> zeroBasedSeqeuenceOfLevel + 1 | _ -> zeroBasedSeqeuenceOfLevel - (newPath, chekPath@curCheckExp, zeroBasedSeqeuenceOfLevel, idx+1)) (pVal,[], 0, 1) |> (fun (a,chekPath,_,_) -> a, chekPath) - ret + let ret = + xs |> + List.fold(fun (curPath, curCheckExp, zeroBasedSequenceOfLevel, idx) n -> + let checkPath, newPath = handleNode zeroBasedSequenceOfLevel curPath n (childTypeIsString && idx=length) + let zeroBasedSequenceOfLevel = match n with SQF -> zeroBasedSequenceOfLevel + 1 | _ -> zeroBasedSequenceOfLevel + (newPath, checkPath@curCheckExp, zeroBasedSequenceOfLevel, idx+1)) (pVal,[], 0, 1) |> (fun (a,checkPath,_,_) -> a, checkPath) + ret | _ -> raise(BugErrorException "getAccessFromScopeNodeList") -let extractEnumClassName (prefix: String)(varName: String)(internalName: String): String = +let extractEnumClassName (prefix: String)(varName: String)(internalName: String): String = match ST.lang with | Scala -> prefix + varName.Substring(0, max 0 (varName.Length - (internalName.Length + 1))) // TODO: check case where max is needed | _ -> "" -let rec extractDefaultInitValue (childType: Asn1TypeKind): String = - match childType with - | Integer i -> i.baseInfo.defaultInitVal - | Real r -> r.baseInfo.defaultInitVal - | NullType n -> n.baseInfo.defaultInitVal - | Boolean b -> b.baseInfo.defaultInitVal - | ReferenceType rt -> extractDefaultInitValue rt.resolvedType.Kind - | _ -> "null" - -let extractACNDefaultInitValue (acnType: AcnInsertedType): String = - match acnType with - | AcnInteger i -> i.defaultValue - | AcnBoolean b -> b.defaultValue - | AcnNullType c -> c.defaultValue - | AcnReferenceToEnumerated e -> e.defaultValue - | AcnReferenceToIA5String s -> s.defaultValue - -let rec resolveReferenceType(t: Asn1TypeKind): Asn1TypeKind = +let rec extractDefaultInitValue (childType: Asn1TypeKind): String = + match childType with + | Integer i -> i.baseInfo.defaultInitVal + | Real r -> r.baseInfo.defaultInitVal + | NullType n -> n.baseInfo.defaultInitVal + | Boolean b -> b.baseInfo.defaultInitVal + | ReferenceType rt -> extractDefaultInitValue rt.resolvedType.Kind + | _ -> "null" + +let rec resolveReferenceType(t: Asn1TypeKind): Asn1TypeKind = match t with | ReferenceType rt -> resolveReferenceType rt.resolvedType.Kind | _ -> t -let isJVMPrimitive (t: Asn1TypeKind) = +let isJVMPrimitive (t: Asn1TypeKind) = match resolveReferenceType t with | Integer _ | Real _ | NullType _ | Boolean _ -> true | _ -> false - + +let defOrRef (r:Asn1AcnAst.AstRoot) (m: Asn1AcnAst.Asn1Module) (a:Asn1AcnAst.AcnReferenceToEnumerated) = + match m.Name.Value = a.modName.Value with + | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName.Value) ; definedInRtl = false} + | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName.Value); typedefName = ToC (r.args.TypePrefix + a.tasName.Value); definedInRtl = false} + +let defOrRef2 (r:Asn1AcnAst.AstRoot) (m: Asn1AcnAst.Asn1Module) (a:Asn1AcnAst.ReferenceToEnumerated) = + match m.Name.Value = a.modName with + | true -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = None; typedefName = ToC (r.args.TypePrefix + a.tasName); definedInRtl = false} + | false -> ReferenceToExistingDefinition {ReferenceToExistingDefinition.programUnit = Some (ToC a.modName); typedefName = ToC (r.args.TypePrefix + a.tasName) ; definedInRtl = false} + + let hasInitMethSuffix (initMethName: string) (suffix: string): bool = - initMethName.EndsWith(suffix) + initMethName.EndsWith(suffix) let isArrayInitialiser(initMethName: string): bool = initMethName.Contains("Array.fill(") let scalaInitMethSuffix (k: Asn1TypeKind) = match ST.lang with - | Scala -> + | Scala -> match isJVMPrimitive k with | false -> match k with @@ -98,8 +100,8 @@ let isEnumForJVMelseFalse (k: Asn1TypeKind): bool = | Enumerated e -> true | _ -> false | _ -> false - -let isSequenceForJVMelseFalse (k: Asn1TypeKind): bool = + +let isSequenceForJVMelseFalse (k: Asn1TypeKind): bool = match ST.lang with | Scala -> match k with @@ -107,14 +109,14 @@ let isSequenceForJVMelseFalse (k: Asn1TypeKind): bool = | _ -> false | _ -> false -let isOctetStringForJVMelseFalse (k: Asn1TypeKind): bool = +let isOctetStringForJVMelseFalse (k: Asn1TypeKind): bool = match ST.lang with | Scala -> match k with | OctetString s -> true | _ -> false | _ -> false - + type LocalVariable with member this.VarName = match this with @@ -128,7 +130,7 @@ type LocalVariable with | GenericLocalVariable lv -> lv.name -type TypeDefintionOrReference with +type TypeDefinitionOrReference with member this.longTypedefName2 bHasModules = match this with @@ -136,7 +138,7 @@ type TypeDefintionOrReference with td.typedefName | ReferenceToExistingDefinition ref -> match ref.programUnit with - | Some pu -> + | Some pu -> match bHasModules with | true -> pu + "." + ref.typedefName | false -> ref.typedefName @@ -145,9 +147,9 @@ type TypeDefintionOrReference with member this.longTypedefName (l:ProgrammingLanguage) = let b = (l = Ada) this.longTypedefName2 b - + member this.getAsn1Name (typePrefix : string) = - let typedefName = + let typedefName = match this with | TypeDefinition td -> td.typedefName | ReferenceToExistingDefinition ref -> ref.typedefName @@ -164,48 +166,48 @@ type Integer with member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons //member this.IsUnsigned = isUnsigned this.uperRange -type Enumerated with +type Enumerated with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type Real with +type Real with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type Boolean with +type Boolean with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type StringType with +type StringType with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type OctetString with +type OctetString with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type BitString with +type BitString with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type SequenceOf with +type SequenceOf with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type ObjectIdentifier with +type ObjectIdentifier with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons -type Sequence with +type Sequence with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons @@ -213,7 +215,7 @@ type Sequence with this.children |> List.choose(fun c -> match c with Asn1Child c -> Some c | AcnChild _ -> None) type Asn1Child with - member this.getBackendName l = + member this.getBackendName l = match l with | C -> this._c_name | Scala -> this._scala_name @@ -221,7 +223,7 @@ type Asn1Child with type ChChildInfo with - member this.getBackendName l = + member this.getBackendName l = match l with | C -> this._c_name | Scala -> this._scala_name @@ -229,11 +231,11 @@ type ChChildInfo with -type Choice with +type Choice with member this.Cons = this.baseInfo.cons member this.WithCons = this.baseInfo.withcons member this.AllCons = this.baseInfo.cons@this.baseInfo.withcons - + type ReferenceType with member ref.AsTypeAssignmentInfo = {TypeAssignmentInfo.modName = ref.baseInfo.modName.Value; tasName = ref.baseInfo.tasName.Value} @@ -245,7 +247,7 @@ type Asn1AcnAst.ChChildInfo with member this.presentWhenName = (ToC this.present_when_name) + "_PRESENT" type ChChildInfo with - member this.presentWhenName (defOrRef:TypeDefintionOrReference option) l = + member this.presentWhenName (defOrRef:TypeDefinitionOrReference option) l = match l with | C -> (ToC this._present_when_name_private) + "_PRESENT" | Scala -> (ToC this._present_when_name_private) + "_PRESENT" // TODO: Scala @@ -254,7 +256,7 @@ type ChChildInfo with | Some (ReferenceToExistingDefinition r) when r.programUnit.IsSome -> r.programUnit.Value + "." + ((ToC this._present_when_name_private) + "_PRESENT") | _ -> (ToC this._present_when_name_private) + "_PRESENT" - + type Asn1AcnAst.NamedItem with @@ -284,16 +286,16 @@ type Asn1AcnAst.Asn1Type with | Asn1AcnAst.TimeType _ ->TC_ReferenceToVariable(TC_COMPLEX, "val" + suf) | Asn1AcnAst.ReferenceType r -> r.resolvedType.getParameterExpr suf c - - + + type Asn1Type with member this.getActualType (r:AstRoot) = match this.Kind with - | ReferenceType t-> + | ReferenceType t-> let md = r.Files |> List.collect(fun f -> f.Modules) |> Seq.find(fun m -> m.Name.Value = t.baseInfo.modName.Value) //t.baseInfo.modName let ts = md.TypeAssignments |> Seq.find(fun ts -> ts.Name.Value = t.baseInfo.tasName.Value) //t.baseInfo.modName ts.Type.getActualType r @@ -310,7 +312,7 @@ with | Choice _ -> this | ObjectIdentifier _ -> this | TimeType _ -> this - + member this.isComplexType = match this.Kind with @@ -345,8 +347,8 @@ with | Choice _ -> this | ObjectIdentifier _ -> this | TimeType _ -> this - - member this.FT_TypeDefintion = + + member this.FT_TypeDefinition = match this.Kind with | Integer t -> t.baseInfo.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList | Real t -> t.baseInfo.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList @@ -361,8 +363,8 @@ with | SequenceOf t -> t.baseInfo.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList | Sequence t -> t.baseInfo.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_SequenceTypeDefinition d)) |> Map.ofList | Choice t -> t.baseInfo.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_ChoiceTypeDefinition d)) |> Map.ofList - | ReferenceType t-> t.baseInfo.typeDef - + | ReferenceType t-> t.baseInfo.typeDef + member this.printValue = match this.Kind with | Integer t -> t.printValue @@ -381,7 +383,7 @@ with | TimeType t -> t.printValue - member this.ConstraintsAsn1Str = + member this.ConstraintsAsn1Str = match this.Kind with | Integer t -> t.constraintsAsn1Str | Real t -> t.constraintsAsn1Str @@ -399,18 +401,6 @@ with | TimeType t -> t.constraintsAsn1Str - - - - - - - - - - - - member this.initFunction = match this.Kind with | Integer t -> t.initFunction @@ -461,7 +451,7 @@ with | Choice t -> t.isValidFunction | ReferenceType t-> t.isValidFunction | TimeType t -> t.isValidFunction - + member this.getUperFunction (l:CommonTypes.Codec) = match l with | CommonTypes.Encode -> this.uperEncFunction @@ -470,7 +460,7 @@ with match l with | CommonTypes.Encode -> this.xerEncFunction | CommonTypes.Decode -> this.xerDecFunction - + member this.uperEncFunction = match this.Kind with | Integer t ->t.uperEncFunction @@ -612,7 +602,7 @@ with member this.MappingFunctionsModules = match this.Kind with - | Sequence t -> + | Sequence t -> let ret1 = match t.baseInfo.acnProperties.postEncodingFunction, t.baseInfo.acnProperties.preDecodingFunction with | Some (AcnGenericTypes.PostEncodingFunction (a, _) ), Some (AcnGenericTypes.PreDecodingFunction (c, _)) -> [a;c] |> List.choose id |> List.map(fun z -> z.Value) @@ -626,7 +616,7 @@ with | Asn1Child _ -> None | AcnChild ancC -> match ancC.Type with - | AcnInteger a -> + | AcnInteger a -> match a.acnProperties.mappingFunction with | Some (AcnGenericTypes.MappingFunction (a, _)) -> a | None -> None @@ -634,7 +624,7 @@ with | _ -> None) |> List.map(fun z -> z.Value) ret1@ret2 - | Integer t -> + | Integer t -> match t.baseInfo.acnProperties.mappingFunction with | Some (AcnGenericTypes.MappingFunction (a, _)) -> [a] |> List.choose id |> List.map(fun z -> z.Value) | None -> [] @@ -651,22 +641,22 @@ with | ReferenceType ref -> ref.resolvedType.MappingFunctionsModules | TimeType _ -> [] - member this.icdFunction = + member this.icdFunction = match this.Kind with - | Integer t -> t.acnEncFunction.icd.Value - | Real t -> t.acnEncFunction.icd.Value - | IA5String t -> t.acnEncFunction.icd.Value - | OctetString t -> t.acnEncFunction.icd.Value - | NullType t -> t.acnEncFunction.icd.Value - | BitString t -> t.acnEncFunction.icd.Value - | Boolean t -> t.acnEncFunction.icd.Value - | Enumerated t -> t.acnEncFunction.icd.Value - | SequenceOf t -> t.acnEncFunction.icd.Value - | Sequence t -> t.acnEncFunction.icd.Value - | Choice t -> t.acnEncFunction.icd.Value - | ReferenceType t -> t.acnEncFunction.icd.Value - | ObjectIdentifier t -> t.acnEncFunction.icd.Value - | TimeType t -> t.acnEncFunction.icd.Value + | Integer t -> t.acnEncFunction.icd.Value + | Real t -> t.acnEncFunction.icd.Value + | IA5String t -> t.acnEncFunction.icd.Value + | OctetString t -> t.acnEncFunction.icd.Value + | NullType t -> t.acnEncFunction.icd.Value + | BitString t -> t.acnEncFunction.icd.Value + | Boolean t -> t.acnEncFunction.icd.Value + | Enumerated t -> t.acnEncFunction.icd.Value + | SequenceOf t -> t.acnEncFunction.icd.Value + | Sequence t -> t.acnEncFunction.icd.Value + | Choice t -> t.acnEncFunction.icd.Value + | ReferenceType t -> t.acnEncFunction.icd.Value + | ObjectIdentifier t -> t.acnEncFunction.icd.Value + | TimeType t -> t.acnEncFunction.icd.Value member this.acnEncFunction : AcnFunction option = match this.Kind with @@ -766,9 +756,9 @@ with | Asn1Encoding.ACN -> this.acnEncDecTestFunc | Asn1Encoding.XER -> this.xerEncDecTestFunc | Asn1Encoding.BER -> None - - - member this.typeDefintionOrReference : TypeDefintionOrReference = + + + member this.typeDefinitionOrReference : TypeDefinitionOrReference = match this.Kind with | Integer t -> t.definitionOrRef | Real t -> t.definitionOrRef @@ -791,7 +781,7 @@ with | ReferenceType r -> this.ActualType.isIA5String | _ -> false - member this.asn1Name = + member this.asn1Name = match this.id with | ReferenceToType((MD _)::(TA tasName)::[]) -> Some tasName | _ -> None @@ -814,7 +804,7 @@ with type Asn1Module with member this.ExportedTypes = match this.Exports with - | Asn1Ast.All -> + | Asn1Ast.All -> let importedTypes = this.Imports |> List.collect(fun imp -> imp.Types) |> List.map(fun x -> x.Value) (this.TypeAssignments |> List.map(fun x -> x.Name.Value))@importedTypes | Asn1Ast.OnlySome(typesAndVars) -> @@ -837,7 +827,7 @@ type AstRoot with | Some vas -> vas member r.Modules = r.Files |> List.collect(fun f -> f.Modules) - member r.getModuleByName (name:StringLoc) = + member r.getModuleByName (name:StringLoc) = let (n,loc) = name.AsTupple match r.Modules |> Seq.tryFind( fun m -> m.Name = name) with | Some(m) -> m @@ -848,7 +838,7 @@ type Asn1File with member this.FileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension this.FileName member this.TypeAssignments = this.Modules |> List.collect(fun m -> m.TypeAssignments) -let getValueByUperRange (r:uperRange<'T>) (z:'T) = +let getValueByUperRange (r:uperRange<'T>) (z:'T) = match r with | Concrete (a,b) -> if a <= z && z <= b then z else a | NegInf b -> if z <= b then z else b //(-inf, b] @@ -856,15 +846,15 @@ let getValueByUperRange (r:uperRange<'T>) (z:'T) = | Full -> z let rec mapValue (v:Asn1AcnAst.Asn1Value) = - let newVKind = + let newVKind = match v.kind with - | Asn1AcnAst.IntegerValue v -> IntegerValue v.Value - | Asn1AcnAst.RealValue v -> RealValue v.Value + | Asn1AcnAst.IntegerValue v -> IntegerValue v.Value + | Asn1AcnAst.RealValue v -> RealValue v.Value | Asn1AcnAst.StringValue v -> StringValue v - | Asn1AcnAst.BooleanValue v -> BooleanValue v.Value - | Asn1AcnAst.BitStringValue v -> BitStringValue v.Value + | Asn1AcnAst.BooleanValue v -> BooleanValue v.Value + | Asn1AcnAst.BitStringValue v -> BitStringValue v.Value | Asn1AcnAst.OctetStringValue v -> OctetStringValue (v |> List.map(fun z -> z.Value)) - | Asn1AcnAst.EnumValue v -> EnumValue v.Value + | Asn1AcnAst.EnumValue v -> EnumValue v.Value | Asn1AcnAst.SeqOfValue v -> SeqOfValue (v |> List.map mapValue) | Asn1AcnAst.SeqValue v -> SeqValue (v |> List.map (fun n -> {NamedValue.name = n.name.Value; Value = mapValue n.Value})) | Asn1AcnAst.ChValue n -> ChValue {NamedValue.name = n.name.Value; Value = mapValue n.Value} @@ -875,7 +865,7 @@ let rec mapValue (v:Asn1AcnAst.Asn1Value) = {Asn1Value.kind = newVKind; id=v.id; loc = v.loc;moduleName = v.moduleName} -let emitComponent (c:ResolvedObjectIdentifierValueCompoent) = +let emitComponent (c:ResolvedObjectIdentifierValueComponent) = match c with | ResObjInteger nVal -> (nVal.Value, None) | ResObjNamedDefValue (label,_,nVal) -> (nVal, Some label.Value) @@ -883,7 +873,7 @@ let emitComponent (c:ResolvedObjectIdentifierValueCompoent) = | ResObjRegisteredKeyword (label,nVal) -> (nVal, Some label.Value) | ResObjDefinedValue (_,_,nVal) -> (nVal, None) -type ObjectIdenfierValue with +type ObjectIdentifierValue with member this.Values = match this with | InternalObjectIdentifierValue intList -> intList |> List.map(fun i -> (i, None)) @@ -894,7 +884,7 @@ type Asn1Value with member this.getBackendName (l:ProgrammingLanguage) = match this.id with | ReferenceToValue (typePath,(VA2 vasName)::[]) -> ToC vasName - | ReferenceToValue (typePath, vasPath) -> + | ReferenceToValue (typePath, vasPath) -> let longName = (typePath.Tail |> List.map (fun i -> i.StrValue))@ (vasPath |> List.map (fun i -> i.StrValue)) |> Seq.StrJoin "_" ToC2(longName.Replace("#","elem").L1) @@ -918,7 +908,7 @@ type Asn1ValueKind with | _ -> this type SeqChildInfo with - member this.acnInsertetField = + member this.acnInsertedField = match this with | Asn1Child _ -> false | AcnChild _ -> true @@ -928,8 +918,8 @@ type SeqChildInfo with | Asn1Child x -> x.Name.Value | AcnChild x -> x.Name.Value member this.savePosition = - match this with - | AcnChild z -> + match this with + | AcnChild z -> match z.Type with | Asn1AcnAst.AcnNullType nt when nt.acnProperties.savePosition -> true | _ -> false @@ -960,18 +950,18 @@ let hasAcnEncodeFunction (encFunc : AcnFunction option) acnParameters = | Some fnc -> match acnParameters with | [] -> - let p = {CallerScope.modName = ""; arg = VALUE "dummy"} + let p = {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} let ret,_ = fnc.funcBody emptyState [] p match ret with | None -> false | Some _ -> true | _ -> false - + let hasUperEncodeFunction (encFunc : UPerFunction option) = match encFunc with | None -> false | Some fnc -> - let p = {CallerScope.modName = ""; arg = VALUE "dummy"} + let p = {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} match fnc.funcBody p with | None -> false | Some _ -> true @@ -980,9 +970,8 @@ let hasXerEncodeFunction (encFunc : XerFunction option) = match encFunc with | None -> false | Some (XerFunction fnc) -> - - let p = {CallerScope.modName = ""; arg = VALUE "dummy"} - let errCode = {ErroCode.errCodeName = "DUMMY_ERR"; errCodeValue=0; comment=None} + let p = {CallerScope.modName = ""; arg = Selection.valueEmptyPath "dummy"} + let errCode = {ErrorCode.errCodeName = "DUMMY_ERR"; errCodeValue=0; comment=None} match fnc.funcBody_e errCode p None with | None -> false | Some _ -> true @@ -997,104 +986,103 @@ let AdaUses (r:AstRoot) = yield sprintf "%s:%s" tas.Name.Value (ToC m.Name.Value); } |> Seq.iter(fun l -> System.Console.WriteLine l) -let rec GetMySelfAndChildren (t:Asn1Type) = +let rec GetMySelfAndChildren (t:Asn1Type) = seq { match t.Kind with | SequenceOf(conType) -> yield! GetMySelfAndChildren conType.childType | Sequence seq -> - for ch in seq.Asn1Children do + for ch in seq.Asn1Children do yield! GetMySelfAndChildren ch.Type - | Choice(ch)-> - for ch in ch.children do + | Choice(ch)-> + for ch in ch.children do yield! GetMySelfAndChildren ch.chType - |_ -> () + |_ -> () yield t } |> Seq.toList -let rec GetMySelfAndChildren2 (lm:Language.LanguageMacros) (t:Asn1Type) (p:CallerScope)= +let rec GetMySelfAndChildren2 (lm:Language.LanguageMacros) (t:Asn1Type) (p:CallerScope)= seq { match t.Kind with - | SequenceOf(conType) -> - let ii = t.id.SeqeuenceOfLevel + 1 + | SequenceOf(conType) -> + let ii = t.id.SequenceOfLevel + 1 let i = "0" //sprintf "i%d" ii - + yield! GetMySelfAndChildren2 lm conType.childType ({p with arg = lm.lg.getArrayItem p.arg i conType.childType.isIA5String}) | Sequence seq -> - for ch in seq.Asn1Children do - - yield! GetMySelfAndChildren2 lm ch.Type ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false}) - | Choice(ch)-> - for ch in ch.children do + for ch in seq.Asn1Children do + yield! GetMySelfAndChildren2 lm ch.Type ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String ch.Optionality.IsSome}) + | Choice(ch)-> + for ch in ch.children do yield! GetMySelfAndChildren2 lm ch.chType ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName ch) ch.chType.isIA5String}) - |_ -> () + |_ -> () yield (t,p) } |> Seq.toList -let rec GetMySelfAndChildren3 visitChildPredicate (t:Asn1Type) = +let rec GetMySelfAndChildren3 visitChildPredicate (t:Asn1Type) = seq { if visitChildPredicate t then match t.Kind with - | SequenceOf(conType) -> + | SequenceOf(conType) -> yield! GetMySelfAndChildren conType.childType | Sequence seq -> - for ch in seq.Asn1Children do + for ch in seq.Asn1Children do yield! GetMySelfAndChildren ch.Type - | Choice(ch)-> - for ch in ch.children do + | Choice(ch)-> + for ch in ch.children do yield! GetMySelfAndChildren ch.chType - |_ -> () + |_ -> () yield t } |> Seq.toList -let getFuncNameGeneric (typeDefinition:TypeDefintionOrReference) nameSuffix = +let getFuncNameGeneric (typeDefinition:TypeDefinitionOrReference) nameSuffix = match typeDefinition with | ReferenceToExistingDefinition refEx -> None | TypeDefinition td -> Some (td.typedefName + nameSuffix) -let getFuncNameGeneric2 (typeDefinition:TypeDefintionOrReference) = +let getFuncNameGeneric2 (typeDefinition:TypeDefinitionOrReference) = match typeDefinition with | ReferenceToExistingDefinition refEx -> None | TypeDefinition td -> Some (td.typedefName) -let nestItems joinItems2 children = - let printChild (content:string) (soNestedContent:string option) = +let nestItems joinItems2 children = + let printChild (content:string) (soNestedContent:string option) = match soNestedContent with | None -> content | Some sNestedContent -> joinItems2 content sNestedContent - let rec printChildren children : Option = + let rec printChildren children : Option = match children with |[] -> None |x::xs -> Some (printChild x (printChildren xs)) printChildren children -let nestItems_ret (lm:LanguageMacros) children = +let nestItems_ret (lm:LanguageMacros) children = nestItems lm.isvalid.JoinTwoIfFirstOk children -let getBaseFuncName (lm:LanguageMacros) (typeDefinition:TypeDefintionOrReference) (o:Asn1AcnAst.ReferenceType) (id:ReferenceToType) (methodSuffix:string) (codec:CommonTypes.Codec) = - let moduleName, typeDefinitionName0 = +let getBaseFuncName (lm:LanguageMacros) (typeDefinition:TypeDefinitionOrReference) (o:Asn1AcnAst.ReferenceType) (id:ReferenceToType) (methodSuffix:string) (codec:CommonTypes.Codec) = + let moduleName, typeDefinitionName0 = match typeDefinition with | ReferenceToExistingDefinition refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName | None -> ToC id.ModName, refToExist.typedefName - | TypeDefinition tdDef -> + | TypeDefinition tdDef -> match tdDef.baseType with | None -> ToC id.ModName, tdDef.typedefName - | Some refToExist -> + | Some refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName | None -> ToC id.ModName, refToExist.typedefName - let baseTypeDefinitionName = + let baseTypeDefinitionName = match lm.lg.hasModules with - | false -> typeDefinitionName0 - | true -> + | false -> typeDefinitionName0 + | true -> match id.ModName = o.modName.Value with - | true -> typeDefinitionName0 - | false -> moduleName + "." + typeDefinitionName0 + | true -> typeDefinitionName0 + | false -> moduleName + "." + typeDefinitionName0 baseTypeDefinitionName, baseTypeDefinitionName + methodSuffix + codec.suffix diff --git a/BackendAst/DAstValidate.fs b/BackendAst/DAstValidate.fs index 2e928c839..c85f0ad42 100644 --- a/BackendAst/DAstValidate.fs +++ b/BackendAst/DAstValidate.fs @@ -19,7 +19,7 @@ open DAstUtilFunctions // 1 single value constraints for composite types (SEQUENCE, SEQUENCE OF, CHOICE) by using the generated value and _equal function (like bit and octet strings) // 2 simpify constraints. For example the constrains of the following type // INT20 ::= INTEGER(-11..10 | 23 | 24)(1..20 EXCEPT 100) -// should be recalcualted as +// should be recalcualted as // uPerRange is 1..10 // so the following simplifications must be performed // INT20 ::= INTEGER(1..10)(1..10) @@ -34,7 +34,7 @@ let getFuncName (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (typeId:Reference let Lte (l:ProgrammingLanguage) eqIsInc e1 e2 = match eqIsInc with - | true -> l.ExpLte e1 e2 + | true -> l.ExpLte e1 e2 | false -> l.ExpLt e1 e2 let foldGenericCon (l:ProgrammingLanguage) valToStrFunc (p:CallerScope) (c:GenericConstraint<'v>) = @@ -50,7 +50,7 @@ let foldGenericCon (l:ProgrammingLanguage) valToStrFunc (p:CallerScope) (c:Gen 0 |> fst let foldRangeCon (l:ProgrammingLanguage) valToStrFunc1 valToStrFunc2 (p:CallerScope) (c:RangeTypeConstraint<'v1,'v2>) = - foldRangeTypeConstraint + foldRangeTypeConstraint (fun e1 e2 b s -> l.ExpOr e1 e2, s) (fun e1 e2 s -> l.ExpAnd e1 e2, s) (fun e s -> l.ExpNot e, s) @@ -58,7 +58,7 @@ let foldRangeCon (l:ProgrammingLanguage) valToStrFunc1 valToStrFunc2 (p:CallerSc (fun e s -> e, s) (fun e1 e2 s -> l.ExpOr e1 e2, s) (fun v s -> l.ExpEqual (p.arg.getValue l) (valToStrFunc2 v) ,s) - (fun v1 v2 minIsIn maxIsIn s -> + (fun v1 v2 minIsIn maxIsIn s -> l.ExpAnd (Lte l minIsIn (valToStrFunc1 v1) (p.arg.getValue l)) (Lte l maxIsIn (p.arg.getValue l) (valToStrFunc1 v2)), s) (fun v1 minIsIn s -> Lte l minIsIn (valToStrFunc1 v1) (p.arg.getValue l), s) (fun v2 maxIsIn s -> Lte l maxIsIn (p.arg.getValue l) (valToStrFunc1 v2), s) @@ -72,53 +72,53 @@ type SimplifiedIntegerConstraint<'a> = | SciConstraint of RangeTypeConstraint<'a, 'a> -let UintHandleEqual (r:Asn1AcnAst.AstRoot) zero v1 = +let UintHandleEqual (r:Asn1AcnAst.AstRoot) zero v1 = match v1 < zero with | true -> SicAlwaysTrue | false -> SciConstraint (RangeSingleValueConstraint v1) - -let SIntHandleEqual (r:Asn1AcnAst.AstRoot) v1 = + +let SIntHandleEqual (r:Asn1AcnAst.AstRoot) v1 = SciConstraint (RangeSingleValueConstraint v1) - + (* e.g. INTEGER (5..MAX) ==> intVal >= 5 *) -let UintHandleRangeContraint_val_MAX (r:Asn1AcnAst.AstRoot) zero eqIsInc v1 = +let UintHandleRangeConstraint_val_MAX (r:Asn1AcnAst.AstRoot) zero eqIsInc v1 = match v1 < zero with | true -> SicAlwaysTrue | false -> match eqIsInc with | true when v1 = zero -> SicAlwaysTrue - | true -> SciConstraint (RangeContraint_val_MAX (v1,eqIsInc)) - | false -> SciConstraint (RangeContraint_val_MAX (v1,eqIsInc)) + | true -> SciConstraint (RangeConstraint_val_MAX (v1,eqIsInc)) + | false -> SciConstraint (RangeConstraint_val_MAX (v1,eqIsInc)) -let SIntHandleRangeContraint_val_MAX (r:Asn1AcnAst.AstRoot) eqIsInc v1 = +let SIntHandleRangeConstraint_val_MAX (r:Asn1AcnAst.AstRoot) eqIsInc v1 = match eqIsInc with | true when v1 = r.args.SIntMin -> SicAlwaysTrue - | true -> SciConstraint (RangeContraint_val_MAX (v1,eqIsInc)) - | false -> SciConstraint (RangeContraint_val_MAX (v1,eqIsInc)) + | true -> SciConstraint (RangeConstraint_val_MAX (v1,eqIsInc)) + | false -> SciConstraint (RangeConstraint_val_MAX (v1,eqIsInc)) (* e.g INTEGER (MIN .. 40) --> intVal <= 40*) -let UintHandleRangeContraint_MIN_val (r:Asn1AcnAst.AstRoot) zero intMax eqIsInc v1 = +let UintHandleRangeConstraint_MIN_val (r:Asn1AcnAst.AstRoot) zero intMax eqIsInc v1 = match v1 < zero with | true -> SicAlwaysTrue | false -> match eqIsInc with | true when v1 = intMax && intMax <> zero -> SicAlwaysTrue - | true -> SciConstraint (RangeContraint_MIN_val (v1,eqIsInc)) - | false -> SciConstraint (RangeContraint_MIN_val (v1,eqIsInc)) + | true -> SciConstraint (RangeConstraint_MIN_val (v1,eqIsInc)) + | false -> SciConstraint (RangeConstraint_MIN_val (v1,eqIsInc)) -let SIntHandleRangeContraint_MIN_val (r:Asn1AcnAst.AstRoot) eqIsInc v1 = +let SIntHandleRangeConstraint_MIN_val (r:Asn1AcnAst.AstRoot) eqIsInc v1 = match eqIsInc with | true when v1 = r.args.SIntMax -> SicAlwaysTrue - | true -> SciConstraint (RangeContraint_MIN_val (v1,eqIsInc)) - | false -> SciConstraint (RangeContraint_MIN_val (v1,eqIsInc)) - -let simplifytIntegerTypeConstraint handleEqual handleRangeContraint_val_MAX handleRangeContraint_MIN_val (c:RangeTypeConstraint<'a, 'a>) = - let handleOr e1 e2 = + | true -> SciConstraint (RangeConstraint_MIN_val (v1,eqIsInc)) + | false -> SciConstraint (RangeConstraint_MIN_val (v1,eqIsInc)) + +let simplifytIntegerTypeConstraint handleEqual handleRangeConstraint_val_MAX handleRangeConstraint_MIN_val (c:RangeTypeConstraint<'a, 'a>) = + let handleOr e1 e2 = match e1, e2 with | SicAlwaysTrue, _ -> SicAlwaysTrue | _ , SicAlwaysTrue -> SicAlwaysTrue @@ -130,7 +130,7 @@ let simplifytIntegerTypeConstraint handleEqual handleRangeContraint_val_MAX hand | SciConstraint e1, SciConstraint e2 -> SciConstraint(RangeIntersectionConstraint (e1,e2)) let handleNot e = e - foldRangeTypeConstraint + foldRangeTypeConstraint (fun e1 e2 b s -> handleOr e1 e2, s) (fun e1 e2 s -> handleAnd e1 e2, s) (fun e s -> handleNot e, s) @@ -138,12 +138,12 @@ let simplifytIntegerTypeConstraint handleEqual handleRangeContraint_val_MAX hand (fun e s -> e, s) (fun e1 e2 s -> handleOr e1 e2, s) (fun v s -> handleEqual v ,s) - (fun v1 v2 minIsIn maxIsIn s -> - let exp1 = handleRangeContraint_val_MAX minIsIn v1 - let exp2 = handleRangeContraint_MIN_val maxIsIn v2 + (fun v1 v2 minIsIn maxIsIn s -> + let exp1 = handleRangeConstraint_val_MAX minIsIn v1 + let exp2 = handleRangeConstraint_MIN_val maxIsIn v2 handleAnd exp1 exp2, s) - (fun v1 minIsIn s -> handleRangeContraint_val_MAX minIsIn v1, s) - (fun v2 maxIsIn s -> handleRangeContraint_MIN_val maxIsIn v2, s) + (fun v1 minIsIn s -> handleRangeConstraint_val_MAX minIsIn v1, s) + (fun v2 maxIsIn s -> handleRangeConstraint_MIN_val maxIsIn v2, s) c 0 |> fst @@ -152,8 +152,8 @@ let simplifytIntegerTypeConstraint handleEqual handleRangeContraint_val_MAX hand // constraint simplification ended here -let foldSizeRangeTypeConstraint (l:ProgrammingLanguage) getSizeFunc (p:CallerScope) (c:PosIntTypeConstraint) = - foldRangeTypeConstraint +let foldSizeRangeTypeConstraint (l:ProgrammingLanguage) getSizeFunc (p:CallerScope) (c:PosIntTypeConstraint) = + foldRangeTypeConstraint (fun e1 e2 b s -> l.ExpOr e1 e2, s) (fun e1 e2 s -> l.ExpAnd e1 e2, s) (fun e s -> l.ExpNot e, s) @@ -161,12 +161,12 @@ let foldSizeRangeTypeConstraint (l:ProgrammingLanguage) getSizeFunc (p:CallerSc (fun e s -> e, s) (fun e1 e2 s -> l.ExpOr e1 e2, s) (fun v s -> l.ExpEqual (getSizeFunc l p) (v.ToString()) ,s) - (fun v1 v2 minIsIn maxIsIn s -> + (fun v1 v2 minIsIn maxIsIn s -> l.ExpAnd (Lte l minIsIn (v1.ToString()) (getSizeFunc l p)) (Lte l maxIsIn (getSizeFunc l p) (v2.ToString())), s) (fun v1 minIsIn s -> Lte l minIsIn (v1.ToString()) (getSizeFunc l p), s) (fun v2 maxIsIn s -> Lte l maxIsIn (getSizeFunc l p) (v2.ToString()), s) c - 0 + 0 let foldSizableConstraint (l:ProgrammingLanguage) compareSingValueFunc getSizeFunc (p:CallerScope) (c:SizableTypeConstraint<'v>) = @@ -198,11 +198,11 @@ let foldStringCon (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) alphaFuncName ( (fun e s -> e, s) (fun e1 e2 s -> l.ExpOr e1 e2, s) (fun v s -> l.ExpStringEqual p.arg.p v.IDQ ,s) - (fun intCon s -> - let aaa = [intCon] |> List.map (fun c -> simplifytIntegerTypeConstraint (UintHandleEqual r 0u) (UintHandleRangeContraint_val_MAX r 0u) (UintHandleRangeContraint_MIN_val r 0u UInt32.MaxValue) c) |> List.choose (fun sc -> match sc with SicAlwaysTrue -> None | SciConstraint c -> Some c) + (fun intCon s -> + let aaa = [intCon] |> List.map (fun c -> simplifytIntegerTypeConstraint (UintHandleEqual r 0u) (UintHandleRangeConstraint_val_MAX r 0u) (UintHandleRangeConstraint_MIN_val r 0u UInt32.MaxValue) c) |> List.choose (fun sc -> match sc with SicAlwaysTrue -> None | SciConstraint c -> Some c) let bbb = aaa |> List.map (fun intCon -> foldSizeRangeTypeConstraint l (fun l p -> l.StrLen p.arg.p) p intCon |> fst) l.ExpAndMulti bbb, s) - (fun alphcon s -> + (fun alphcon s -> let foldAlpha = (foldRangeCon l (fun v -> v.ToString().ISQ) (fun v -> v.ToString().ISQ)) let alphaBody = foldAlpha ({CallerScope.modName = p.modName; arg = VALUE (sprintf "str%s" (l.ArrayAccess "i"))}) alphcon let alphaFuncName = sprintf "%s_%d" alphaFuncName s.alphaIndex @@ -210,12 +210,12 @@ let foldStringCon (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) alphaFuncName ( match l with | C -> isvalid_c.Print_AlphabetCheckFunc alphaFuncName [alphaBody] | Ada -> isvalid_a.Print_AlphabetCheckFunc alphaFuncName [alphaBody] - let alphFunc = {AlphaFunc.funcName = alphaFuncName; funcBody = funcBody } + let alphaFunc = {AlphaFunc.funcName = alphaFuncName; funcBody = funcBody } - let newState = {FoldStringCon23State.alphaIndex = s.alphaIndex + 1; alphaFuncs = alphFunc::s.alphaFuncs} - sprintf "%s(%s)" alphaFuncName p.arg.p, newState) + let newState = {FoldStringCon23State.alphaIndex = s.alphaIndex + 1; alphaFuncs = alphaFunc::s.alphaFuncs} + sprintf "%s(%s)" alphaFuncName p.arg.p, newState) c - us0 + us0 @@ -245,99 +245,99 @@ type ConstraintToStringFunc<'c,'state> = | StatefullConstraintToStringFunc of 'state * (CallerScope -> 'c -> 'state -> string*'state) -let createPrimitiveFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) allCons conToStrFunc (typeDefinition:TypeDefintionOrReference) (alphaFuncs : AlphaFunc list) (us:State) = +let createPrimitiveFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) allCons conToStrFunc (typeDefinition:TypeDefinitionOrReference) (alphaFuncs : AlphaFunc list) (us:State) = let hasValidationFunc= hasValidationFunc allCons - + // match allCons with // | [] -> None, us // | _ -> - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName - let funcExp (p:CallerScope) = + let funcExp (p:CallerScope) = let allCons = allCons |> List.map (conToStrFunc p) match allCons with | [] -> "TRUE" - | c::cs -> l.ExpAndMulti allCons + | c::cs -> l.ExpAndMulti allCons - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = r.stg.is_valid.makeExpressionToStatement (funcExp p) errCode.errCodeName let p = t.getParamType l Encode let varName = p.arg.p let sStar = p.arg.getStar l - let func = + let func = match funcName with | None -> None - | Some funcName -> - let exp = funcBody p + | Some funcName -> + let exp = funcBody p match l with |C -> Some(isvalid_c.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) - let funcDef = + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with |C -> Some(isvalid_c.EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = [errCode] func = func funcDef = funcDef funcExp = Some funcExp - funcBody = funcBody + funcBody = funcBody //funcBody2 = (fun p acc -> funcBody p) alphaFuncs = alphaFuncs localVariables = [] anonymousVariables = [] - } + } Some ret, ns -let createBitOrOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) allCons conToStrFunc (typeDefinition:TypeDefintionOrReference) (alphaFuncs : AlphaFunc list) anonymousVariables (us:State) = +let createBitOrOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) allCons conToStrFunc (typeDefinition:TypeDefinitionOrReference) (alphaFuncs : AlphaFunc list) anonymousVariables (us:State) = // match allCons with // | [] -> None, us // | _ -> - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName - let funcExp (p:CallerScope) = + let funcExp (p:CallerScope) = let allCons = allCons |> List.map (conToStrFunc p) match allCons with //| [] -> raise(BugErrorException("Invalid case")) | [] -> "TRUE" | c::cs -> l.ExpAndMulti allCons - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = r.stg.is_valid.makeExpressionToStatement (funcExp p) errCode.errCodeName let p = t.getParamType l Encode let varName = p.arg.p let sStar = p.arg.getStar l - let func = + let func = match funcName with | None -> None - | Some funcName -> - let exp = funcBody p + | Some funcName -> + let exp = funcBody p match l with |C -> Some(isvalid_c.EmitTypeAssignment_oct_or_bit_string varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) - let funcDef = + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with |C -> Some(isvalid_c.EmitTypeAssignment_oct_or_bit_string_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = [errCode] @@ -349,25 +349,25 @@ let createBitOrOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage alphaFuncs = alphaFuncs localVariables = [] anonymousVariables = anonymousVariables - } + } Some ret, ns let getIntSimplifiedConstraints (r:Asn1AcnAst.AstRoot) isUnsigned (allCons : IntegerTypeConstraint list) = match isUnsigned with - | true -> - allCons |> - List.map (fun c -> - let ret = simplifytIntegerTypeConstraint (UintHandleEqual r 0I) (UintHandleRangeContraint_val_MAX r 0I) (UintHandleRangeContraint_MIN_val r 0I r.args.UIntMax) c + | true -> + allCons |> + List.map (fun c -> + let ret = simplifytIntegerTypeConstraint (UintHandleEqual r 0I) (UintHandleRangeConstraint_val_MAX r 0I) (UintHandleRangeConstraint_MIN_val r 0I r.args.UIntMax) c ret - ) |> - List.choose (fun sc -> - match sc with - | SicAlwaysTrue -> None + ) |> + List.choose (fun sc -> + match sc with + | SicAlwaysTrue -> None | SciConstraint c -> Some c) - | false -> allCons |> List.map (fun c -> simplifytIntegerTypeConstraint (SIntHandleEqual r) (SIntHandleRangeContraint_val_MAX r) (SIntHandleRangeContraint_MIN_val r) c) |> List.choose (fun sc -> match sc with SicAlwaysTrue -> None | SciConstraint c -> Some c) - + | false -> allCons |> List.map (fun c -> simplifytIntegerTypeConstraint (SIntHandleEqual r) (SIntHandleRangeConstraint_val_MAX r) (SIntHandleRangeConstraint_MIN_val r) c) |> List.choose (fun sc -> match sc with SicAlwaysTrue -> None | SciConstraint c -> Some c) + -let integerToString (l:ProgrammingLanguage) isUnsigned (i:BigInteger) = +let integerToString (l:ProgrammingLanguage) isUnsigned (i:BigInteger) = match l with | Ada -> i.ToString() | C -> @@ -382,34 +382,34 @@ let createIntegerFunctionByCons (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) i match allCons with | [] -> None | _ -> - let funcExp (p:CallerScope) = + let funcExp (p:CallerScope) = let allCons = allCons |> List.map (conToStrFunc p) - l.ExpAndMulti allCons + l.ExpAndMulti allCons Some funcExp -let createIntegerFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createIntegerFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) (us:State) = let allCons = getIntSimplifiedConstraints r o.isUnsigned o.AllCons createPrimitiveFunction r l t allCons (foldRangeCon l (integerToString l o.isUnsigned ) (integerToString l o.isUnsigned)) typeDefinition [] us -let createRealFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createRealFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) (us:State) = createPrimitiveFunction r l t o.AllCons (foldRangeCon l (fun v -> v.ToString("E20", NumberFormatInfo.InvariantInfo)) (fun v -> v.ToString("E20", NumberFormatInfo.InvariantInfo))) typeDefinition [] us -let createStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) (us:State) = let allCons = o.AllCons let alphafuncName = ToC (((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_CharsAreValid") let initialState = {FoldStringCon23State. alphaIndex = 0; alphaFuncs = [] } - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName - let funcExp (p:CallerScope) = + let funcExp (p:CallerScope) = match allCons with | [] -> "TRUE", [] - | c::cs -> + | c::cs -> let allCons,fs = allCons |> foldMap (fun st c -> foldStringCon r l alphafuncName p c st) initialState - l.ExpAndMulti allCons, fs.alphaFuncs + l.ExpAndMulti allCons, fs.alphaFuncs - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = let exp, alphaFuncs = funcExp p r.stg.is_valid.makeExpressionToStatement exp errCode.errCodeName, alphaFuncs @@ -419,50 +419,50 @@ let createStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1A let p = t.getParamType l Encode let varName = p.arg.p let sStar = p.arg.getStar l - let exp, alphaFuncs = funcBody p - let func = + let exp, alphaFuncs = funcBody p + let func = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with - |C -> Some(isvalid_c.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) - |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) - let funcDef = + |C -> Some(isvalid_c.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) + |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive varName sStar funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) ) + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with |C -> Some(isvalid_c.EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) |Ada -> Some(isvalid_a.EmitTypeAssignment_primitive_def varName sStar funcName (typeDefinition.longTypedefName l) errCode.errCodeName (BigInteger errCode.errCodeValue)) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = [errCode] func = func funcDef = funcDef funcExp = Some funcExp2 - funcBody = funcBody2 + funcBody = funcBody2 //funcBody2 = (fun p acc -> funcBody p) alphaFuncs = alphaFuncs localVariables = [] anonymousVariables = [] - } + } Some ret, ns -let createBoolFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createBoolFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) (us:State) = createPrimitiveFunction r l t (o.cons@o.withcons) (foldGenericCon l (fun p v -> v.ToString().ToLower())) typeDefinition [] us type ObjectIdConstraintOrBasicValidation = | ObjectIdConstraint_basic | ObjectIdConstraint_const of ObjectIdConstraint -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) (us:State) = - let conToStrFunc_basic (p:CallerScope) = +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) (us:State) = + let conToStrFunc_basic (p:CallerScope) = match o.relativeObjectId with - | false -> sprintf "ObjectIdentifier_isValid(%s)" (p.arg.getPointer l) - | true -> sprintf "RelativeOID_isValid(%s)" (p.arg.getPointer l) + | false -> sprintf "ObjectIdentifier_isValid(%s)" (p.arg.getPointer l) + | true -> sprintf "RelativeOID_isValid(%s)" (p.arg.getPointer l) let conToStrFunc_c = (foldGenericCon l (fun p v -> v.ToString().ToLower())) let conToStrFunc (p:CallerScope) (mc:ObjectIdConstraintOrBasicValidation) = match mc with @@ -473,7 +473,7 @@ let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage createPrimitiveFunction r l t newCons conToStrFunc typeDefinition [] us -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) (defOrDer:TypeDefintionOrReference) (us:State) = +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) (defOrDer:TypeDefinitionOrReference) (us:State) = let printNamedItem (p:CallerScope) (v:string) = let itm = o.items |> Seq.find (fun x -> x.Name.Value = v) let ret = itm.getBackendName (Some defOrDer) l @@ -487,7 +487,7 @@ let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A // | Ada -> // match t.inheritInfo with // | None -> ret -// | Some inhInfo -> +// | Some inhInfo -> // match inhInfo.modName = p.modName with // | true -> ret // | false -> (ToC inhInfo.modName) + "." + ret @@ -496,18 +496,18 @@ let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A -let exlcudeSizeConstraintIfFixedSize minSize maxSize allCons = +let exlcudeSizeConstraintIfFixedSize minSize maxSize allCons = match minSize = maxSize with | false -> allCons - | true -> allCons |> List.filter(fun x -> match x with SizeContraint al-> false | _ -> true) + | true -> allCons |> List.filter(fun x -> match x with SizeConstraint al-> false | _ -> true) -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = let allCons = exlcudeSizeConstraintIfFixedSize o.minSize.uper o.maxSize.uper o.AllCons let curProgramUnit = ToC t.id.ModName let anonymousVariables = - allCons |> - List.map DastFold.getValueFromSizeableConstraint - |> List.collect id |> + allCons |> + List.map DastFold.getValueFromSizeableConstraint + |> List.collect id |> List.choose (fun (v:Asn1AcnAst.OctetStringValue, (id,loc)) -> let valKind = OctetStringValue (v |> List.map(fun z -> z.Value)) let recValue = {Asn1Value.kind = valKind; id=id;loc=loc} @@ -515,7 +515,7 @@ let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t: | ReferenceToValue (typePath,(VA2 vasName)::[]) -> None | ReferenceToValue(ts,vs) -> let typeDefinitionName = typeDefinition.longTypedefName l - Some ({AnonymousVariable.valueName = (recValue.getBackendName l); valueExpresion = (printValue curProgramUnit None recValue.kind); typeDefinitionName = typeDefinitionName; valKind=valKind})) + Some ({AnonymousVariable.valueName = (recValue.getBackendName l); valueExpression = (printValue curProgramUnit None recValue.kind); typeDefinitionName = typeDefinitionName; valKind=valKind})) let compareSingValueFunc (p:CallerScope) (v:Asn1AcnAst.OctetStringValue, (id,loc)) = let recValue = {Asn1Value.kind = OctetStringValue (v |> List.map(fun z -> z.Value)); id=id;loc=loc} let vstr = {CallerScope.modName = id.ModName; arg = VALUE (recValue.getBackendName l)} @@ -532,13 +532,13 @@ let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t: createBitOrOctetStringFunction r l t allCons foldSizeCon typeDefinition [] anonymousVariables us -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = let allCons = exlcudeSizeConstraintIfFixedSize o.minSize.uper o.maxSize.uper o.AllCons let curProgramUnit = ToC t.id.ModName let anonymousVariables = - allCons |> - List.map DastFold.getValueFromSizeableConstraint - |> List.collect id |> + allCons |> + List.map DastFold.getValueFromSizeableConstraint + |> List.collect id |> List.choose (fun (v:Asn1AcnAst.BitStringValue, (id,loc)) -> let valKind = BitStringValue (v.Value) let recValue = {Asn1Value.kind = valKind; id=id;loc=loc} @@ -546,12 +546,12 @@ let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:As | ReferenceToValue (typePath,(VA2 vasName)::[]) -> None | ReferenceToValue(ts,vs) -> let typeDefinitionName = defOrRef.longTypedefName l - Some ({AnonymousVariable.valueName = (recValue.getBackendName l); valueExpresion = (printValue curProgramUnit None recValue.kind); typeDefinitionName = typeDefinitionName; valKind = valKind})) + Some ({AnonymousVariable.valueName = (recValue.getBackendName l); valueExpression = (printValue curProgramUnit None recValue.kind); typeDefinitionName = typeDefinitionName; valKind = valKind})) let compareSingValueFunc (p:CallerScope) (v:Asn1AcnAst.BitStringValue, (id,loc)) = let recValue = {Asn1Value.kind = BitStringValue (v.Value ); id=id;loc=loc} //let vstr = VALUE (recValue.getBackendName l) let vstr = {CallerScope.modName = id.ModName; arg = VALUE (recValue.getBackendName l)} -// let vstr = +// let vstr = // match p.arg.getAcces l with // | "->" -> getAddres l (recValue.getBackendName l) // | _ -> recValue.getBackendName l @@ -567,10 +567,10 @@ let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:As (* SEQUENCE *) -let isValidSequenceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.Asn1Child) (newChild:Asn1Type) (us:State)= - let JoinTwoIfFirstOk = match l with C -> isvalid_c.JoinTwoIfFirstOk |Ada -> isvalid_a.JoinTwoIfFirstOk +let isValidSequenceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.Asn1Child) (newChild:Asn1Type) (us:State)= + let JoinTwoIfFirstOk = match l with C -> isvalid_c.JoinTwoIfFirstOk |Ada -> isvalid_a.JoinTwoIfFirstOk let c_name = o.getBackendName l - let sInnerStatement = + let sInnerStatement = match newChild.isValidFunction with | Some (isValidFunction) -> Some((fun (p:CallerScope) -> @@ -581,28 +581,28 @@ let isValidSequenceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.Asn1Child) (new | None -> None | Some (func, isValid) -> match o.Optionality with - | Some _ -> + | Some _ -> match l with - | C -> + | C -> let newFunc = (fun (p:CallerScope) -> isvalid_c.Sequence_OptionalChild p.arg.p (p.arg.getAcces l) c_name (func p )) Some (newFunc, isValid) - | Ada -> + | Ada -> let newFunc = (fun (p:CallerScope) -> isvalid_a.Sequence_OptionalChild p.arg.p (p.arg.getAcces l) c_name (func p )) Some (newFunc, isValid) | None -> Some (func, isValid) let isAlwaysPresentStatement, finalState = - let child_always_present_or_absent = - match l with - | C -> isvalid_c.Sequence_optional_child_always_present_or_absent + let child_always_present_or_absent = + match l with + | C -> isvalid_c.Sequence_optional_child_always_present_or_absent | Ada -> isvalid_a.Sequence_optional_child_always_present_or_absent - + match o.Optionality with - | Some(Asn1AcnAst.AlwaysAbsent) -> + | Some(Asn1AcnAst.AlwaysAbsent) -> let errCodeName = ToC ("ERR_" + ((newChild.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) + "_IS_PRESENT" let errCode, ns = getNextValidErrorCode us errCodeName let isValidStatement = (fun (p:CallerScope) -> child_always_present_or_absent p.arg.p (p.arg.getAcces l) c_name errCode.errCodeName "0") Some(isValidStatement, errCode), ns - | Some(Asn1AcnAst.AlwaysPresent) -> + | Some(Asn1AcnAst.AlwaysPresent) -> let errCodeName = ToC ("ERR_" + ((newChild.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) + "_IS_ABSENT" let errCode, ns = getNextValidErrorCode us errCodeName let isValidStatement = (fun (p:CallerScope) -> child_always_present_or_absent p.arg.p (p.arg.getAcces l) c_name errCode.errCodeName "1") @@ -611,18 +611,18 @@ let isValidSequenceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.Asn1Child) (new match sInnerStatement, isAlwaysPresentStatement with | None, None -> None , finalState - | None, Some(isValid, errCode) -> + | None, Some(isValid, errCode) -> Some({SeqChoiceChildInfoIsValid.isValidStatement = isValid; localVars = []; alphaFuncs = []; errCode = [errCode]}), finalState - | Some(isValid, chFunc), None -> + | Some(isValid, chFunc), None -> Some({SeqChoiceChildInfoIsValid.isValidStatement = isValid; localVars = chFunc.localVariables; alphaFuncs = chFunc.alphaFuncs; errCode = chFunc.errCodes}), finalState - | Some(isValid1, chFunc), Some(isValid2, errCode) -> - let isValid = (fun (p:CallerScope) -> JoinTwoIfFirstOk (isValid2 p ) (isValid1 p )) + | Some(isValid1, chFunc), Some(isValid2, errCode) -> + let isValid = (fun (p:CallerScope) -> JoinTwoIfFirstOk (isValid2 p ) (isValid1 p )) Some({SeqChoiceChildInfoIsValid.isValidStatement = isValid; localVars = chFunc.localVariables; alphaFuncs = chFunc.alphaFuncs; errCode = errCode::chFunc.errCodes}), finalState -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (children:SeqChildInfo list) (us:State) = +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (children:SeqChildInfo list) (us:State) = - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) let asn1Children = children |> List.choose(fun c -> match c with Asn1Child x -> Some x | AcnChild _ -> None) let body = let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) @@ -636,13 +636,13 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn let alphaFuncs = childrenConent |> List.collect(fun x -> x.alphaFuncs) let localVars = childrenConent |> List.collect(fun x -> x.localVars) let ercCodes = errCode::(childrenConent |> List.collect(fun x -> x.errCode)) - let vcbs,retstate = + let vcbs,retstate = o.cons2 |> Asn1Fold.foldMap(fun cs c -> DastValidate2.sequenceConstraint2ValidationCodeBlock r l t.id asn1Children () c cs) {DastValidate2.alphaIndex = 0; DastValidate2.alphaFuncs = alphaFuncs} //let eee p = o.cons2 |> Asn1Fold.foldMap(fun cc c -> DastValidate2.sequenceConstraint2ValidationCodeBlock r l t.id asn1Children () p c cc) ns1 - let funcBody (p:CallerScope) = - let seqValidationStatement = + let funcBody (p:CallerScope) = + let seqValidationStatement = match o.cons2 with | [] -> None | _ -> @@ -651,36 +651,36 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn let vcb = DastValidate2.ValidationCodeBlock_Multiple_And l vcbs Some (DastValidate2.convertVCBToStatementAndAssigneErrCode l vcb errCode.errCodeName) let aaa = - let childrenCheckStatements = x::xs |> List.map(fun x -> x.isValidStatement p) + let childrenCheckStatements = x::xs |> List.map(fun x -> x.isValidStatement p) (childrenCheckStatements@(seqValidationStatement |> Option.toList)) |> DAstUtilFunctions.nestItems l "ret" aaa.Value Some(alphaFuncs@retstate.alphaFuncs, localVars, ercCodes, funcBody, ns1) match body with | None -> None, us | Some(alphaFuncs, localVars, ercCodes, funcBody, finalState) -> - let func = + let func = let p = t.getParamType l Encode match funcName with | None -> None - | Some funcName -> - let exp = funcBody p + | Some funcName -> + let exp = funcBody p let lvars = localVars |> List.map(fun (lv:LocalVariable) -> lv.GetDeclaration l) |> Seq.distinct match l with |C -> Some(isvalid_c.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) |Ada -> Some(isvalid_a.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) - let funcDef = + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with - |C -> + |C -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_c.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_c.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - |Ada -> + |Ada -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_a.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_a.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = ercCodes @@ -691,30 +691,30 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn //funcBody2 = funcBody alphaFuncs = alphaFuncs localVariables = localVars - anonymousVariables = + anonymousVariables = let ret = asn1Children |> List.collect(fun c -> match c.Type.isValidFunction with Some vf -> vf.anonymousVariables | None -> []) ret |> Seq.distinctBy(fun x -> x.valueName) |> Seq.toList - } + } Some ret, finalState (* CHOICE *) -let isValidChoiceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.ChChildInfo) (newChild:Asn1Type) (us:State)= +let isValidChoiceChild (l:ProgrammingLanguage) (o:Asn1AcnAst.ChChildInfo) (newChild:Asn1Type) (us:State)= let c_name = ToC (o.getBackendName l) - let sInnerStatement = + let sInnerStatement = match newChild.isValidFunction with | Some (isValidFunction) -> Some((fun (p:CallerScope) ->isValidFunction.funcBody ({p with arg = p.arg.getChChild l c_name newChild.isIA5String})), isValidFunction) | None -> None - + match sInnerStatement with | None -> None , us - | Some(isValid, chFunc) -> + | Some(isValid, chFunc) -> Some({SeqChoiceChildInfoIsValid.isValidStatement = isValid; localVars = chFunc.localVariables; alphaFuncs = chFunc.alphaFuncs; errCode = chFunc.errCodes}), us -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (children:ChChildInfo list) (baseTypeValFunc : IsValidFunction option) (us:State) = - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) - let choice = match l with C -> isvalid_c.choice |Ada -> isvalid_a.choice +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (children:ChChildInfo list) (baseTypeValFunc : IsValidFunction option) (us:State) = + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) + let choice = match l with C -> isvalid_c.choice |Ada -> isvalid_a.choice let choice_child = match l with C -> isvalid_c.choice_child | Ada -> isvalid_a.choice_child let always_true_statement = match l with C -> isvalid_c.always_true_statement | Ada -> isvalid_a.always_true_statement let always_false_statement = match l with C -> isvalid_c.always_false_statement | Ada -> isvalid_a.always_false_statement @@ -722,14 +722,14 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1A let body = let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) //let errCodeValue = us.currErrCode - //let errCode = {ErroCode.errCodeName = errCodeName; errCodeValue = errCodeValue} + //let errCode = {ErrorCode.errCodeName = errCodeName; errCodeValue = errCodeValue} let errCode, ns = getNextValidErrorCode us errCodeName - let childrenConent, finalState = - children |> - Asn1Fold.foldMap (fun errCode cc -> + let childrenConent, finalState = + children |> + Asn1Fold.foldMap (fun errCode cc -> let (vc,erc) = cc.isValidBodyStats errCode ((cc,vc),erc)) ns //let deltaErrCode = finalErrCode - us.currErrCode @@ -738,13 +738,13 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1A let alphaFuncs = validatedComponenets |> List.collect(fun x -> x.alphaFuncs) let localVars = validatedComponenets |> List.collect(fun x -> x.localVars) let ercCodes = errCode::(validatedComponenets |> List.collect(fun x -> x.errCode)) - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = let childrenContent = - childrenConent |> - List.map(fun (cc, vc) -> - let chBody, bAlwaysAbsent = + childrenConent |> + List.map(fun (cc, vc) -> + let chBody, bAlwaysAbsent = match cc.Optionality with - | None + | None | Some (Asn1AcnAst.ChoiceAlwaysPresent) -> match vc with | Some vc -> vc.isValidStatement p ,false @@ -758,50 +758,50 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1A match body with | None -> None, us | Some(alphaFuncs, localVars, ercCodes, funcBody, finalState) -> - let func = + let func = let p = t.getParamType l Encode match funcName with | None -> None - | Some funcName -> - let exp = funcBody p + | Some funcName -> + let exp = funcBody p let lvars = localVars |> List.map(fun (lv:LocalVariable) -> lv.GetDeclaration l) |> Seq.distinct match l with |C -> Some(isvalid_c.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) |Ada -> Some(isvalid_a.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) - let funcDef = + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with - |C -> + |C -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_c.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_c.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - |Ada -> + |Ada -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_a.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_a.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = ercCodes func = func funcDef = funcDef funcExp = None - funcBody = funcBody + funcBody = funcBody //funcBody2 = funcBody alphaFuncs = alphaFuncs localVariables = localVars - anonymousVariables = - let ret =children |> List.collect(fun c -> match c.chType.isValidFunction with Some vf -> vf.anonymousVariables | None -> []) + anonymousVariables = + let ret =children |> List.collect(fun c -> match c.chType.isValidFunction with Some vf -> vf.anonymousVariables | None -> []) ret |> Seq.distinctBy(fun x -> x.valueName) |> Seq.toList - } + } Some ret, finalState -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (childType:Asn1Type) (baseTypeValFunc : IsValidFunction option) (us:State) = - let funcName = getFuncName r l t.id (t.FT_TypeDefintion.[l]) +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (childType:Asn1Type) (baseTypeValFunc : IsValidFunction option) (us:State) = + let funcName = getFuncName r l t.id (t.FT_TypeDefinition.[l]) let bIsFixedSize = o.minSize.uper = o.maxSize.uper - let hasValidationFunc = + let hasValidationFunc = match bIsFixedSize with | false -> true | true -> @@ -814,9 +814,9 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A (*alphaFuncs, localVars, ercCodes, funcBody, deltaErrCode*) let body = - let allSizeCons = o.AllCons |> List.filter(fun x -> match x with SizeContraint al-> true | _ -> false) + let allSizeCons = o.AllCons |> List.filter(fun x -> match x with SizeConstraint al-> true | _ -> false) let foldSizeCon = foldSizableConstraint l (fun p v -> v.ToString()) (fun l p -> l.Length p.arg.p (p.arg.getAcces l)) - let sizeConstrData = + let sizeConstrData = match bIsFixedSize with | true -> None | false -> @@ -829,12 +829,12 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A let allCons = allSizeCons |> List.map (foldSizeCon p ) l.ExpAndMulti allCons Some(errCode, sIsValidSizeExpFunc, ns) - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) match childType.isValidFunction, sizeConstrData with | None, None -> None | Some cvf, None -> - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = //let childAccesPath = p + childAccess + l.ArrName + (l.ArrayAccess i) //"[" + i + "]" let innerStatement = Some(cvf.funcBody ({p with arg = p.arg.getArrayItem l i childType.isIA5String}) ) match l with @@ -842,11 +842,11 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A | Ada -> isvalid_a.sequenceOf p.arg.p (p.arg.getAcces l) i bIsFixedSize ( o.minSize.uper) None None innerStatement Some(cvf.alphaFuncs, lv::cvf.localVariables , cvf.errCodes, funcBody, us) | None, Some(errCode, sIsValidSizeExpFunc, ns) -> - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = r.stg.is_valid.makeExpressionToStatement (sIsValidSizeExpFunc p ) errCode.errCodeName Some([],[], [errCode], funcBody, ns) | Some cvf, Some(errCode, sIsValidSizeExpFunc, ns) -> - let funcBody (p:CallerScope) = + let funcBody (p:CallerScope) = //let childAccesPath = p + childAccess + l.ArrName + (l.ArrayAccess i) //"[" + i + "]" let innerStatement = Some(cvf.funcBody ({p with arg = p.arg.getArrayItem l i childType.isIA5String})) match l with @@ -858,30 +858,30 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A match body with | None -> None, us | Some(alphaFuncs, localVars, ercCodes, funcBody, newState) -> - let func = + let func = let p = t.getParamType l Encode match funcName with | None -> None - | Some funcName -> - let exp = funcBody p + | Some funcName -> + let exp = funcBody p let lvars = localVars |> List.map(fun (lv:LocalVariable) -> lv.GetDeclaration l) |> Seq.distinct match l with |C -> Some(isvalid_c.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) |Ada -> Some(isvalid_a.EmitTypeAssignment_composite funcName (typeDefinition.longTypedefName l) exp (alphaFuncs |> List.map(fun x -> x.funcBody)) lvars) - let funcDef = + let funcDef = match funcName with | None -> None - | Some funcName -> + | Some funcName -> match l with - |C -> + |C -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_c.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_c.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - |Ada -> + |Ada -> let arrsErrcodes = ercCodes |> List.map(fun s -> isvalid_a.EmitTypeAssignment_composite_def_err_code s.errCodeName (BigInteger s.errCodeValue)) Some(isvalid_a.EmitTypeAssignment_composite_def funcName (typeDefinition.longTypedefName l) arrsErrcodes) - - let ret = + + let ret = { IsValidFunction.funcName = funcName errCodes = ercCodes @@ -892,15 +892,15 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:A //funcBody2 = funcBody alphaFuncs = alphaFuncs localVariables = localVars - anonymousVariables = + anonymousVariables = match childType.isValidFunction with | Some v -> v.anonymousVariables | None -> [] - } + } Some ret, newState -let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (baseType:Asn1Type) (us:State) = - baseType.isValidFunction, us +let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (baseType:Asn1Type) (us:State) = + baseType.isValidFunction, us #endif \ No newline at end of file diff --git a/BackendAst/DAstVariables.fs b/BackendAst/DAstVariables.fs index dbf459bb5..211830450 100644 --- a/BackendAst/DAstVariables.fs +++ b/BackendAst/DAstVariables.fs @@ -11,12 +11,10 @@ open DAstUtilFunctions open Language -//let getDefaultValueByType (t:Asn1Type) = t.initialValue +let printOctetStringValueAsCompoundLiteral (lm:LanguageMacros) curProgramUnitName (o:Asn1AcnAst.OctetString) (bytes : byte list) = + let printOct = lm.vars.PrintBitOrOctetStringValueAsCompoundLiteral -let printOctetStringValueAsCompoundLitteral (lm:LanguageMacros) curProgamUnitName (o:Asn1AcnAst.OctetString) (bytes : byte list) = - let printOct = lm.vars.PrintBitOrOctetStringValueAsCompoundLitteral - - let td = (lm.lg.getSizeableTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules curProgamUnitName + let td = (lm.lg.getSizeableTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules curProgramUnitName printOct td (o.minSize.uper = o.maxSize.uper) bytes (BigInteger bytes.Length) let printTimeValue (lm:LanguageMacros) (td) (v:TimeValue) = @@ -29,19 +27,19 @@ let printTimeValue (lm:LanguageMacros) (td) (v:TimeValue) = |Asn1Date_UtcTimeValue (dt,tv) -> lm.vars.PrintTimeValue_Asn1Date_UtcTime td dt tv |Asn1Date_LocalTimeWithTimeZoneValue (dt,tv,tz)-> lm.vars.PrintTimeValue_Asn1Date_LocalTimeWithTimeZone td dt tv tz - -let printBitStringValueAsCompoundLitteral (lm:LanguageMacros) curProgamUnitName (o:Asn1AcnAst.BitString) (v : BitStringValue) = - let printOct = lm.vars.PrintBitOrOctetStringValueAsCompoundLitteral - let td = (lm.lg.getSizeableTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules curProgamUnitName + +let printBitStringValueAsCompoundLiteral (lm:LanguageMacros) curProgramUnitName (o:Asn1AcnAst.BitString) (v : BitStringValue) = + let printOct = lm.vars.PrintBitOrOctetStringValueAsCompoundLiteral + let td = (lm.lg.getSizeableTypeDefinition o.typeDef).longTypedefName2 lm.lg.hasModules curProgramUnitName let bytes = lm.lg.bitStringValueToByteArray v printOct td (o.minSize.uper = o.maxSize.uper) bytes o.minSize.uper -let converStringValue2TargetLangStringLiteral (lm:LanguageMacros) mxSizeUper (v:StringValue) = +let convertStringValue2TargetLangStringLiteral (lm:LanguageMacros) mxSizeUper (v:StringValue) = let (parts,_) = v let vStr = CommonTypes.StringValue2String parts - let arrNuls = [0 .. ((int mxSizeUper) - vStr.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) - let pParts = - parts |> + let arrNulls = [0 .. ((int mxSizeUper) - vStr.Length)]|>Seq.map(fun x -> lm.vars.PrintStringValueNull()) + let pParts = + parts |> List.map(fun s -> match s with | CStringValue sv -> lm.vars.PrintSingleStringValue (sv.Replace("\"","\"\"")) @@ -50,48 +48,48 @@ let converStringValue2TargetLangStringLiteral (lm:LanguageMacros) mxSizeUper (v: | SpecialCharacter HorizontalTab -> lm.vars.PrintHT () | SpecialCharacter NullCharacter -> lm.vars.PrintStringValueNull () ) - lm.vars.PrintStringValue pParts arrNuls + lm.vars.PrintStringValue pParts arrNulls -let rec printValue (r:DAst.AstRoot) (lm:LanguageMacros) (curProgamUnitName:string) (t:Asn1Type) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = +let rec printValue (r:DAst.AstRoot) (lm:LanguageMacros) (curProgramUnitName:string) (t:Asn1Type) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = match gv with | IntegerValue v -> lm.vars.PrintIntValue v | RealValue v -> lm.vars.PrintRealValue v | BooleanValue v -> lm.vars.PrintBooleanValue v - | StringValue v -> + | StringValue v -> match t.ActualType.Kind with - | IA5String st -> converStringValue2TargetLangStringLiteral lm (int st.baseInfo.maxSize.uper) v + | IA5String st -> convertStringValue2TargetLangStringLiteral lm (int st.baseInfo.maxSize.uper) v | _ -> raise(BugErrorException "unexpected type") - | BitStringValue v -> + | BitStringValue v -> let bytes = bitStringValueToByteArray (StringLoc.ByValue v) match t.ActualType.Kind with - | OctetString os -> - let td = lm.lg.getSizeableTypeDefinition os.baseInfo.typeDef + | OctetString os -> + let td = lm.lg.getSizeableTypeDefinition os.baseInfo.typeDef lm.vars.PrintOctetStringValue td (os.baseInfo.minSize.uper = os.baseInfo.maxSize.uper) bytes (BigInteger bytes.Length) - | BitString bs -> - let td = lm.lg.getSizeableTypeDefinition bs.baseInfo.typeDef + | BitString bs -> + let td = lm.lg.getSizeableTypeDefinition bs.baseInfo.typeDef let arBits = v.ToCharArray() |> Array.map(fun x -> x.ToString()) lm.vars.PrintBitStringValue td (bs.baseInfo.minSize.uper = bs.baseInfo.maxSize.uper) arBits (BigInteger arBits.Length) bytes (BigInteger bytes.Length) | _ -> raise(BugErrorException "unexpected type") - | OctetStringValue v -> + | OctetStringValue v -> match t.ActualType.Kind with - | OctetString os -> - let td = lm.lg.getSizeableTypeDefinition os.baseInfo.typeDef + | OctetString os -> + let td = lm.lg.getSizeableTypeDefinition os.baseInfo.typeDef lm.vars.PrintOctetStringValue td (os.baseInfo.minSize.uper = os.baseInfo.maxSize.uper) v (BigInteger v.Length) - | BitString bs -> - let td = lm.lg.getSizeableTypeDefinition bs.baseInfo.typeDef - let bittring = byteArrayToBitStringValue v - let arBits = bittring.ToCharArray() |> Array.map(fun x -> x.ToString()) + | BitString bs -> + let td = lm.lg.getSizeableTypeDefinition bs.baseInfo.typeDef + let bitstring = byteArrayToBitStringValue v + let arBits = bitstring.ToCharArray() |> Array.map(fun x -> x.ToString()) let maxLen = if (arBits.Length > int bs.baseInfo.maxSize.uper) then ((int bs.baseInfo.maxSize.uper)-1) else (arBits.Length-1) let arBits = arBits.[0 .. maxLen] lm.vars.PrintBitStringValue td (bs.baseInfo.minSize.uper = bs.baseInfo.maxSize.uper) arBits (BigInteger arBits.Length) v (BigInteger v.Length) | _ -> raise(BugErrorException "unexpected type") - | EnumValue v -> + | EnumValue v -> match t.ActualType.Kind with - | Enumerated enm -> + | Enumerated enm -> let typeModName = (t.getActualType r).id.ModName let itm = enm.baseInfo.items |> Seq.find(fun x -> x.Name.Value = v) - let itmName = lm.lg.getNamedItemBackendName2 t.ActualType.moduleName curProgamUnitName itm + let itmName = lm.lg.getNamedItemBackendName2 t.ActualType.moduleName curProgramUnitName itm lm.vars.PrintEnumValue itmName | _ -> raise(BugErrorException "unexpected type") | NullValue v -> lm.vars.PrintNullValue () @@ -107,44 +105,44 @@ let rec printValue (r:DAst.AstRoot) (lm:LanguageMacros) (curProgamUnitName:stri let td = lm.lg.typeDef tt.baseInfo.typeDef printTimeValue lm td v | _ -> raise(BugErrorException "unexpected type") - | SeqOfValue v -> + | SeqOfValue v -> match t.ActualType.Kind with - | SequenceOf so -> + | SequenceOf so -> let td = lm.lg.getSizeableTypeDefinition so.baseInfo.typeDef - let childVals = v |> List.map (fun chv -> printValue r lm curProgamUnitName so.childType (Some gv) chv.kind) + let childVals = v |> List.map (fun chv -> printValue r lm curProgramUnitName so.childType (Some gv) chv.kind) let sDefValue = so.childType.initFunction.initExpression lm.vars.PrintSequenceOfValue td (so.baseInfo.minSize.uper = so.baseInfo.maxSize.uper) (BigInteger v.Length) childVals sDefValue | _ -> raise(BugErrorException "unexpected type") - | SeqValue v -> + | SeqValue v -> match t.ActualType.Kind with - | Sequence s -> + | Sequence s -> let td = lm.lg.getSequenceTypeDefinition s.baseInfo.typeDef - let typeDefName = lm.lg.getLongTypedefName t.typeDefintionOrReference // t.typeDefintionOrReference.longTypedefName l//if parentValue.IsSome then s.typeDefinition.typeDefinitionBodyWithinSeq else s.typeDefinition.name - let optChildren = + let typeDefName = lm.lg.getLongTypedefName t.typeDefinitionOrReference // t.typeDefinitionOrReference.longTypedefName l//if parentValue.IsSome then s.typeDefinition.typeDefinitionBodyWithinSeq else s.typeDefinition.name + let optChildren = s.children |> List.choose(fun ch -> match ch with Asn1Child a -> Some a | AcnChild _ -> None) |> List.filter(fun ch -> ch.Optionality.IsSome) |> List.map(fun x -> - + match v |> Seq.tryFind(fun chv -> chv.name = x.Name.Value) with | Some _ -> lm.vars.PrintSequenceValue_child_exists (lm.lg.getAsn1ChildBackendName x) "1" | None -> lm.vars.PrintSequenceValue_child_exists (lm.lg.getAsn1ChildBackendName x) "0") - let arrChildren = + let arrChildren = s.children |> List.choose(fun ch -> match ch with Asn1Child a -> Some a | AcnChild _ -> None) |> - List.choose(fun x -> + List.choose(fun x -> match v |> Seq.tryFind(fun chv -> chv.name = x.Name.Value) with - | Some v -> + | Some v -> let childType = x.Type - Some (lm.vars.PrintSequenceValueChild (lm.lg.getAsn1ChildBackendName x) (printValue r lm curProgamUnitName childType (Some gv) v.Value.kind)) - | None -> - let chV = + Some (lm.vars.PrintSequenceValueChild (lm.lg.getAsn1ChildBackendName x) (printValue r lm curProgramUnitName childType (Some gv) v.Value.kind)) + | None -> + let chV = match x.Optionality with - | Some(Asn1AcnAst.Optional opt) -> + | Some(Asn1AcnAst.Optional opt) -> match opt.defaultValue with - | Some v -> + | Some v -> let chV = (mapValue v).kind - Some (printValue r lm curProgamUnitName x.Type None chV) + Some (printValue r lm curProgramUnitName x.Type None chV) | None -> if lm.lg.supportsInitExpressions then (Some x.Type.initFunction.initExpression) else None | _ -> if lm.lg.supportsInitExpressions then (Some x.Type.initFunction.initExpression) else None match chV with @@ -152,15 +150,15 @@ let rec printValue (r:DAst.AstRoot) (lm:LanguageMacros) (curProgamUnitName:stri | Some chV -> Some (lm.vars.PrintSequenceValueChild (lm.lg.getAsn1ChildBackendName x) chV )) lm.vars.PrintSequenceValue td typeDefName arrChildren optChildren | _ -> raise(BugErrorException "unexpected type") - | ChValue v -> + | ChValue v -> match t.ActualType.Kind with - | Choice s -> - let typeDefName = lm.lg.getLongTypedefName t.typeDefintionOrReference + | Choice s -> + let typeDefName = lm.lg.getLongTypedefName t.typeDefinitionOrReference s.children |> List.filter(fun x -> x.Name.Value = v.name) |> - List.map(fun x -> - let chValue = printValue r lm curProgamUnitName x.chType (Some gv) v.Value.kind - let sChildNamePresent = lm.lg.presentWhenName (Some t.typeDefintionOrReference) x + List.map(fun x -> + let chValue = printValue r lm curProgramUnitName x.chType (Some gv) v.Value.kind + let sChildNamePresent = lm.lg.presentWhenName (Some t.typeDefinitionOrReference) x lm.vars.PrintChoiceValue typeDefName (lm.lg.getAsn1ChChildBackendName x) chValue sChildNamePresent true ) |> List.head | _ -> raise(BugErrorException "unexpected type") @@ -168,22 +166,19 @@ let rec printValue (r:DAst.AstRoot) (lm:LanguageMacros) (curProgamUnitName:stri match t.ActualType.Kind with | Integer _ | Real _ -> - printValue r lm curProgamUnitName t parentValue v.kind + printValue r lm curProgramUnitName t parentValue v.kind | _ -> match lm.lg.hasModules with | false -> - printValue r lm curProgamUnitName t parentValue v.kind + printValue r lm curProgramUnitName t parentValue v.kind | true -> let vas = r.getValueAssignmentByName md vs - match (ToC md) = curProgamUnitName with - | true -> lm.lg.getValueAssignmentName vas - | false -> curProgamUnitName + "." + (lm.lg.getValueAssignmentName vas) - - - + match (ToC md) = curProgramUnitName with + | true -> lm.lg.getValueAssignmentName vas + | false -> curProgramUnitName + "." + (lm.lg.getValueAssignmentName vas) let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with | IntegerValue i -> lm.vars.PrintIntValue i | RefValue ((md,vs),ov) -> vs @@ -191,7 +186,7 @@ let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnA printValue let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with | RealValue i -> lm.vars.PrintRealValue i | RefValue ((md,vs),ov) -> vs @@ -199,7 +194,7 @@ let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst. printValue let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with | BooleanValue i -> lm.vars.PrintBooleanValue i | RefValue ((md,vs),ov) -> vs @@ -208,10 +203,10 @@ let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnA -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefintionOrReference) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (defOrRef:TypeDefinitionOrReference) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with - | EnumValue i -> + | EnumValue i -> let itm = o.items |> Seq.find(fun x -> x.Name.Value = i) lm.vars.PrintEnumValue (lm.lg.getNamedItemBackendName (Some defOrRef) itm) | RefValue ((md,vs),ov) -> vs @@ -221,7 +216,7 @@ let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) = let stgMacro = lm.vars.PrintNullValue - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with | NullValue _ -> stgMacro () | RefValue ((md,vs),ov) -> vs @@ -230,45 +225,44 @@ let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn let createStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with - | StringValue v -> - converStringValue2TargetLangStringLiteral lm (int o.maxSize.uper) v + | StringValue v -> + convertStringValue2TargetLangStringLiteral lm (int o.maxSize.uper) v | RefValue ((md,vs),ov) -> vs | _ -> raise(BugErrorException "unexpected value") printValue -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (defOrRef:TypeDefintionOrReference) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (defOrRef:TypeDefinitionOrReference) = let PrintOctetStringValue = lm.vars.PrintOctetStringValue - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with - | OctetStringValue v -> - let td = lm.lg.getSizeableTypeDefinition o.typeDef + | OctetStringValue v -> + let td = lm.lg.getSizeableTypeDefinition o.typeDef PrintOctetStringValue td (o.minSize.uper = o.maxSize.uper) v (BigInteger v.Length) - | BitStringValue v -> + | BitStringValue v -> let bytes = bitStringValueToByteArray (StringLoc.ByValue v) |> Seq.toList - let td = lm.lg.getSizeableTypeDefinition o.typeDef // (o.typeDef.[l]).longTypedefName l curProgamUnitName - //let typeDefName = defOrRef.longTypedefName l//if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name + let td = lm.lg.getSizeableTypeDefinition o.typeDef PrintOctetStringValue td (o.minSize.uper = o.maxSize.uper) bytes (BigInteger bytes.Length) | RefValue ((md,vs),ov) -> vs | _ -> raise(BugErrorException "unexpected value") printValue -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (defOrRef:TypeDefintionOrReference) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (defOrRef:TypeDefinitionOrReference) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = let td = lm.lg.typeDef o.typeDef match v with - | ObjOrRelObjIdValue v -> + | ObjOrRelObjIdValue v -> lm.vars.PrintObjectIdentifierValue td (v.Values |> List.map fst) (BigInteger v.Values.Length) | RefValue ((md,vs),ov) -> vs | _ -> raise(BugErrorException "unexpected value") printValue -let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (defOrRef:TypeDefintionOrReference) = - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = +let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (defOrRef:TypeDefinitionOrReference) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = let td = lm.lg.typeDef o.typeDef match v with | TimeValue v -> printTimeValue lm td v @@ -277,36 +271,33 @@ let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac printValue -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (defOrRef:TypeDefintionOrReference) = - let PrintBitStringValue = lm.vars.PrintBitStringValue - let PrintOctetStringValue = lm.vars.PrintOctetStringValue - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (defOrRef:TypeDefinitionOrReference) = + let PrintBitStringValue = lm.vars.PrintBitStringValue + let PrintOctetStringValue = lm.vars.PrintOctetStringValue + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (v:Asn1ValueKind) = match v with - | BitStringValue v -> + | BitStringValue v -> let bytes = bitStringValueToByteArray (StringLoc.ByValue v) - let td = lm.lg.getSizeableTypeDefinition o.typeDef //(o.typeDef.[l]).longTypedefName l curProgamUnitName - //let typeDefName = defOrRef.longTypedefName l//if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name + let td = lm.lg.getSizeableTypeDefinition o.typeDef let arBits = v.ToCharArray() |> Array.map(fun x -> x.ToString()) PrintBitStringValue td (o.minSize.uper = o.maxSize.uper) arBits (BigInteger arBits.Length) bytes (BigInteger bytes.Length) - | OctetStringValue v -> - let td = lm.lg.getSizeableTypeDefinition o.typeDef //(o.typeDef.[l]).longTypedefName l curProgamUnitName - //let typeDefName = defOrRef.longTypedefName l //if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name + | OctetStringValue v -> + let td = lm.lg.getSizeableTypeDefinition o.typeDef PrintOctetStringValue td (o.minSize.uper = o.maxSize.uper) v (BigInteger v.Length) | RefValue ((md,vs),ov) -> vs | _ -> raise(BugErrorException "unexpected value") printValue -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (defOrRef:TypeDefintionOrReference) (childType:Asn1Type) = - let stgMacro = lm.vars.PrintBooleanValue - let PrintSequenceOfValue = lm.vars.PrintSequenceOfValue - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (defOrRef:TypeDefinitionOrReference) (childType:Asn1Type) = + let stgMacro = lm.vars.PrintBooleanValue + let PrintSequenceOfValue = lm.vars.PrintSequenceOfValue + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = match gv with - | SeqOfValue chVals -> - let childVals = chVals |> List.map (fun chv -> childType.printValue curProgamUnitName (Some gv) chv.kind) - //let typeDefName = defOrRef.longTypedefName l//if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name - let sDefValue = childType.initFunction.initExpression //childType.printValue curProgamUnitName None childType.initialValue - let td = lm.lg.getSizeableTypeDefinition o.typeDef + | SeqOfValue chVals -> + let childVals = chVals |> List.map (fun chv -> childType.printValue curProgramUnitName (Some gv) chv.kind) + let sDefValue = childType.initFunction.initExpression + let td = lm.lg.getSizeableTypeDefinition o.typeDef PrintSequenceOfValue td (o.minSize.uper = o.maxSize.uper) (BigInteger chVals.Length) childVals sDefValue | RefValue ((md,vs),ov) -> vs @@ -314,43 +305,43 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A printValue -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (defOrRef:TypeDefintionOrReference) (children:SeqChildInfo list) = +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (defOrRef:TypeDefinitionOrReference) (children:SeqChildInfo list) = let PrintSequenceValue_child_exists = lm.vars.PrintSequenceValue_child_exists let PrintSequenceValueChild = lm.vars.PrintSequenceValueChild let PrintSequenceValue = lm.vars.PrintSequenceValue - - let optChildren = + + let optChildren = children |> List.choose(fun ch -> match ch with Asn1Child a -> Some a | AcnChild _ -> None) |> - List.filter(fun ch -> ch.Optionality.IsSome) - - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = + List.filter(fun ch -> ch.Optionality.IsSome) + + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = match gv with - | SeqValue v -> - let td = lm.lg.getSequenceTypeDefinition o.typeDef // (o.typeDef.[l]).longTypedefName l curProgamUnitName - let typeDefName = lm.lg.getLongTypedefName defOrRef//if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name - let optChildren = + | SeqValue v -> + let td = lm.lg.getSequenceTypeDefinition o.typeDef + let typeDefName = lm.lg.getLongTypedefName defOrRef + let optChildren = optChildren |> List.map(fun x -> match v |> Seq.tryFind(fun chv -> chv.name = x.Name.Value) with | Some _ -> PrintSequenceValue_child_exists (lm.lg.getAsn1ChildBackendName x) "1" | None -> PrintSequenceValue_child_exists (lm.lg.getAsn1ChildBackendName x) "0") - let arrChildren = + let arrChildren = children |> List.choose(fun ch -> match ch with Asn1Child a -> Some a | AcnChild _ -> None) |> - List.choose(fun x -> + List.choose(fun x -> match v |> Seq.tryFind(fun chv -> chv.name = x.Name.Value) with - | Some v -> - let childValue = x.Type.printValue curProgamUnitName (Some gv) v.Value.kind + | Some v -> + let childValue = x.Type.printValue curProgramUnitName (Some gv) v.Value.kind Some (lm.vars.PrintSequenceValueChild (lm.lg.getAsn1ChildBackendName x) childValue) - | None -> - let childValue = + | None -> + let childValue = match x.Optionality with - | Some(Asn1AcnAst.Optional opt) -> + | Some(Asn1AcnAst.Optional opt) -> match opt.defaultValue with - | Some zz -> + | Some zz -> let v = (mapValue zz).kind - Some(x.Type.printValue curProgamUnitName (Some gv) v) + Some(x.Type.printValue curProgramUnitName (Some gv) v) | None -> match lm.lg.supportsInitExpressions with false -> None | true -> Some (x.Type.initFunction.initExpression) | _ -> match lm.lg.supportsInitExpressions with false -> None | true -> Some (x.Type.initFunction.initExpression) match childValue with @@ -362,17 +353,17 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Acn printValue -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (defOrRef:TypeDefintionOrReference) (children:ChChildInfo list) = +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (defOrRef:TypeDefinitionOrReference) (children:ChChildInfo list) = let PrintChoiceValue = lm.vars.PrintChoiceValue - let printValue (curProgamUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = + let printValue (curProgramUnitName:string) (parentValue:Asn1ValueKind option) (gv:Asn1ValueKind) = match gv with - | ChValue chVal -> - let typeDefName = lm.lg.getLongTypedefName defOrRef //if parentValue.IsSome then typeDefinition.typeDefinitionBodyWithinSeq else typeDefinition.name + | ChValue chVal -> + let typeDefName = lm.lg.getLongTypedefName defOrRef children |> List.filter(fun x -> x.Name.Value = chVal.name) |> - List.map(fun x -> - - let childValue = (x.chType.printValue curProgamUnitName (Some gv) chVal.Value.kind) + List.map(fun x -> + + let childValue = (x.chType.printValue curProgramUnitName (Some gv) chVal.Value.kind) let sChildNamePresent = lm.lg.presentWhenName (Some defOrRef) x lm.vars.PrintChoiceValue typeDefName (lm.lg.getAsn1ChChildBackendName x) childValue sChildNamePresent true ) |> @@ -381,6 +372,6 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAs | _ -> raise(BugErrorException "unexpected value") printValue -let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (defOrRef:TypeDefintionOrReference) (baseType:Asn1Type) = +let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (defOrRef:TypeDefinitionOrReference) (baseType:Asn1Type) = baseType.printValue diff --git a/BackendAst/DAstXer.fs b/BackendAst/DAstXer.fs index e6baa3643..175df0c64 100644 --- a/BackendAst/DAstXer.fs +++ b/BackendAst/DAstXer.fs @@ -39,7 +39,7 @@ let rec XerTagFnc (t:Asn1AcnAst.Asn1Type) (r:Asn1AcnAst.AstRoot) = | Asn1AcnAst.SequenceOf(_) -> Some (XerLiteralConstant "SEQUENCE-OF") | Asn1AcnAst.ObjectIdentifier _ -> Some (XerLiteralConstant "OBJECT-IDENTIFIER") | Asn1AcnAst.TimeType tc -> Some (XerLiteralConstant (CommonTypes.timeTypeToAsn1Str tc.timeClass)) - + let private aux (s:string) = 2 * (s.Length + 1) + 1 |> BigInteger @@ -57,7 +57,7 @@ let getMaxSizeInBytesForXER_NumericString maxSize = maxSize let getMaxSizeInBytesForXER (xmlTag:XerTag) (contentSize:BigInteger) : BigInteger = let tagValue = - match xmlTag with + match xmlTag with | XerLiteralConstant tagValue | XerFunctionParameter (tagValue, _) -> tagValue @@ -66,46 +66,46 @@ let getMaxSizeInBytesForXER (xmlTag:XerTag) (contentSize:BigInteger) : BigInteg | _ -> (2I * (BigInteger(tagValue.Length + 2))) + 1I + contentSize -let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeDefinition:TypeDefintionOrReference) = +let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (typeDefinition:TypeDefinitionOrReference) = getFuncNameGeneric typeDefinition ("_XER" + codec.suffix) -let createXerFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) xerFuncBody_e soSparkAnnotations (us:State) = - let emitTypeAssignment = lm.xer.EmitTypeAssignment +let createXerFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) xerFuncBody_e soSparkAnnotations (us:State) = + let emitTypeAssignment = lm.xer.EmitTypeAssignment let emitTypeAssignment_def = lm.xer.EmitTypeAssignment_def - let EmitTypeAssignment_def_err_code = lm.uper.EmitTypeAssignment_def_err_code - + let EmitTypeAssignment_def_err_code = lm.uper.EmitTypeAssignment_def_err_code + let funcName = getFuncName r lm codec typeDefinition let p = lm.lg.getParamType t codec - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let isValidFuncName = match isValidFunc with None -> None | Some f -> f.funcName - let sInitilialExp = "" + let sInitialExp = "" let errCodeName = ToC ("ERR_XER" + (codec.suffix.ToUpper()) + "_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let defaultErrCode, ns = getNextValidErrorCode us errCodeName None let xerFuncBody = (xerFuncBody_e defaultErrCode) - let xerFunc, xerFuncDef, encodingSizeInBytes = + let xerFunc, xerFuncDef, encodingSizeInBytes = match funcName with | None -> None, None, 0I - | Some funcName -> + | Some funcName -> let asn1TasName = typeDefinition.getAsn1Name r.args.TypePrefix let xerBdResultOpt : XERFuncBodyResult option= xerFuncBody_e defaultErrCode p (Some (XerFunctionParameter (asn1TasName, "xmlTag"))) - let bodyResult_funcBody, errCodes, bodyResult_localVariables, encodingSizeInBytes = + let bodyResult_funcBody, errCodes, bodyResult_localVariables, encodingSizeInBytes = match xerBdResultOpt with - | Some bodyResult -> + | Some bodyResult -> bodyResult.funcBody, bodyResult.errCodes, bodyResult.localVariables, bodyResult.encodingSizeInBytes - | None -> - let emtyStatement = lm.lg.emtyStatement - emtyStatement, [], [], 0I + | None -> + let emptyStatement = lm.lg.emptyStatement + emptyStatement, [], [], 0I let lvars = bodyResult_localVariables |> List.map(fun (lv:LocalVariable) -> lm.lg.getLocalVariableDeclaration lv) |> Seq.distinct - let xerFunc = Some(emitTypeAssignment asn1TasName varName sStar funcName isValidFuncName (lm.lg.getLongTypedefName typeDefinition) lvars bodyResult_funcBody soSparkAnnotations sInitilialExp codec) + let xerFunc = Some(emitTypeAssignment asn1TasName varName sStar funcName isValidFuncName (lm.lg.getLongTypedefName typeDefinition) lvars bodyResult_funcBody soSparkAnnotations sInitialExp codec) let errCodStr = errCodes |> List.map(fun x -> (EmitTypeAssignment_def_err_code x.errCodeName) (BigInteger x.errCodeValue)) let xerFuncDef = Some(emitTypeAssignment_def varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) errCodStr (encodingSizeInBytes = 0I) (encodingSizeInBytes) soSparkAnnotations codec) xerFunc, xerFuncDef, encodingSizeInBytes - let ret = + let ret = { XerFunctionRec.funcName = funcName func = xerFunc @@ -118,16 +118,16 @@ let createXerFunction_any (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Comm let orElse defaultValue optValue = match optValue with Some x -> x | None -> defaultValue -let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let Integer = lm.xer.Integer let IntegerPos = lm.xer.IntegerPos - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "INTEGER") - let checkExp = + let checkExp = match (DastValidate2.createIntegerFunctionByCons r lm (o.intClass) (o.cons@o.withcons)) with | None -> None - | Some expFunc -> - let makeExpressionToStatement0 = lm.isvalid.makeExpressionToStatement0 + | Some expFunc -> + let makeExpressionToStatement0 = lm.isvalid.makeExpressionToStatement0 match expFunc p with | VCBTrue -> Some (makeExpressionToStatement0 "true") | VCBFalse -> Some (makeExpressionToStatement0 "false") @@ -139,7 +139,7 @@ let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Comm let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) let contentSize = getMaxSizeInBytesForXER_Integer () let totalSize = getMaxSizeInBytesForXER xmlTag contentSize - let bodyStm = + let bodyStm = match o.isUnsigned with | true -> IntegerPos pp xmlTag.p nLevel checkExp errCode.errCodeName codec | false -> Integer pp xmlTag.p nLevel checkExp errCode.errCodeName codec @@ -147,7 +147,7 @@ let createIntegerFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Comm let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let checkExp (isValidFunc: IsValidFunction option) p = +let checkExp (isValidFunc: IsValidFunction option) p = match isValidFunc with | None -> None | Some fnc -> None @@ -155,9 +155,9 @@ let checkExp (isValidFunc: IsValidFunction option) p = // | None -> None // | Some expFunc -> (Some (expFunc p)) -let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let Boolean = lm.xer.Boolean - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "") let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) @@ -168,13 +168,13 @@ let createBooleanFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Comm let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let Real = lm.xer.Real - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "REAL") let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let contentSize = getMaxSizeInBytesForXER_Real + let contentSize = getMaxSizeInBytesForXER_Real let totalSize = getMaxSizeInBytesForXER xmlTag contentSize let bodyStm = Real pp xmlTag.p nLevel (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=totalSize} @@ -182,35 +182,35 @@ let createRealFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonT createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let ObjectIdentifier = lm.xer.ObjectIdentifier - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "ObjectIdentifier") let pp = match codec with CommonTypes.Encode -> lm.lg.getPointer p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let contentSize = getMaxSizeInBytesForXER_Real + let contentSize = getMaxSizeInBytesForXER_Real let totalSize = getMaxSizeInBytesForXER xmlTag contentSize let bodyStm = ObjectIdentifier pp xmlTag.p nLevel (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let TimeType = lm.xer.TimeType - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "TIME") let pp = match codec with CommonTypes.Encode -> lm.lg.getPointer p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let contentSize = getMaxSizeInBytesForXER_Real + let contentSize = getMaxSizeInBytesForXER_Real let totalSize = getMaxSizeInBytesForXER xmlTag contentSize let bodyStm = TimeType pp (DAstUPer.getTimeSubTypeByClass o.timeClass) xmlTag.p nLevel (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.NullType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let nullFunc = lm.xer.Null - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let pp = match codec with CommonTypes.Encode -> lm.lg.getPointer p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let xmlTag = xmlTag |> orElse (XerLiteralConstant "NULL") let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) @@ -220,12 +220,12 @@ let createNullTypeFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Com let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let Enumerated = lm.xer.Enumerated let Enumerated_item = lm.xer.Enumerated_item - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "") - let pp = lm.lg.getValue p.arg + let pp = lm.lg.getValue p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) let contentSize = getMaxSizeInBytesForXER_Enumerated (o.items |> List.map (fun itm -> itm.Name.Value)) let totalSize = getMaxSizeInBytesForXER xmlTag contentSize @@ -236,9 +236,9 @@ let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:C let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let String = lm.xer.String - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant (if o.isNumeric then "NumericString" else "IA5String")) let pp = match codec with CommonTypes.Encode -> lm.lg.getValue p.arg | CommonTypes.Decode -> lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) @@ -249,52 +249,52 @@ let createIA5StringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Co let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let OctetString = lm.xer.OctetString - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "OCTET-STRING") let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) let contentSize = getMaxSizeInBytesForXER_OctetString o.maxSize.uper let totalSize = getMaxSizeInBytesForXER xmlTag contentSize - let bodyStm = OctetString p.arg.p (lm.lg.getAccess p.arg) xmlTag.p nLevel o.maxSize.uper (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec + let bodyStm = OctetString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) xmlTag.p nLevel o.maxSize.uper (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (us:State) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (us:State) = let BitString = lm.xer.BitString - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "BIT-STRING") let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) let contentSize = getMaxSizeInBytesForXER_BitString o.maxSize.uper let totalSize = getMaxSizeInBytesForXER xmlTag contentSize - let bodyStm = BitString p.arg.p (lm.lg.getAccess p.arg) xmlTag.p nLevel o.maxSize.uper (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec + let bodyStm = BitString (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) xmlTag.p nLevel o.maxSize.uper (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (child:Asn1Type) (us:State) = let SequenceOf = lm.xer.SequenceOf - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "SEQUENCE-OF") - let ii = t.id.SeqeuenceOfLevel + 1 + let ii = t.id.SequenceOfLevel + 1 let i = sprintf "i%d" ii - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) let pp = lm.lg.getPointer p.arg let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let chFunc = + let chFunc = match child.getXerFunction codec with | XerFunction z -> z | XerFunctionDummy -> raise (BugErrorException "XerFunctionDummy") - let childTag = - let definedInRTL = - match child.typeDefintionOrReference with + let childTag = + let definedInRTL = + match child.typeDefinitionOrReference with | TypeDefinition td -> false | ReferenceToExistingDefinition ref -> ref.definedInRtl match definedInRTL with | false -> - let childTagName = (child.typeDefintionOrReference).getAsn1Name r.args.TypePrefix + let childTagName = (child.typeDefinitionOrReference).getAsn1Name r.args.TypePrefix (Some (XerLiteralConstant childTagName)) | true -> None @@ -302,12 +302,12 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:C let internalItem_str, chLocalVars, chErrCodes, chSize = match internalItem with Some x -> x.funcBody, x.localVariables, x.errCodes, x.encodingSizeInBytes | None -> "",[],[],0I let contentSize = o.maxSize.uper * chSize let totalSize = getMaxSizeInBytesForXER xmlTag contentSize - let bodyStm = SequenceOf p.arg.p (lm.lg.getAccess p.arg) xmlTag.p nLevel i o.maxSize.uper internalItem_str (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec + let bodyStm = SequenceOf (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) xmlTag.p nLevel i o.maxSize.uper internalItem_str (o.minSize.uper=o.maxSize.uper) (checkExp isValidFunc p) errCode.errCodeName codec Some {XERFuncBodyResult.funcBody = bodyStm; errCodes= errCode::chErrCodes; localVariables=lv::chLocalVars;encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (us:State) = +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (children:SeqChildInfo list) (us:State) = let nestChildItems (lm:LanguageMacros) (codec:CommonTypes.Codec) children = DAstUtilFunctions.nestItems_ret lm children let sequence_mandatory_child = lm.xer.Sequence_mandatory_child let sequence_default_child = lm.xer.Sequence_default_child @@ -317,125 +317,125 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Com let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let xmlTag = xmlTag |> orElse (XerLiteralConstant "SEQUENCE") let nonAcnChildren = children |> List.choose(fun c -> match c with Asn1Child c -> Some c | AcnChild _ -> None) let handleChild (child:Asn1Child) = - let chFunc = + let chFunc = match child.Type.getXerFunction codec with | XerFunction z -> z | XerFunctionDummy -> raise (BugErrorException "XerFunctionDummy") - - let childContentResult = chFunc.funcBody ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) (Some (XerLiteralConstant child.Name.Value)) + let chP = {p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String child.Optionality.IsSome} + let childContentResult = chFunc.funcBody chP (Some (XerLiteralConstant child.Name.Value)) match childContentResult with | None -> None | Some childContent -> - let childBody, child_localVariables = + let childBody, child_localVariables = match child.Optionality with | None -> sequence_mandatory_child (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value codec, childContent.localVariables - //| Some Asn1AcnAst.AlwaysAbsent -> match codec with CommonTypes.Encode -> None | CommonTypes.Decode -> Some (sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) child.c_name childContent.funcBody codec) + //| Some Asn1AcnAst.AlwaysAbsent -> match codec with CommonTypes.Encode -> None | CommonTypes.Decode -> Some (sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) child.c_name childContent.funcBody codec) | Some Asn1AcnAst.AlwaysAbsent //-> "", [] - | Some Asn1AcnAst.AlwaysPresent -> sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value codec, childContent.localVariables - | Some (Asn1AcnAst.Optional opt) -> + | Some Asn1AcnAst.AlwaysPresent -> sequence_optional_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value codec, childContent.localVariables + | Some (Asn1AcnAst.Optional opt) -> match opt.defaultValue with - | None -> sequence_optional_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value codec, childContent.localVariables - | Some v -> - let defInit= child.Type.initFunction.initByAsn1Value ({p with arg = lm.lg.getSeqChild p.arg (lm.lg.getAsn1ChildBackendName child) child.Type.isIA5String false}) (mapValue v).kind - sequence_default_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value defInit codec, childContent.localVariables + | None -> sequence_optional_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value codec, childContent.localVariables + | Some v -> + let defInit= child.Type.initFunction.initByAsn1Value chP (mapValue v).kind + sequence_default_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.getAsn1ChildBackendName child) childContent.funcBody child.Name.Value defInit codec, childContent.localVariables Some (childBody, child_localVariables, childContent.errCodes, childContent.encodingSizeInBytes) - + let childrenStatements0 = nonAcnChildren |> List.choose handleChild let childrenStatements = childrenStatements0 |> List.map(fun (s,_,_,_) -> s) let childrenLocalvars = childrenStatements0 |> List.collect(fun (_,s,_,_) -> s) let childrenErrCodes = childrenStatements0 |> List.collect(fun (_,_,s,_) -> s) let contentSize = childrenStatements0 |> List.map(fun (_,_,_,s) -> s) |> List.fold (+) 0I - let startTag = sequence_start p.arg.p xmlTag.p nLevel errCode.errCodeName (childrenStatements |> Seq.isEmpty) codec + let startTag = sequence_start (p.arg.joined lm.lg) xmlTag.p nLevel errCode.errCodeName (childrenStatements |> Seq.isEmpty) codec let endTag = sequence_end xmlTag.p nLevel errCode.errCodeName codec - let seqContent = - let opt = (startTag::childrenStatements@[endTag]) |> nestChildItems lm codec + let seqContent = + let opt = (startTag::childrenStatements@[endTag]) |> nestChildItems lm codec match opt with | Some x -> x | None -> "" - + let totalSize = getMaxSizeInBytesForXER xmlTag contentSize Some {XERFuncBodyResult.funcBody = seqContent; errCodes= errCode::childrenErrCodes; localVariables=childrenLocalvars;encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (us:State) = +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (children:ChChildInfo list) (us:State) = let choice_child = lm.xer.CHOICE_child let choice_no_tag = lm.xer.CHOICE_no_tag let choice = lm.xer.CHOICE let typeDefinitionName = typeDefinition.longTypedefName2 lm.lg.hasModules let nLevel = BigInteger (t.id.AcnAbsPath.Length - 2) - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let handleChild childIndex (child:ChChildInfo) = - let chFunc = + let chFunc = match child.chType.getXerFunction codec with | XerFunction z -> z | XerFunctionDummy -> raise (BugErrorException "XerFunctionDummy") - let childContentResult = + let childContentResult = chFunc.funcBody ({p with arg = lm.lg.getChChild p.arg (lm.lg.getAsn1ChChildBackendName child) child.chType.isIA5String}) (Some (XerLiteralConstant child.Name.Value)) match childContentResult with | None -> None | Some childContent -> let sChildName = lm.lg.getAsn1ChChildBackendName child - let sChildTypeDef = lm.lg.getLongTypedefName child.chType.typeDefintionOrReference + let sChildTypeDef = lm.lg.getLongTypedefName child.chType.typeDefinitionOrReference let sChoiceTypeName = typeDefinitionName - let childBody = choice_child p.arg.p (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some typeDefinition) child) childContent.funcBody (childIndex = 0) child.Name.Value sChildName sChildTypeDef sChoiceTypeName codec + let childBody = choice_child (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) (lm.lg.presentWhenName (Some typeDefinition) child) childContent.funcBody (childIndex = 0) child.Name.Value sChildName sChildTypeDef sChoiceTypeName codec Some (childBody, childContent.localVariables, childContent.errCodes, childContent.encodingSizeInBytes) let childrenStatements0 = children |> List.mapi handleChild |> List.choose id let childrenStatements = childrenStatements0 |> List.map(fun (s,_,_,_) -> s) let childrenLocalvars = childrenStatements0 |> List.collect(fun (_,s,_,_) -> s) let childrenErrCodes = childrenStatements0 |> List.collect(fun (_,_,s,_) -> s) let contentSize = childrenStatements0 |> List.map(fun (_,_,_,s) -> s) |> List.fold max 0I - let no_tag_body = choice_no_tag p.arg.p (lm.lg.getAccess p.arg) childrenStatements errCode.errCodeName codec + let no_tag_body = choice_no_tag (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) childrenStatements errCode.errCodeName codec let chContent, totalSize = match xmlTag with | None -> no_tag_body, contentSize - | Some xmlTag -> - choice p.arg.p (lm.lg.getAccess p.arg) xmlTag.p nLevel no_tag_body errCode.errCodeName codec, getMaxSizeInBytesForXER xmlTag contentSize - + | Some xmlTag -> + choice (p.arg.joined lm.lg) (lm.lg.getAccess p.arg) xmlTag.p nLevel no_tag_body errCode.errCodeName codec, getMaxSizeInBytesForXER xmlTag contentSize + Some {XERFuncBodyResult.funcBody = chContent; errCodes= errCode::childrenErrCodes; localVariables=childrenLocalvars;encodingSizeInBytes=totalSize} let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us -let createReferenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = +let createReferenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:CommonTypes.Codec) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (isValidFunc: IsValidFunction option) (baseType:Asn1Type) (us:State) = let callBaseTypeFunc = lm.xer.call_base_type_func - let moduleName, typeDefinitionName0 = + let moduleName, typeDefinitionName0 = let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let typeDef = lm.lg.getTypeDefinition t1.FT_TypeDefintion + let typeDef = lm.lg.getTypeDefinition t1.FT_TypeDefinition typeDef.programUnit, typeDef.typeName - let baseTypeDefinitionName = + let baseTypeDefinitionName = match lm.lg.hasModules with - | false -> typeDefinitionName0 - | true -> + | false -> typeDefinitionName0 + | true -> match t.id.ModName = o.modName.Value with - | true -> typeDefinitionName0 - | false -> moduleName + "." + typeDefinitionName0 + | true -> typeDefinitionName0 + | false -> moduleName + "." + typeDefinitionName0 let baseFncName = baseTypeDefinitionName+ "_XER" + codec.suffix let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let t1WithExtensios = o.resolvedType; - - match TypesEquivalence.uperEquivalence t1 t1WithExtensios with + let t1WithExtensions = o.resolvedType; + + match TypesEquivalence.uperEquivalence t1 t1WithExtensions with | true -> - let funcBody (errCode:ErroCode) (p:CallerScope) (xmlTag:XerTag option) = + let funcBody (errCode:ErrorCode) (p:CallerScope) (xmlTag:XerTag option) = let baseTypeXerFunc = match baseType.getXerFunction codec with | XerFunction z -> z | XerFunctionDummy -> raise (BugErrorException "XerFunctionDummy") match baseTypeXerFunc.funcBody p xmlTag with - | Some baseXerFunc -> + | Some baseXerFunc -> let xmlTag = xmlTag |> orElse (XerLiteralConstant o.tasName.Value) let funcBodyContent = callBaseTypeFunc (lm.lg.getParamValue t p.arg codec) xmlTag.p baseFncName codec Some {XERFuncBodyResult.funcBody = funcBodyContent; errCodes= [errCode]; localVariables=[];encodingSizeInBytes=baseXerFunc.encodingSizeInBytes} @@ -443,5 +443,5 @@ let createReferenceFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (codec:Co let soSparkAnnotations = None createXerFunction_any r lm codec t typeDefinition isValidFunc funcBody soSparkAnnotations us - | false -> + | false -> baseType.getXerFunction codec, us diff --git a/BackendAst/DastFold.fs b/BackendAst/DastFold.fs index 4654fd20b..b87ad5614 100644 --- a/BackendAst/DastFold.fs +++ b/BackendAst/DastFold.fs @@ -8,31 +8,31 @@ open DAstUtilFunctions let foldMap = Asn1Fold.foldMap let foldAsn1Type - (t:Asn1Type) - (us:'UserState) - integerFunc - realFunc - ia5StringFunc - octetStringFunc - nullTypeFunc - bitStringFunc - booleanFunc - enumeratedFunc - objectIdentifierFunc - timeTypeFunc - seqOfTypeFunc - - seqAsn1ChildFunc - seqAcnChildFunc - seqTypeFunc - - chChild - chTypeFunc - refTypeFunc - typeFunc + (t:Asn1Type) + (us:'UserState) + (integerFunc: Asn1Type -> Integer -> 'UserState -> 'a) + (realFunc: Asn1Type -> Real -> 'UserState -> 'a) + (ia5StringFunc: Asn1Type -> StringType -> 'UserState -> 'a) + (octetStringFunc: Asn1Type -> OctetString -> 'UserState -> 'a) + (nullTypeFunc: Asn1Type -> NullType -> 'UserState -> 'a) + (bitStringFunc: Asn1Type -> BitString -> 'UserState -> 'a) + (booleanFunc: Asn1Type -> Boolean -> 'UserState -> 'a) + (enumeratedFunc: Asn1Type -> Enumerated -> 'UserState -> 'a) + (objectIdentifierFunc: Asn1Type -> ObjectIdentifier -> 'UserState -> 'a) + (timeTypeFunc: Asn1Type -> TimeType -> 'UserState -> 'a) + (seqOfTypeFunc: Asn1Type -> SequenceOf -> 'b -> 'a) + + (seqAsn1ChildFunc: Asn1Type -> Sequence -> Asn1Child -> 'b -> 'c * 'UserState) + (seqAcnChildFunc: Asn1Type -> Sequence -> AcnChild -> 'UserState -> 'c * 'UserState) + (seqTypeFunc: Asn1Type -> Sequence -> 'c list * 'UserState -> 'a) + + (chChild: Asn1Type -> Choice -> ChChildInfo -> 'b -> 'd * 'UserState) + (chTypeFunc: Asn1Type -> Choice -> 'd list * 'UserState -> 'a) + (refTypeFunc: Asn1Type -> ReferenceType -> 'b -> 'a) + (typeFunc: Asn1Type -> 'a -> 'b) : 'b = let rec loopType (t:Asn1Type) (us:'UserState) = - let newKind = + let newKind = match t.Kind with | Integer cnt -> integerFunc t cnt us | Real cnt -> realFunc t cnt us @@ -44,20 +44,19 @@ let foldAsn1Type | Enumerated cnt -> enumeratedFunc t cnt us | ObjectIdentifier cnt -> objectIdentifierFunc t cnt us | TimeType cnt -> timeTypeFunc t cnt us - | SequenceOf cnt -> + | SequenceOf cnt -> let newChildType = loopType cnt.childType us - seqOfTypeFunc t cnt newChildType - | Sequence seqInfo -> + seqOfTypeFunc t cnt newChildType + | Sequence seqInfo -> let newChildren = - seqInfo.children |> - foldMap (fun curState ch -> + seqInfo.children |> + foldMap (fun curState ch -> match ch with - | Asn1Child asn1Chlld -> seqAsn1ChildFunc t seqInfo asn1Chlld (loopType asn1Chlld.Type curState) + | Asn1Child asn1Child -> seqAsn1ChildFunc t seqInfo asn1Child (loopType asn1Child.Type curState) | AcnChild acnChild -> seqAcnChildFunc t seqInfo acnChild curState) us - //seqChild ch (loopType ch.chType curState)) us seqTypeFunc t seqInfo newChildren - | Choice chInfo -> + | Choice chInfo -> let newChildren = chInfo.children |> foldMap (fun curState ch -> chChild t chInfo ch (loopType ch.chType curState)) us chTypeFunc t chInfo newChildren | ReferenceType ref -> @@ -78,39 +77,3 @@ let getValueFromSizeableConstraint (c:SizableTypeConstraint<'v>) = (fun _ intCon s -> [],s) c 0 |> fst - -(* -let rec getOctetStringValues (t:Asn1Type) = - seq { - match t.Kind with - | OctetString o -> - let octVals = (o.baseInfo.cons@o.baseInfo.withcons) |> List.map getValueFromSizeableConstraint |> List.collect id - yield! octVals - | Sequence seq -> - for ch in seq.Asn1Children do - yield! getOctetStringValues ch.Type - | Choice ch -> - for ch in ch.children do - yield! getOctetStringValues ch.chType - | SequenceOf ch -> - yield! getOctetStringValues ch.childType - | _ -> () - } |> Seq.toList - -let rec getBitStringValues (t:Asn1Type) = - seq { - match t.Kind with - | BitString o -> - let octVals = (o.baseInfo.cons@o.baseInfo.withcons) |> List.map getValueFromSizeableConstraint |> List.collect id - yield! octVals - | Sequence seq -> - for ch in seq.Asn1Children do - yield! getBitStringValues ch.Type - | Choice ch -> - for ch in ch.children do - yield! getBitStringValues ch.chType - | SequenceOf ch -> - yield! getBitStringValues ch.childType - | _ -> () - } |> Seq.toList -*) \ No newline at end of file diff --git a/BackendAst/DastTestCaseCreation.fs b/BackendAst/DastTestCaseCreation.fs index d805748ee..e08a3ce48 100644 --- a/BackendAst/DastTestCaseCreation.fs +++ b/BackendAst/DastTestCaseCreation.fs @@ -11,19 +11,19 @@ open DAstUtilFunctions open Language -let GetEncodingString (lm:LanguageMacros) = function +let GetEncodingString (lm:LanguageMacros) = function | UPER -> lm.lg.atc.uperPrefix | ACN -> lm.lg.atc.acnPrefix | BER -> lm.lg.atc.berPrefix | XER -> lm.lg.atc.xerPrefix -let includedPackages r (lm:LanguageMacros) = +let includedPackages r (lm:LanguageMacros) = match lm.lg.hasModules with | false -> r.programUnits |> Seq.map(fun x -> x.testcase_specFileName) | true -> r.programUnits |> Seq.collect(fun x -> [x.name; x.testcase_name]) -let rec gAmber (t:Asn1Type) = +let rec gAmber (t:Asn1Type) = match t.Kind with | Integer _ -> "&" , "&" | Real _ -> "&" , "&" @@ -42,13 +42,13 @@ let rec gAmber (t:Asn1Type) = let emitTestCaseAsFunc (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc let emitTestCaseAsFunc_h (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc_h -let invokeTestCaseAsFunc (lm:LanguageMacros) = lm.atc.invokeTestCaseAsFunc -let emitTestCaseAsFunc_dummy_init (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc_dummy_init -let emitTestCaseAsFunc_dummy_init_function (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc_dummy_init_function +let invokeTestCaseAsFunc (lm:LanguageMacros) = lm.atc.invokeTestCaseAsFunc +let emitTestCaseAsFunc_dummy_init (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc_dummy_init +let emitTestCaseAsFunc_dummy_init_function (lm:LanguageMacros) = lm.atc.emitTestCaseAsFunc_dummy_init_function -let GetDatFile (r:DAst.AstRoot) lm (v:ValueAssignment) modName sTasName encAmper (enc:Asn1Encoding) = - let generate_dat_file = lm.atc.PrintSuite_call_codec_generate_dat_file +let GetDatFile (r:DAst.AstRoot) lm (v:ValueAssignment) modName sTasName encAmper (enc:Asn1Encoding) = + let generate_dat_file = lm.atc.PrintSuite_call_codec_generate_dat_file let bGenerateDatFile = (r.args.CheckWithOss && v.Name.Value = "testPDU") match bGenerateDatFile, enc with | false,_ -> "" @@ -60,7 +60,7 @@ let GetDatFile (r:DAst.AstRoot) lm (v:ValueAssignment) modName sTasName encAmper let PrintValueAssignmentAsTestCase (r:DAst.AstRoot) lm (e:Asn1Encoding) (v:ValueAssignment) (m:Asn1Module) (typeModName:string) (sTasName : string) (idx :int) dummyInitStatementsNeededForStatementCoverage = let modName = typeModName//ToC m.Name.Value let sFuncName = sprintf "test_case_%A_%06d" e idx - let encAmper, initAmper = gAmber v.Type + let encAmper, initAmper = gAmber v.Type let initAmper = match ST.lang with | Scala -> @@ -74,28 +74,29 @@ let PrintValueAssignmentAsTestCase (r:DAst.AstRoot) lm (e:Asn1Encoding) (v:Value match ST.lang with | Scala -> match resolveReferenceType v.Type.Kind with - | Integer v -> "tc_data = " + initStatement - | Real v -> initStatement - | IA5String v -> initStatement - | OctetString v -> initStatement - | NullType v -> initStatement - | BitString v -> initStatement - | Boolean v -> initStatement - | Enumerated v -> initStatement + | Integer v -> "tc_data = " + initStatement + | Real v -> initStatement + | IA5String v -> initStatement + | OctetString v -> initStatement + | NullType v -> initStatement + | BitString v -> initStatement + | Boolean v -> initStatement + | Enumerated v -> initStatement | ObjectIdentifier v -> initStatement - | SequenceOf v -> initStatement - | Sequence v -> initStatement - | Choice v -> initStatement - | TimeType v -> initStatement + | SequenceOf v -> initStatement + | Sequence v -> initStatement + | Choice v -> initStatement + | TimeType v -> initStatement + | ReferenceType _ -> raise (BugErrorException "Impossible, since we have resolvedReferenceType") | _ -> initStatement let sTestCaseIndex = idx.ToString() let bStatic = match v.Type.ActualType.Kind with Integer _ | Enumerated(_) -> false | _ -> true let GetDatFile = GetDatFile r lm v modName sTasName encAmper let func_def = emitTestCaseAsFunc_h lm sFuncName - let func_dody = emitTestCaseAsFunc lm sFuncName [] modName sTasName encAmper (GetEncodingString lm e) true initStatement bStatic "" dummyInitStatementsNeededForStatementCoverage initAmper - let func_invokation = invokeTestCaseAsFunc lm sFuncName - (func_def, func_dody, func_invokation) - + let func_body = emitTestCaseAsFunc lm sFuncName [] modName sTasName encAmper (GetEncodingString lm e) true initStatement bStatic "" dummyInitStatementsNeededForStatementCoverage initAmper + let func_invocation = invokeTestCaseAsFunc lm sFuncName + (func_def, func_body, func_invocation) + let PrintAutomaticTestCase (r:DAst.AstRoot) (lm:LanguageMacros) (e:Asn1Encoding) (initStatement:String) (localVars : LocalVariable list) (m:Asn1Module) (t:Asn1Type) (modName : string) (sTasName : string) (idx :int) initFuncName = let sFuncName = sprintf "test_case_%A_%06d" e idx //let modName = ToC m.Name.Value @@ -113,18 +114,18 @@ let PrintAutomaticTestCase (r:DAst.AstRoot) (lm:LanguageMacros) (e:Asn1Encoding) let GetDatFile = "" let sTestCaseIndex = idx.ToString() let func_def = emitTestCaseAsFunc_h lm sFuncName - let func_dody = emitTestCaseAsFunc lm sFuncName arrsVars modName sTasName encAmper (GetEncodingString lm e) false initStatement bStatic "" initFuncName initAmper - let func_invokation = invokeTestCaseAsFunc lm sFuncName - (func_def, func_dody, func_invokation) + let func_body = emitTestCaseAsFunc lm sFuncName arrsVars modName sTasName encAmper (GetEncodingString lm e) false initStatement bStatic "" initFuncName initAmper + let func_invocation = invokeTestCaseAsFunc lm sFuncName + (func_def, func_body, func_invocation) let getTypeDecl (r:DAst.AstRoot) (vasPU_name:string) (lm:LanguageMacros) (vas:ValueAssignment) = let t = vas.Type match t.Kind with | Integer _ | Real _ - | Boolean _ -> lm.lg.getLongTypedefName t.typeDefintionOrReference + | Boolean _ -> lm.lg.getLongTypedefName t.typeDefinitionOrReference | ReferenceType ref -> - let tasName = ToC2(r.args.TypePrefix + ref.baseInfo.tasName.Value) + let tasName = ToC2(r.args.TypePrefix + ref.baseInfo.tasName.Value) match lm.lg.hasModules with | false -> tasName | true -> @@ -132,18 +133,18 @@ let getTypeDecl (r:DAst.AstRoot) (vasPU_name:string) (lm:LanguageMacros) (vas:Va | true -> tasName |false -> (ToC ref.baseInfo.modName.Value) + "." + tasName - - | _ -> + + | _ -> match t.tasInfo with - | Some tasInfo -> ToC2(r.args.TypePrefix + tasInfo.tasName) - | None -> lm.lg.getLongTypedefName t.typeDefintionOrReference + | Some tasInfo -> ToC2(r.args.TypePrefix + tasInfo.tasName) + | None -> lm.lg.getLongTypedefName t.typeDefinitionOrReference let TestSuiteFileName = "testsuite" let emitDummyInitStatementsNeededForStatementCoverage (lm:Language.LanguageMacros) (t:Asn1Type) = - let pdumy = {CallerScope.modName = ToC "MainProgram"; arg = VALUE "tmp0"} + let pdummy = {CallerScope.modName = ToC "MainProgram"; arg = Selection.valueEmptyPath "tmp0" } let rec getInitializationFunctions (n:InitFunction) = seq { for c in n.nonEmbeddedChildrenFuncs do @@ -151,33 +152,33 @@ let emitDummyInitStatementsNeededForStatementCoverage (lm:Language.LanguageMacro yield n } |> Seq.toList let actualInitFuncNames = - getInitializationFunctions t.initFunction |> + getInitializationFunctions t.initFunction |> List.choose (fun i -> match i.initProcedure with | None -> None | Some initProc -> Some initProc.funcName) |> Set.ofList - GetMySelfAndChildren2 lm t pdumy |> - List.choose(fun (t,p) -> + GetMySelfAndChildren2 lm t pdummy |> + List.choose(fun (t,p) -> let initProc = t.initFunction.initProcedure - let dummyVarName = + let dummyVarName = match t.isIA5String with | true -> lm.lg.getValue p.arg | false -> lm.lg.getPointer p.arg - let sTypeName = lm.lg.getLongTypedefName t.typeDefintionOrReference - let sTypeName = + let sTypeName = lm.lg.getLongTypedefName t.typeDefinitionOrReference + let sTypeName = match lm.lg.hasModules with | false -> sTypeName - | true -> + | true -> match sTypeName.Contains "." with | true -> sTypeName - | false -> - (lm.lg.getTypeDefinition t.FT_TypeDefintion).programUnit + "." + sTypeName + | false -> + (lm.lg.getTypeDefinition t.FT_TypeDefinition).programUnit + "." + sTypeName match initProc with | None -> None - | Some initProc when actualInitFuncNames.Contains initProc.funcName -> - match lm.lg.initMetod with + | Some initProc when actualInitFuncNames.Contains initProc.funcName -> + match lm.lg.initMethod with | InitMethod.Procedure -> Some (emitTestCaseAsFunc_dummy_init lm sTypeName initProc.funcName dummyVarName) | InitMethod.Function -> @@ -186,7 +187,7 @@ let emitDummyInitStatementsNeededForStatementCoverage (lm:Language.LanguageMacro let printAllTestCasesAndTestCaseRunner (r:DAst.AstRoot) (lm:LanguageMacros) outDir = - let tcFunctors = + let tcFunctors = seq { for m in r.Files |> List.collect(fun f -> f.Modules) do for e in r.args.encodings do @@ -194,7 +195,7 @@ let printAllTestCasesAndTestCaseRunner (r:DAst.AstRoot) (lm:LanguageMacros) outD let encDecTestFunc = t.Type.getEncDecTestFunc e match encDecTestFunc with | Some _ -> - let hasEncodeFunc = e <> Asn1Encoding.ACN || hasAcnEncodeFunction t.Type.acnEncFunction t.Type.acnParameters + let hasEncodeFunc = e <> Asn1Encoding.ACN || hasAcnEncodeFunction t.Type.acnEncFunction t.Type.acnParameters if hasEncodeFunc then let isTestCaseValid atc = match t.Type.acnEncFunction with @@ -203,28 +204,26 @@ let printAllTestCasesAndTestCaseRunner (r:DAst.AstRoot) (lm:LanguageMacros) outD for atc in t.Type.initFunction.automaticTestCases do let testCaseIsValid = e <> Asn1Encoding.ACN || (isTestCaseValid atc) if testCaseIsValid then - let generateTcFun idx = - let p = {CallerScope.modName = ToC "MainProgram"; arg = VALUE "tc_data"} + let generateTcFun idx = + let p = {CallerScope.modName = ToC "MainProgram"; arg = Selection.valueEmptyPath "tc_data"} let initStatement = atc.initTestCaseFunc p let dummyInitStatementsNeededForStatementCoverage = (emitDummyInitStatementsNeededForStatementCoverage lm t.Type)//t.Type.initFunction.initFuncName - - PrintAutomaticTestCase r lm e initStatement.funcBody initStatement.localVariables m t.Type ((lm.lg.getTypeDefinition t.Type.FT_TypeDefintion).programUnit) ((lm.lg.getTypeDefinition t.Type.FT_TypeDefintion).typeName) idx dummyInitStatementsNeededForStatementCoverage + + PrintAutomaticTestCase r lm e initStatement.funcBody initStatement.localVariables m t.Type ((lm.lg.getTypeDefinition t.Type.FT_TypeDefinition).programUnit) ((lm.lg.getTypeDefinition t.Type.FT_TypeDefinition).typeName) idx dummyInitStatementsNeededForStatementCoverage yield generateTcFun - | None -> () + | None -> () for v in m.ValueAssignments do - let encDecTestFunc, typeModName, tasName = + let encDecTestFunc, typeModName, tasName = match v.Type.Kind with | ReferenceType ref -> ref.resolvedType.getEncDecTestFunc e, (ToC ref.baseInfo.modName.Value), (ToC2(r.args.TypePrefix + ref.baseInfo.tasName.Value) ) - | _ -> v.Type.getEncDecTestFunc e, (ToC m.Name.Value), lm.lg.getLongTypedefName v.Type.typeDefintionOrReference + | _ -> v.Type.getEncDecTestFunc e, (ToC m.Name.Value), lm.lg.getLongTypedefName v.Type.typeDefinitionOrReference match encDecTestFunc with | Some _ -> - let generateTcFun idx = - //if (v.Name.Value = "apid") then - // printfn "debug" + let generateTcFun idx = let dummyInitStatementsNeededForStatementCoverage = (emitDummyInitStatementsNeededForStatementCoverage lm v.Type) - PrintValueAssignmentAsTestCase r lm e v m typeModName tasName (*(getTypeDecl r (ToC m.Name.Value) l v )*) idx dummyInitStatementsNeededForStatementCoverage + PrintValueAssignmentAsTestCase r lm e v m typeModName tasName (*(getTypeDecl r (ToC m.Name.Value) l v )*) idx dummyInitStatementsNeededForStatementCoverage yield generateTcFun | None -> () } |> Seq.toList @@ -237,56 +236,55 @@ let printAllTestCasesAndTestCaseRunner (r:DAst.AstRoot) (lm:LanguageMacros) outD let printTestCaseFileBody = lm.atc.printTestCaseFileBody let arrsSrcTstFiles, arrsHdrTstFiles = - [1 .. nFiles] |> + [1 .. nFiles] |> List.map (fun fileIndex -> let testCaseFileName = sprintf "test_case_%03d" fileIndex - testCaseFileName + "." + lm.lg.BodyExtention, testCaseFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention) |> + testCaseFileName + "." + lm.lg.BodyExtension, testCaseFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension) |> List.unzip - - [1 .. nFiles] |> + + [1 .. nFiles] |> List.iter (fun fileIndex -> - let arrsTestFunctionDefs, arrsTestFunctionBodies,_ = - tcFunctors |> - Seq.mapi (fun i f -> i+1,f) |> + let arrsTestFunctionDefs, arrsTestFunctionBodies,_ = + tcFunctors |> + Seq.mapi (fun i f -> i+1,f) |> Seq.filter(fun (i,_) -> i > nMaxTestCasesPerFile * (fileIndex-1) && i <= nMaxTestCasesPerFile * fileIndex) |> Seq.map(fun (i, fnc) -> fnc i) |> Seq.toList |> List.unzip3 - + let testCaseFileName = sprintf "test_case_%03d" fileIndex let contentC = printTestCaseFileBody testCaseFileName (includedPackages r lm) arrsTestFunctionBodies - let outCFileName = Path.Combine(outDir, testCaseFileName + "." + lm.lg.BodyExtention) + let outCFileName = Path.Combine(outDir, testCaseFileName + "." + lm.lg.BodyExtension) File.WriteAllText(outCFileName, contentC.Replace("\r","")) let contentH = printTestCaseFileDef testCaseFileName (includedPackages r lm) arrsTestFunctionDefs - let outHFileName = Path.Combine(outDir, testCaseFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention) + let outHFileName = Path.Combine(outDir, testCaseFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension) File.WriteAllText(outHFileName, contentH.Replace("\r","")) ) - let _, _, func_invokations = + let _, _, func_invocations = tcFunctors |> - Seq.mapi (fun i f -> i+1,f) |> + Seq.mapi (fun i f -> i+1,f) |> Seq.map(fun (i, fnc) -> fnc i) |> Seq.toList |> List.unzip3 let includedPackages = - [1 .. nFiles] |> + [1 .. nFiles] |> List.map (fun fileIndex -> sprintf "test_case_%03d" fileIndex ) let contentH = lm.atc.PrintATCRunnerDefinition() let hasTestSuiteRunner = not (String.IsNullOrWhiteSpace contentH) - let contentC = lm.atc.PrintATCRunner TestSuiteFileName includedPackages [] func_invokations [] [] false - let outCFileName = + let contentC = lm.atc.PrintATCRunner TestSuiteFileName includedPackages [] func_invocations [] [] false + let outCFileName = match hasTestSuiteRunner with - | true -> Path.Combine(outDir, TestSuiteFileName + "." + lm.lg.BodyExtention) - | false -> Path.Combine(outDir, "mainprogram" + "." + lm.lg.BodyExtention) + | true -> Path.Combine(outDir, TestSuiteFileName + "." + lm.lg.BodyExtension) + | false -> Path.Combine(outDir, "mainprogram" + "." + lm.lg.BodyExtension) File.WriteAllText(outCFileName, contentC.Replace("\r","")) if hasTestSuiteRunner then - let outHFileName = Path.Combine(outDir, TestSuiteFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtention) + let outHFileName = Path.Combine(outDir, TestSuiteFileName + lm.lg.SpecNameSuffix + "." + lm.lg.SpecExtension) File.WriteAllText(outHFileName, contentH.Replace("\r","")) arrsSrcTstFiles, arrsHdrTstFiles - //tcFunctors |> Seq.mapi (fun i fnc -> fnc i) - + diff --git a/BackendAst/DastValidate2.fs b/BackendAst/DastValidate2.fs index b6eb6e70b..e89556c64 100644 --- a/BackendAst/DastValidate2.fs +++ b/BackendAst/DastValidate2.fs @@ -24,23 +24,23 @@ let printGenericConAsAsn1 valToStrFunc (c:Asn1AcnAst.GenericConstraint<'v>) (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc v) ,s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc v) ,s) c 0 |> fst let printRangeConAsAsn1 valToStrFunc (c:Asn1AcnAst.RangeTypeConstraint<'v1,'v1>) = - Asn1Fold.foldRangeTypeConstraint + Asn1Fold.foldRangeTypeConstraint (fun _ e1 e2 b s -> stg_asn1.Print_UnionConstraint e1 e2, s) (fun _ e1 e2 s -> stg_asn1.Print_IntersectionConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_AllExceptConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_ExceptConstraint e1 e2, s) (fun _ e s -> stg_asn1.Print_RootConstraint e, s) (fun _ e1 e2 s -> stg_asn1.Print_RootConstraint2 e1 e2, s) - (fun _ v s -> stg_asn1.Print_SingleValueContraint (valToStrFunc v) ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> - stg_asn1.Print_RangeContraint (valToStrFunc v1) (valToStrFunc v2) minIsIn maxIsIn, s) - (fun _ v1 minIsIn s -> stg_asn1.Print_RangeContraint_val_MAX (valToStrFunc v1) minIsIn, s) - (fun _ v2 maxIsIn s -> stg_asn1.Print_RangeContraint_MIN_val (valToStrFunc v2) maxIsIn, s) + (fun _ v s -> stg_asn1.Print_SingleValueConstraint (valToStrFunc v) ,s) + (fun _ v1 v2 minIsIn maxIsIn s -> + stg_asn1.Print_RangeConstraint (valToStrFunc v1) (valToStrFunc v2) minIsIn maxIsIn, s) + (fun _ v1 minIsIn s -> stg_asn1.Print_RangeConstraint_val_MAX (valToStrFunc v1) minIsIn, s) + (fun _ v2 maxIsIn s -> stg_asn1.Print_RangeConstraint_MIN_val (valToStrFunc v2) maxIsIn, s) c 0 |> fst @@ -53,9 +53,9 @@ let ValidationBlockAsStringExpr = function let ValidationCodeBlock_OR (lm:LanguageMacros) vp1 vp2 = - let expressionOrStament = lm.isvalid.ExpressionOrStament + let expressionOrStatement = lm.isvalid.ExpressionOrStatement let statementOrExpression = lm.isvalid.StatementOrExpression - let statementOrStament = lm.isvalid.StatementOrStament + let statementOrStatement = lm.isvalid.StatementOrStatement let expOr = lm.isvalid.ExpOr match vp1, vp2 with | VCBTrue, _ -> VCBTrue @@ -63,27 +63,27 @@ let ValidationCodeBlock_OR (lm:LanguageMacros) vp1 vp2 = | VCBFalse, _ -> vp2 | _, VCBFalse -> vp1 | VCBExpression sExp1, VCBExpression sExp2 -> VCBExpression (expOr sExp1 sExp2) - | VCBExpression sExp1, VCBStatement (sStat2, lv2) -> VCBStatement(expressionOrStament sExp1 sStat2, lv2) + | VCBExpression sExp1, VCBStatement (sStat2, lv2) -> VCBStatement(expressionOrStatement sExp1 sStat2, lv2) | VCBStatement (sStat1, lv1), VCBExpression sExp2 -> VCBStatement(statementOrExpression sStat1 sExp2, lv1) - | VCBStatement (sStat1, lv1), VCBStatement (sStat2,lv2) -> VCBStatement(statementOrStament sStat1 sStat2, lv1@lv2) + | VCBStatement (sStat1, lv1), VCBStatement (sStat2,lv2) -> VCBStatement(statementOrStatement sStat1 sStat2, lv1@lv2) let ValidationCodeBlock_AND (lm:LanguageMacros) vp1 vp2 = - let expressionAndStament = lm.isvalid.ExpressionAndStament - let statementAndExpression = lm.isvalid.StatementAndExpression - let statementAndStament = lm.isvalid.StatementAndStament + let expressionAndStatement = lm.isvalid.ExpressionAndStatement + let statementAndExpression = lm.isvalid.StatementAndExpression + let statementAndStatement = lm.isvalid.StatementAndStatement match vp1, vp2 with | VCBTrue, _ -> vp2 | _,VCBTrue -> vp1 | VCBFalse, _ -> VCBFalse | _, VCBFalse -> VCBFalse | VCBExpression sExp1, VCBExpression sExp2 -> VCBExpression (lm.isvalid.ExpAnd sExp1 sExp2) - | VCBExpression sExp1, VCBStatement (sStat2,lv2) -> VCBStatement(expressionAndStament sExp1 sStat2, lv2) + | VCBExpression sExp1, VCBStatement (sStat2,lv2) -> VCBStatement(expressionAndStatement sExp1 sStat2, lv2) | VCBStatement (sStat1, lv1), VCBExpression sExp2 -> VCBStatement(statementAndExpression sStat1 sExp2, lv1) - | VCBStatement (sStat1, lv1), VCBStatement (sStat2,lv2) -> VCBStatement(statementAndStament sStat1 sStat2, lv1@lv2) + | VCBStatement (sStat1, lv1), VCBStatement (sStat2,lv2) -> VCBStatement(statementAndStatement sStat1 sStat2, lv1@lv2) let ValidationCodeBlock_Multiple_And (lm:LanguageMacros) (vpList:ValidationCodeBlock list) = - let makeExpressionToStatement0 = lm.isvalid.makeExpressionToStatement0 - let expAndMulti = lm.isvalid.ExpAndMulit + let makeExpressionToStatement0 = lm.isvalid.makeExpressionToStatement0 + let expAndMulti = lm.isvalid.ExpAndMulti match vpList |> Seq.exists((=) VCBFalse) with | true -> VCBFalse | false -> @@ -91,9 +91,9 @@ let ValidationCodeBlock_Multiple_And (lm:LanguageMacros) (vpList:ValidationCode let bAllAreExpressions = false//vpList |> Seq.forall(fun z -> match z with VCBExpression _ -> true | _ -> false ) match bAllAreExpressions with | true -> VCBExpression (expAndMulti (vpList |> List.map(fun z -> match z with VCBExpression s -> s | VCBStatement (s,_) -> s | _ -> "invalid"))) - | false -> + | false -> let soJoinedStatement, lv = - let children, lv = + let children, lv = vpList |> List.map(fun z -> match z with VCBExpression s -> makeExpressionToStatement0 s, [] | VCBStatement s -> s | _ -> "invalid", []) |> List.unzip @@ -104,7 +104,7 @@ let ValidationCodeBlock_Multiple_And (lm:LanguageMacros) (vpList:ValidationCode let ValidationCodeBlock_Not (lm:LanguageMacros) vp = let statementNot = lm.isvalid.StatementNot - let expNot = lm.isvalid.ExpNot + let expNot = lm.isvalid.ExpNot match vp with | VCBTrue -> VCBFalse @@ -113,7 +113,7 @@ let ValidationCodeBlock_Not (lm:LanguageMacros) vp = | VCBStatement (sStat, lv) -> VCBStatement ((statementNot sStat), lv) -let convertVCBToStatementAndAssigneErrCode (lm:LanguageMacros) vp sErrCode = +let convertVCBToStatementAndAssignedErrCode (lm:LanguageMacros) vp sErrCode = let convertVCBExpressionToStatementAndUpdateErrCode = lm.isvalid.convertVCBExpressionToStatementAndUpdateErrCode let convertVCBStatementToStatementAndUpdateErrCode = lm.isvalid.convertVCBStatementToStatementAndUpdateErrCode let convertVCBTRUEToStatementAndUpdateErrCode = lm.isvalid.convertVCBTRUEToStatementAndUpdateErrCode @@ -127,9 +127,9 @@ let convertVCBToStatementAndAssigneErrCode (lm:LanguageMacros) vp sErrCode = let ValidationCodeBlock_Except (lm:LanguageMacros) vp1 vp2 = // vp1 and (not vp2) - let expressionExceptStament = lm.isvalid.ExpressionExceptStament + let expressionExceptStatement = lm.isvalid.ExpressionExceptStatement let statementExceptExpression = lm.isvalid.StatementExceptExpression - let statementExceptStament = lm.isvalid.StatementExceptStament + let statementExceptStatement = lm.isvalid.StatementExceptStatement let expAnd = lm.isvalid.ExpAnd let expNot = lm.isvalid.ExpNot match vp1, vp2 with @@ -138,26 +138,26 @@ let ValidationCodeBlock_Except (lm:LanguageMacros) vp1 vp2 = | VCBFalse, _ -> VCBFalse | _, VCBFalse -> vp1 | VCBExpression sExp1, VCBExpression sExp2 -> VCBExpression (expAnd sExp1 (expNot sExp2)) - | VCBExpression sExp1, VCBStatement (sStat2, lv2) -> VCBStatement(expressionExceptStament sExp1 sStat2, lv2) + | VCBExpression sExp1, VCBStatement (sStat2, lv2) -> VCBStatement(expressionExceptStatement sExp1 sStat2, lv2) | VCBStatement (sStat1, lv1), VCBExpression sExp2 -> VCBStatement(statementExceptExpression sStat1 sExp2, lv1) - | VCBStatement (sStat1, lv1), VCBStatement (sStat2, lv2) -> VCBStatement(statementExceptStament sStat1 sStat2, lv1@lv2) + | VCBStatement (sStat1, lv1), VCBStatement (sStat2, lv2) -> VCBStatement(statementExceptStatement sStat1 sStat2, lv1@lv2) let Lte (lm:LanguageMacros) eqIsInc e1 e2 = match eqIsInc with - | true -> lm.isvalid.ExpLte e1 e2 + | true -> lm.isvalid.ExpLte e1 e2 | false -> lm.isvalid.ExpLt e1 e2 let con_or l _ (e1 : CallerScope -> ValidationCodeBlock) (e2 : CallerScope -> ValidationCodeBlock) b s = (fun p -> ValidationCodeBlock_OR l (e1 p) (e2 p)), s let con_and lm _ (e1 : CallerScope -> ValidationCodeBlock) (e2 : CallerScope -> ValidationCodeBlock) s = (fun p -> ValidationCodeBlock_AND lm (e1 p) (e2 p)), s let con_not lm _ (e : CallerScope -> ValidationCodeBlock) s = (fun p -> ValidationCodeBlock_Not lm (e p)), s -let con_ecxept lm _ (e1 : CallerScope -> ValidationCodeBlock) (e2 : CallerScope -> ValidationCodeBlock) s = (fun p -> ValidationCodeBlock_Except lm (e1 p) (e2 p)), s +let con_except lm _ (e1 : CallerScope -> ValidationCodeBlock) (e2 : CallerScope -> ValidationCodeBlock) s = (fun p -> ValidationCodeBlock_Except lm (e1 p) (e2 p)), s let con_root _ e s = e,s let con_root2 lm _ (e1 : CallerScope -> ValidationCodeBlock) (e2 : CallerScope -> ValidationCodeBlock) s = (fun p -> ValidationCodeBlock_OR lm (e1 p) (e2 p)), s (* e.g. INTEGER (v1..MAX) ==> v1 <= p.p *) -let con_rangeContraint_val_MAX (lm:LanguageMacros) minint maxint v1 eqIsInc valToStrFunc pToStrFunc = +let con_rangeConstraint_val_MAX (lm:LanguageMacros) minint maxint v1 eqIsInc valToStrFunc pToStrFunc = match v1 < minint with | true -> fun (p:CallerScope) -> VCBTrue (* e.g. for unsigned integer (-40 .. MAX) *) | false when v1 = minint && eqIsInc -> fun (p:CallerScope) -> VCBTrue @@ -165,7 +165,7 @@ let con_rangeContraint_val_MAX (lm:LanguageMacros) minint maxint v1 eqIsInc val (* e.g INTEGER (MIN .. v1) --> p.p <= v1 *) -let con_angeContraint_MIN_val (lm:LanguageMacros) minint maxint v1 eqIsInc valToStrFunc pToStrFunc = +let con_rangeConstraint_MIN_val (lm:LanguageMacros) minint maxint v1 eqIsInc valToStrFunc pToStrFunc = match v1 > maxint with | true -> fun (p:CallerScope) -> VCBTrue (* e.g. for unsigned integer (MIN .. value_larger_than_maxint) *) | false when v1 = maxint && eqIsInc -> fun (p:CallerScope) -> VCBTrue @@ -173,30 +173,30 @@ let con_angeContraint_MIN_val (lm:LanguageMacros) minint maxint v1 eqIsInc valT let foldGenericCon (lm:LanguageMacros) valToStrFunc (c:GenericConstraint<'v>) st = - foldGenericConstraint (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) + foldGenericConstraint (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) (fun _ v s -> (fun p -> VCBExpression (lm.isvalid.ExpEqual (lm.lg.getValue p.arg) (valToStrFunc v))) ,s) c st -let foldSizeRangeTypeConstraint (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) getSizeFunc (c:PosIntTypeConstraint) st = +let foldSizeRangeTypeConstraint (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) getSizeFunc (c:PosIntTypeConstraint) st = let valToStrFunc (v:UInt32) = v.ToString() - foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) + foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) (fun _ v (s:State) -> (fun p -> VCBExpression (lm.isvalid.ExpEqual (getSizeFunc lm p) (valToStrFunc v))) ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> - let exp1 = con_rangeContraint_val_MAX lm UInt32.MinValue UInt32.MaxValue v1 minIsIn valToStrFunc getSizeFunc - let exp2 = con_angeContraint_MIN_val lm UInt32.MinValue UInt32.MaxValue v2 maxIsIn valToStrFunc getSizeFunc + (fun _ v1 v2 minIsIn maxIsIn s -> + let exp1 = con_rangeConstraint_val_MAX lm UInt32.MinValue UInt32.MaxValue v1 minIsIn valToStrFunc getSizeFunc + let exp2 = con_rangeConstraint_MIN_val lm UInt32.MinValue UInt32.MaxValue v2 maxIsIn valToStrFunc getSizeFunc con_and lm s exp1 exp2 s) - (fun asn1 v1 minIsIn s -> con_rangeContraint_val_MAX lm UInt32.MinValue UInt32.MaxValue v1 minIsIn valToStrFunc getSizeFunc, s) - (fun asn1 v2 maxIsIn s -> con_angeContraint_MIN_val lm UInt32.MinValue UInt32.MaxValue v2 maxIsIn valToStrFunc getSizeFunc, s) + (fun asn1 v1 minIsIn s -> con_rangeConstraint_val_MAX lm UInt32.MinValue UInt32.MaxValue v1 minIsIn valToStrFunc getSizeFunc, s) + (fun asn1 v2 maxIsIn s -> con_rangeConstraint_MIN_val lm UInt32.MinValue UInt32.MaxValue v2 maxIsIn valToStrFunc getSizeFunc, s) c st let foldSizableConstraint (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) hasCount compareSingValueFunc getSizeFunc (c:SizableTypeConstraint<'v>) st = - foldSizableTypeConstraint2 (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) + foldSizableTypeConstraint2 (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) (fun _ v s -> (fun p -> compareSingValueFunc p v) ,s) - (fun _ intCon s -> + (fun _ intCon s -> match hasCount with | true -> foldSizeRangeTypeConstraint r lm getSizeFunc intCon s | false -> (fun p -> VCBTrue), s) @@ -204,9 +204,9 @@ let foldSizableConstraint (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) hasCount co st let ia5StringConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeId:ReferenceToType) (c:IA5StringConstraint) (us0:State) = - let print_AlphabetCheckFunc = lm.isvalid.Print_AlphabetCheckFunc - let stringContainsChar (v:String) = - let newStr = + let print_AlphabetCheckFunc = lm.isvalid.Print_AlphabetCheckFunc + let stringContainsChar (v:String) = + let newStr = if v.Length>1 then v.IDQ elif v.Length = 1 then @@ -223,62 +223,57 @@ let ia5StringConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (lm:Language let alphaFuncName = ToC (((typeId.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm")) + "_CharsAreValid") let foldRangeCharCon (lm:LanguageMacros) (c:CharTypeConstraint) st = let valToStrFunc1 v = v.ToString().ISQ - foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) - (fun _ (v:string) s -> (fun p -> VCBExpression( stringContainsChar v p.arg.p)) ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> + foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) + (fun _ (v:string) s -> (fun p -> VCBExpression (stringContainsChar v (p.arg.joined lm.lg))) ,s) + (fun _ v1 v2 minIsIn maxIsIn s -> (fun p -> VCBExpression(lm.isvalid.ExpAnd (Lte lm minIsIn (valToStrFunc1 v1) (lm.lg.getValue p.arg)) (Lte lm maxIsIn (lm.lg.getValue p.arg) (valToStrFunc1 v2)))), s) (fun _ v1 minIsIn s -> (fun p -> VCBExpression( Lte lm minIsIn (valToStrFunc1 v1) (lm.lg.getValue p.arg))), s) (fun _ v2 maxIsIn s -> (fun p -> VCBExpression(Lte lm maxIsIn (lm.lg.getValue p.arg) (valToStrFunc1 v2))), s) c - st - - foldStringTypeConstraint2 (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) - (fun _ v s -> (fun p -> VCBExpression (lm.isvalid.ExpStringEqual p.arg.p v.IDQ)) ,s) - (fun _ intCon s -> foldSizeRangeTypeConstraint r lm (fun l p -> lm.isvalid.StrLen p.arg.p) intCon s) - (fun _ alphcon (s:State) -> - let alphaBody p = - let alphaFunc = foldRangeCharCon lm alphcon 0 |> fst + st + + foldStringTypeConstraint2 (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) + (fun _ v s -> (fun p -> VCBExpression (lm.isvalid.ExpStringEqual (p.arg.joined lm.lg) v.IDQ)) ,s) + (fun _ intCon s -> foldSizeRangeTypeConstraint r lm (fun l p -> lm.isvalid.StrLen (p.arg.joined lm.lg)) intCon s) + (fun _ alphcon (s:State) -> + let alphaBody p = + let alphaFunc = foldRangeCharCon lm alphcon 0 |> fst match alphaFunc p with | VCBExpression x -> x | VCBStatement (x,_) -> x | VCBTrue -> "TRUE" | VCBFalse -> "FALSE" - + let alphaFuncName = sprintf "%s_%d" alphaFuncName s.alphaIndex let funcBody p = print_AlphabetCheckFunc alphaFuncName [alphaBody p] - let alphFunc = {AlphaFunc.funcName = alphaFuncName; funcBody = funcBody } + let alphaFunc = {AlphaFunc.funcName = alphaFuncName; funcBody = funcBody } - let newState = {s with alphaIndex = s.alphaIndex + 1; alphaFuncs = alphFunc::s.alphaFuncs} - let retFnc p = VCBExpression (sprintf "%s(%s)" alphaFuncName p.arg.p) - retFnc, newState) + let newState = {s with alphaIndex = s.alphaIndex + 1; alphaFuncs = alphaFunc::s.alphaFuncs} + let retFnc p = VCBExpression (sprintf "%s(%s)" alphaFuncName (p.arg.joined lm.lg)) + retFnc, newState) c - us0 - - - - - + us0 let integerConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (intClass:Asn1AcnAst.IntegerClass) (c:IntegerTypeConstraint) st = let valToStrFunc (i:BigInteger) = lm.lg.intValueToString i intClass let p2StrFunc l (p:CallerScope) = l.lg.getValue p.arg - foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_ecxept lm) con_root (con_root2 lm) + foldRangeTypeConstraint (con_or lm) (con_and lm) (con_not lm) (con_except lm) con_root (con_root2 lm) (fun _ v s -> (fun p -> VCBExpression (lm.isvalid.ExpEqual (lm.lg.getValue p.arg) (valToStrFunc v))) ,s) - (fun asn1 v1 v2 minIsIn maxIsIn s -> - let exp1 = con_rangeContraint_val_MAX lm intClass.Min intClass.Max v1 minIsIn valToStrFunc p2StrFunc - let exp2 = con_angeContraint_MIN_val lm intClass.Min intClass.Max v2 maxIsIn valToStrFunc p2StrFunc + (fun asn1 v1 v2 minIsIn maxIsIn s -> + let exp1 = con_rangeConstraint_val_MAX lm intClass.Min intClass.Max v1 minIsIn valToStrFunc p2StrFunc + let exp2 = con_rangeConstraint_MIN_val lm intClass.Min intClass.Max v2 maxIsIn valToStrFunc p2StrFunc con_and lm asn1 exp1 exp2 s) - (fun _ v1 minIsIn s -> con_rangeContraint_val_MAX lm intClass.Min intClass.Max v1 minIsIn valToStrFunc p2StrFunc, s) - (fun _ v2 maxIsIn s -> con_angeContraint_MIN_val lm intClass.Min intClass.Max v2 maxIsIn valToStrFunc p2StrFunc, s) + (fun _ v1 minIsIn s -> con_rangeConstraint_val_MAX lm intClass.Min intClass.Max v1 minIsIn valToStrFunc p2StrFunc, s) + (fun _ v2 maxIsIn s -> con_rangeConstraint_MIN_val lm intClass.Min intClass.Max v2 maxIsIn valToStrFunc p2StrFunc, s) c st let realConstraint2ValidationCodeBlock (l:LanguageMacros) (c:RealTypeConstraint) st = let valToStrFunc (v:double) = v.ToString(FsUtils.doubleParseString, NumberFormatInfo.InvariantInfo) - foldRangeTypeConstraint (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) + foldRangeTypeConstraint (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) (fun _ v s -> (fun p -> VCBExpression(l.isvalid.ExpEqual (l.lg.getValue p.arg) (valToStrFunc v))) ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> + (fun _ v1 v2 minIsIn maxIsIn s -> (fun p -> VCBExpression (l.isvalid.ExpAnd (Lte l minIsIn (valToStrFunc v1) (l.lg.getValue p.arg)) (Lte l maxIsIn (l.lg.getValue p.arg) (valToStrFunc v2)))), s) (fun _ v1 minIsIn s -> (fun p -> VCBExpression(Lte l minIsIn (valToStrFunc v1) (l.lg.getValue p.arg))), s) (fun _ v2 maxIsIn s -> (fun p -> VCBExpression(Lte l maxIsIn (l.lg.getValue p.arg) (valToStrFunc v2))), s) @@ -288,32 +283,32 @@ let realConstraint2ValidationCodeBlock (l:LanguageMacros) (c:RealTypeConstraint let booleanConstraint2ValidationCodeBlock (lm:LanguageMacros) (c:BoolConstraint) st = foldGenericCon lm (fun v -> v.ToString().ToLower()) c st - + let objIdConstraint2ValidationCodeBlock (l:LanguageMacros) (c:ObjectIdConstraint) st = let objId_equal = l.isvalid.objId_equal - + let printObjectIdentifierValue = l.vars.PrintObjectIdentifierValueAsCompoundLiteral - - foldGenericConstraint (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) - (fun _ (a,b) s -> + + foldGenericConstraint (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) + (fun _ (a,b) s -> let v = Asn1DefinedObjectIdentifierValue(a,b) - (fun (p:CallerScope) -> + (fun (p:CallerScope) -> let lit = printObjectIdentifierValue (v.Values |> List.map fst) (BigInteger v.Values.Length) - VCBExpression (objId_equal p.arg.p lit)) ,s) + VCBExpression (objId_equal (p.arg.joined l.lg) lit)) ,s) c st - + let timeConstraint2ValidationCodeBlock (l:LanguageMacros) (td) (c:TimeConstraint) st = - let print_Asn1LocalTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1LocalTime - let print_Asn1UtcTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1UtcTime - let print_Asn1LocalTimeWithTimeZone = l.vars.PrintTimeValueAsCompoundLiteral_Asn1LocalTimeWithTimeZone - let print_Asn1Date = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date - let print_Asn1Date_LocalTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_LocalTime - let print_Asn1Date_UtcTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_UtcTime - let print_Asn1Date_LocalTimeWithTimeZone = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_LocalTimeWithTimeZone - - let printValueAsLiteral (iv:Asn1DateTimeValue) = + let print_Asn1LocalTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1LocalTime + let print_Asn1UtcTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1UtcTime + let print_Asn1LocalTimeWithTimeZone = l.vars.PrintTimeValueAsCompoundLiteral_Asn1LocalTimeWithTimeZone + let print_Asn1Date = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date + let print_Asn1Date_LocalTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_LocalTime + let print_Asn1Date_UtcTime = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_UtcTime + let print_Asn1Date_LocalTimeWithTimeZone = l.vars.PrintTimeValueAsCompoundLiteral_Asn1Date_LocalTimeWithTimeZone + + let printValueAsLiteral (iv:Asn1DateTimeValue) = match iv with |Asn1LocalTimeValue tv -> print_Asn1LocalTime td tv |Asn1UtcTimeValue tv -> print_Asn1UtcTime td tv @@ -323,16 +318,16 @@ let timeConstraint2ValidationCodeBlock (l:LanguageMacros) (td) (c:TimeConstraint |Asn1Date_UtcTimeValue (dt,tv) -> print_Asn1Date_UtcTime td dt tv |Asn1Date_LocalTimeWithTimeZoneValue (dt,tv,tz)-> print_Asn1Date_LocalTimeWithTimeZone td dt tv tz - foldGenericConstraint (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) - (fun _ v s -> - (fun (p:CallerScope) -> + foldGenericConstraint (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) + (fun _ v s -> + (fun (p:CallerScope) -> let lit = printValueAsLiteral v - VCBExpression (l.isvalid.ExpEqual p.arg.p lit)) ,s) + VCBExpression (l.isvalid.ExpEqual (p.arg.joined l.lg) lit)) ,s) c st -let enumeratedConstraint2ValidationCodeBlock (l:LanguageMacros) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) (c:EnumConstraint) st = +let enumeratedConstraint2ValidationCodeBlock (l:LanguageMacros) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) (c:EnumConstraint) st = let printNamedItem (v:string) = let itm = o.items |> Seq.find (fun x -> x.Name.Value = v) let ret = l.lg.getNamedItemBackendName (Some typeDefinition ) itm @@ -340,30 +335,30 @@ let enumeratedConstraint2ValidationCodeBlock (l:LanguageMacros) (o:Asn1AcnAst.E foldGenericCon l printNamedItem c st let octetStringConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (typeId:ReferenceToType) (o:Asn1AcnAst.OctetString) (equalFunc:EqualFunction) (c:OctetStringConstraint) st = - let getSizeFunc (lm:LanguageMacros) p = l.lg.Length p.arg.p (l.lg.getAccess p.arg) - let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.OctetStringValue, (id,loc)) = + let getSizeFunc (lm:LanguageMacros) p = l.lg.Length (p.arg.joined l.lg) (l.lg.getAccess p.arg) + let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.OctetStringValue, (id,loc)) = let octet_var_string_equal = l.isvalid.octet_var_string_equal let octet_fix_string_equal = l.isvalid.octet_fix_string_equal - let printOctetArrayAsCompoundLitteral = l.vars.PrintOctetArrayAsCompoundLitteral - let octArrLiteral = printOctetArrayAsCompoundLitteral (v |> List.map (fun b -> b.Value)) + let printOctetArrayAsCompoundLiteral = l.vars.PrintOctetArrayAsCompoundLiteral + let octArrLiteral = printOctetArrayAsCompoundLiteral (v |> List.map (fun b -> b.Value)) match o.isFixedSize with - | true -> VCBExpression (octet_fix_string_equal p.arg.p (l.lg.getAccess p.arg) o.minSize.uper (v.Length.AsBigInt) octArrLiteral) - | false -> VCBExpression (octet_var_string_equal p.arg.p (l.lg.getAccess p.arg) (v.Length.AsBigInt) octArrLiteral) + | true -> VCBExpression (octet_fix_string_equal (p.arg.joined l.lg) (l.lg.getAccess p.arg) o.minSize.uper (v.Length.AsBigInt) octArrLiteral) + | false -> VCBExpression (octet_var_string_equal (p.arg.joined l.lg) (l.lg.getAccess p.arg) (v.Length.AsBigInt) octArrLiteral) let fnc, ns = foldSizableConstraint r l (not o.isFixedSize) compareSingleValueFunc getSizeFunc c st fnc, ns let bitStringConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (typeId:ReferenceToType) (o:Asn1AcnAst.BitString) (equalFunc:EqualFunction) (c:BitStringConstraint) st = - let getSizeFunc (l:LanguageMacros) p = l.lg.Length p.arg.p (l.lg.getAccess p.arg) - let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.BitStringValue, (id,loc)) = + let getSizeFunc (l:LanguageMacros) p = l.lg.Length (p.arg.joined l.lg) (l.lg.getAccess p.arg) + let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.BitStringValue, (id,loc)) = let bit_var_string_equal = l.isvalid.bit_var_string_equal let bit_fix_string_equal = l.isvalid.bit_fix_string_equal - let printOctetArrayAsCompoundLitteral = l.vars.PrintOctetArrayAsCompoundLitteral + let printOctetArrayAsCompoundLiteral = l.vars.PrintOctetArrayAsCompoundLiteral let bytes = bitStringValueToByteArray (StringLoc.ByValue v.Value) - let octArrLiteral = printOctetArrayAsCompoundLitteral bytes - let bitArrLiteral = variables_a.PrintBitArrayAsCompoundLitteral (v.Value.ToCharArray() |> Seq.map(fun c -> if c = '0' then 0uy else 1uy)) + let octArrLiteral = printOctetArrayAsCompoundLiteral bytes + let bitArrLiteral = variables_a.PrintBitArrayAsCompoundLiteral (v.Value.ToCharArray() |> Seq.map(fun c -> if c = '0' then 0uy else 1uy)) match o.isFixedSize with - | true -> VCBExpression (bit_fix_string_equal p.arg.p (l.lg.getAccess p.arg) o.minSize.uper (v.Value.Length.AsBigInt) octArrLiteral bitArrLiteral) - | false -> VCBExpression (bit_var_string_equal p.arg.p (l.lg.getAccess p.arg) (v.Value.Length.AsBigInt) octArrLiteral bitArrLiteral) + | true -> VCBExpression (bit_fix_string_equal (p.arg.joined l.lg) (l.lg.getAccess p.arg) o.minSize.uper (v.Value.Length.AsBigInt) octArrLiteral bitArrLiteral) + | false -> VCBExpression (bit_var_string_equal (p.arg.joined l.lg) (l.lg.getAccess p.arg) (v.Value.Length.AsBigInt) octArrLiteral bitArrLiteral) let fnc, ns = foldSizableConstraint r l (not o.isFixedSize) compareSingleValueFunc getSizeFunc c st fnc, ns @@ -380,52 +375,52 @@ let rec anyConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMac | Enumerated o, EnumConstraint c -> enumeratedConstraint2ValidationCodeBlock l o.baseInfo o.definitionOrRef c st | ObjectIdentifier o, ObjectIdConstraint c -> objIdConstraint2ValidationCodeBlock l c st | TimeType o, TimeConstraint c -> timeConstraint2ValidationCodeBlock l (l.lg.typeDef o.baseInfo.typeDef) c st - | Sequence o, SeqConstraint c -> + | Sequence o, SeqConstraint c -> let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.SeqValue) = VCBTrue //currently single value constraints are ignored. sequenceConstraint2ValidationCodeBlock r l t.id o.Asn1Children valToStrFunc c st | SequenceOf o, SequenceOfConstraint c -> sequenceOfConstraint2ValidationCodeBlock r l t.id o.baseInfo o.childType o.equalFunction c st - | Choice o, ChoiceConstraint c -> + | Choice o, ChoiceConstraint c -> let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.ChValue) = VCBTrue //currently single value constraints are ignored. choiceConstraint2ValidationCodeBlock r l t.id o.children valToStrFunc o.definitionOrRef c st | _ -> raise(SemanticError(erLoc, "Invalid combination of type/constraint type")) - + and sequenceConstraint2ValidationCodeBlock (r: Asn1AcnAst.AstRoot) (l: LanguageMacros) (typeId: ReferenceToType) (children: Asn1Child list) valToStrFunc (c: SeqConstraint) st = let child_always_present_or_absentExp = l.isvalid.Sequence_optional_child_always_present_or_absent_expr let sequence_OptionalChild = l.isvalid.Sequence_OptionalChild - let expressionToStament = l.isvalid.ExpressionToStament + let expressionToStatement = l.isvalid.ExpressionToStatement - let handleNamedConstraint curState (nc:NamedConstraint) = + let handleNamedConstraint curState (nc:NamedConstraint) = let ch = children |> Seq.find(fun x -> x.Name.Value = nc.Name.Value) - + let childCheck, ns = - match nc.Contraint with + match nc.Constraint with | None -> (fun p -> VCBTrue), curState | Some ac -> let fnc, ns = anyConstraint2ValidationCodeBlock r l nc.Name.Location ch.Type ac curState - (fun p -> - let child_arg = l.lg.getSeqChild p.arg (l.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String false + (fun p -> + let child_arg = l.lg.getSeqChild p.arg (l.lg.getAsn1ChildBackendName ch) ch.Type.isIA5String ch.Optionality.IsSome let chp = {p with arg = child_arg} fnc chp), ns - + let childCheck = match ch.Optionality with | None -> childCheck - | Some _ -> - let newChidlCheckFnc (p:CallerScope) = + | Some _ -> + let newChildCheckFnc (p:CallerScope) = match childCheck p with - | VCBExpression exp -> VCBStatement (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) (expressionToStament exp), []) - | VCBStatement (stat, lv1)-> VCBStatement (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) stat, lv1) + | VCBExpression exp -> VCBStatement (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) (expressionToStatement exp), []) + | VCBStatement (stat, lv1)-> VCBStatement (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) stat, lv1) | VCBTrue -> VCBTrue - | VCBFalse -> VCBStatement (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) (expressionToStament "FALSE"), []) + | VCBFalse -> VCBStatement (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) (expressionToStatement "FALSE"), []) - newChidlCheckFnc + newChildCheckFnc - let isAbsentFlag = + let isAbsentFlag = match ST.lang with | ProgrammingLanguage.Scala -> l.lg.FalseLiteral | _ -> "0" - let isPresentFlag = + let isPresentFlag = match ST.lang with | ProgrammingLanguage.Scala -> l.lg.TrueLiteral | _ -> "1" // leave like it was - TRUE may not be 1 @@ -434,21 +429,21 @@ and sequenceConstraint2ValidationCodeBlock (r: Asn1AcnAst.AstRoot) (l: LanguageM match nc.Mark with | Asn1Ast.NoMark -> [] | Asn1Ast.MarkOptional -> [] - | Asn1Ast.MarkAbsent -> - let isExp = (fun (p:CallerScope) -> VCBExpression (child_always_present_or_absentExp p.arg.p (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) isAbsentFlag)) + | Asn1Ast.MarkAbsent -> + let isExp = (fun (p:CallerScope) -> VCBExpression (child_always_present_or_absentExp (p.arg.joined l.lg) (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) isAbsentFlag)) [isExp] - | Asn1Ast.MarkPresent -> - let isExp = (fun (p:CallerScope) -> VCBExpression (child_always_present_or_absentExp p.arg.p (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) isPresentFlag)) + | Asn1Ast.MarkPresent -> + let isExp = (fun (p:CallerScope) -> VCBExpression (child_always_present_or_absentExp (p.arg.joined l.lg) (l.lg.getAccess p.arg) (l.lg.getAsn1ChildBackendName ch) isPresentFlag)) [isExp] presentAbsent@[childCheck], ns - foldSeqConstraint (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) - (fun _ v s -> (fun p -> valToStrFunc p v) ,s) - (fun _ ncs s -> - let withComponentItems, ns = ncs |> Asn1Fold.foldMap handleNamedConstraint s + foldSeqConstraint (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) + (fun _ v s -> (fun p -> valToStrFunc p v) ,s) + (fun _ ncs s -> + let withComponentItems, ns = ncs |> Asn1Fold.foldMap handleNamedConstraint s let withComponentItems = withComponentItems |> List.collect id - let fnc p = + let fnc p = ValidationCodeBlock_Multiple_And l (withComponentItems |> List.map (fun fnc -> fnc p)) fnc, ns) c @@ -456,90 +451,90 @@ and sequenceConstraint2ValidationCodeBlock (r: Asn1AcnAst.AstRoot) (l: LanguageM -and choiceConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (typeId:ReferenceToType) (children:ChChildInfo list) valToStrFunc (defOrRef:TypeDefintionOrReference) (c:ChoiceConstraint) st = +and choiceConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (typeId:ReferenceToType) (children:ChChildInfo list) valToStrFunc (defOrRef:TypeDefinitionOrReference) (c:ChoiceConstraint) st = let choice_OptionalChild = l.isvalid.Choice_OptionalChild - let expressionToStament = l.isvalid.ExpressionToStament + let expressionToStatement = l.isvalid.ExpressionToStatement let choice_child_always_present_Exp = l.isvalid.Choice_child_always_present_Exp let choice_child_always_absent_Exp = l.isvalid.Choice_child_always_absent_Exp - let handleNamedConstraint curState (nc:NamedConstraint) = + let handleNamedConstraint curState (nc:NamedConstraint) = let ch = children |> Seq.find(fun x -> x.Name.Value = nc.Name.Value) let presentWhenName = l.lg.presentWhenName (Some defOrRef) ch let childCheck, ns = - match nc.Contraint with + match nc.Constraint with | None -> (fun p -> VCBTrue), curState | Some ac -> let fnc, ns = anyConstraint2ValidationCodeBlock r l nc.Name.Location ch.chType ac curState - (fun p -> + (fun p -> let child_arg = l.lg.getChChild p.arg (l.lg.getAsn1ChChildBackendName ch) ch.chType.isIA5String let chp = {p with arg = child_arg} fnc chp), ns - + let childCheck = - let newChidlCheckFnc (p:CallerScope) = + let newChildCheckFnc (p:CallerScope) = match childCheck p with - | VCBExpression exp -> VCBStatement (choice_OptionalChild p.arg.p "" (l.lg.getAccess p.arg) presentWhenName (expressionToStament exp), []) - | VCBStatement (stat, lv1)-> VCBStatement (choice_OptionalChild p.arg.p "" (l.lg.getAccess p.arg) presentWhenName stat, lv1) + | VCBExpression exp -> VCBStatement (choice_OptionalChild (p.arg.joined l.lg) "" (l.lg.getAccess p.arg) presentWhenName (expressionToStatement exp), []) + | VCBStatement (stat, lv1)-> VCBStatement (choice_OptionalChild (p.arg.joined l.lg) "" (l.lg.getAccess p.arg) presentWhenName stat, lv1) | VCBTrue -> VCBTrue - | VCBFalse -> VCBStatement (choice_OptionalChild p.arg.p "" (l.lg.getAccess p.arg) (presentWhenName) (expressionToStament "FALSE"), []) + | VCBFalse -> VCBStatement (choice_OptionalChild (p.arg.joined l.lg) "" (l.lg.getAccess p.arg) (presentWhenName) (expressionToStatement "FALSE"), []) - newChidlCheckFnc + newChildCheckFnc let presentAbsent = match nc.Mark with | Asn1Ast.NoMark -> [] | Asn1Ast.MarkOptional -> [] - | Asn1Ast.MarkAbsent -> - let isExp = (fun (p:CallerScope) -> VCBExpression (choice_child_always_absent_Exp p.arg.p (l.lg.getAccess p.arg) presentWhenName )) + | Asn1Ast.MarkAbsent -> + let isExp = (fun (p:CallerScope) -> VCBExpression (choice_child_always_absent_Exp (p.arg.joined l.lg) (l.lg.getAccess p.arg) presentWhenName )) [isExp] - | Asn1Ast.MarkPresent -> - let isExp = (fun (p:CallerScope) -> VCBExpression (choice_child_always_present_Exp p.arg.p (l.lg.getAccess p.arg) presentWhenName )) + | Asn1Ast.MarkPresent -> + let isExp = (fun (p:CallerScope) -> VCBExpression (choice_child_always_present_Exp (p.arg.joined l.lg) (l.lg.getAccess p.arg) presentWhenName )) [isExp] presentAbsent@[childCheck], ns - foldChoiceConstraint (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) - (fun _ v s -> (fun p -> valToStrFunc p v) ,s) - (fun _ ncs s -> - let withComponentItems, ns = ncs |> Asn1Fold.foldMap handleNamedConstraint s + foldChoiceConstraint (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) + (fun _ v s -> (fun p -> valToStrFunc p v) ,s) + (fun _ ncs s -> + let withComponentItems, ns = ncs |> Asn1Fold.foldMap handleNamedConstraint s let withComponentItems = withComponentItems |> List.collect id - let fnc p = + let fnc p = ValidationCodeBlock_Multiple_And l (withComponentItems |> List.map (fun fnc -> fnc p)) fnc, ns) c st and sequenceOfConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (typeId:ReferenceToType) (o:Asn1AcnAst.SequenceOf) (child:Asn1Type) (equalFunc:EqualFunction) (c:SequenceOfConstraint) st = - - let ii = typeId.SeqeuenceOfLevel + 1 + + let ii = typeId.SequenceOfLevel + 1 let i = sprintf "i%d" ii let lv = SequenceOfIndex (ii, None) - let expressionToStament = l.isvalid.ExpressionToStament + let expressionToStatement = l.isvalid.ExpressionToStatement let statementForLoop = l.isvalid.StatementForLoop - let getSizeFunc (l:LanguageMacros) p = l.lg.Length p.arg.p (l.lg.getAccess p.arg) - let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.SeqOfValue) = + let getSizeFunc (l:LanguageMacros) p = l.lg.Length (p.arg.joined l.lg) (l.lg.getAccess p.arg) + let compareSingleValueFunc (p:CallerScope) (v:Asn1AcnAst.SeqOfValue) = VCBTrue - foldSequenceOfTypeConstraint2 (con_or l) (con_and l) (con_not l) (con_ecxept l) con_root (con_root2 l) + foldSequenceOfTypeConstraint2 (con_or l) (con_and l) (con_not l) (con_except l) con_root (con_root2 l) (fun _ v s -> (fun p -> compareSingleValueFunc p v) ,s) - (fun _ intCon s -> + (fun _ intCon s -> match o.isFixedSize with | false -> foldSizeRangeTypeConstraint r l getSizeFunc intCon s | true -> (fun p -> VCBTrue), s) - (fun _ c loc s -> - (fun p -> + (fun _ c loc s -> + (fun p -> let fnc, ns = anyConstraint2ValidationCodeBlock r l loc child c s let ch_arg = l.lg.getArrayItem p.arg i child.isIA5String let childCheck p = fnc ({p with arg = ch_arg}) - let ret = - match childCheck p with - | VCBExpression exp -> VCBStatement (statementForLoop p.arg.p (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper (expressionToStament exp), [lv]) - | VCBStatement (stat, lv2)-> VCBStatement (statementForLoop p.arg.p (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper stat, lv::lv2) + let ret = + match childCheck p with + | VCBExpression exp -> VCBStatement (statementForLoop (p.arg.joined l.lg) (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper (expressionToStatement exp), [lv]) + | VCBStatement (stat, lv2)-> VCBStatement (statementForLoop (p.arg.joined l.lg) (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper stat, lv::lv2) | VCBTrue -> VCBTrue - | VCBFalse -> VCBStatement (statementForLoop p.arg.p (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper (expressionToStament "FALSE"), [lv]) - ret), s) + | VCBFalse -> VCBStatement (statementForLoop (p.arg.joined l.lg) (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper (expressionToStatement "FALSE"), [lv]) + ret), s) c st @@ -547,39 +542,33 @@ and sequenceOfConstraint2ValidationCodeBlock (r:Asn1AcnAst.AstRoot) (l:LanguageM let getIntSimplifiedConstraints (r:Asn1AcnAst.AstRoot) isUnsigned (allCons : IntegerTypeConstraint list) = allCons - + let hasValidationFunc allCons = match allCons with | [] -> false | _ -> true -(* -let getFuncName (r:Asn1AcnAst.AstRoot) (l:ProgrammingLanguage) (lm:LanguageMacros) (typeId:ReferenceToType) (td:FE_TypeDefinition) = - match typeId.tasInfo with - | None -> None - | Some _ -> Some (td.typeName + "_IsConstraintValid") -*) -let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefintionOrReference) = +let getFuncName (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (typeDefinition:TypeDefinitionOrReference) = getFuncNameGeneric typeDefinition "_IsConstraintValid" -let str_p (lm:LanguageMacros) (typeid:ReferenceToType) = - ({CallerScope.modName = typeid.ModName; arg = VALUE (sprintf "str%s" (lm.lg.ArrayAccess "i"))}) +let str_p (lm:LanguageMacros) (typeid:ReferenceToType) = + ({CallerScope.modName = typeid.ModName; arg = (Selection.emptyPath "str" FixArray).append (ArrayAccess ("i", Value))}) type IsValidAux = { isValidStatement : CallerScope -> ValidationStatement localVars : LocalVariable list alphaFuncs : AlphaFunc list - childErrCodes : ErroCode list + childErrCodes : ErrorCode list } -type SeqCompIsValidAux = +type SeqCompIsValidAux = | IsValidEmbedded of {| isValidStatement : CallerScope -> ValidationStatement localVars : LocalVariable list alphaFuncs : AlphaFunc list - childErrCodes : ErroCode list + childErrCodes : ErrorCode list |} | IsValidProcCall of {| isValidStatement : CallerScope -> ValidationStatement @@ -587,28 +576,27 @@ type SeqCompIsValidAux = |} -let createIsValidFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (fncBodyE : ErroCode->CallerScope->ValidationStatement) (typeDefinition:TypeDefintionOrReference) (alphaFuncs : AlphaFunc list) (localVars : LocalVariable list) (childErrCodes : ErroCode list) nonEmbeddedChildrenValidFuncs errorCodeComment (us:State) = - //let hasValidationFunc= hasValidationFunc allCons +let createIsValidFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (fncBodyE : ErrorCode->CallerScope->ValidationStatement) (typeDefinition:TypeDefinitionOrReference) (alphaFuncs : AlphaFunc list) (localVars : LocalVariable list) (childErrCodes : ErrorCode list) nonEmbeddedChildrenValidFuncs errorCodeComment (us:State) = let emitTasFnc = lm.isvalid.EmitTypeAssignment_composite let emitTasFncDef = lm.isvalid.EmitTypeAssignment_composite_def let defErrCode = lm.isvalid.EmitTypeAssignment_composite_def_err_code - let funcName = getFuncName r lm typeDefinition //t.id (t.FT_TypeDefintion.[l]) + let funcName = getFuncName r lm typeDefinition let errCodeName = ToC ("ERR_" + ((t.id.AcnAbsPath |> Seq.skip 1 |> Seq.StrJoin("-")).Replace("#","elm"))) let errCode, ns = getNextValidErrorCode us errCodeName errorCodeComment let funcBody = fncBodyE errCode let errCodes = errCode::childErrCodes let p = lm.lg.getParamType t Encode - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let sPtrPrefix = lm.lg.getPtrPrefix p.arg let sPtrSuffix = lm.lg.getPtrSuffix p.arg - let func, funcDef = + let func, funcDef = match funcName with | None -> None, None - | Some funcName -> - let statement, stLVs, bUnreferenced = + | Some funcName -> + let statement, stLVs, bUnreferenced = match funcBody p with | ValidationStatementTrue (st,lv) | ValidationStatementFalse (st,lv) -> st, lv, true @@ -622,26 +610,25 @@ let createIsValidFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1Ac let arrsErrcodes = errCodes |> List.map(fun s -> defErrCode s.errCodeName (BigInteger s.errCodeValue) (split s.comment)) let fncH = emitTasFncDef varName sStar funcName (lm.lg.getLongTypedefName typeDefinition) arrsErrcodes Some fnc, Some fncH - let ret = + let ret = { IsValidFunction.funcName = funcName errCodes = errCodes func = func funcDef = funcDef - funcBody = funcBody + funcBody = funcBody alphaFuncs = alphaFuncs localVariables = localVars anonymousVariables = [] nonEmbeddedChildrenValidFuncs = nonEmbeddedChildrenValidFuncs - } + } Some ret, ns -let funcBody l fncs (e:ErroCode) (p:CallerScope) = +let funcBody l fncs (e:ErrorCode) (p:CallerScope) = let combinedVcb = fncs |> List.map (fun fnc -> fnc p) |> (ValidationCodeBlock_Multiple_And l) - convertVCBToStatementAndAssigneErrCode l combinedVcb e.errCodeName + convertVCBToStatementAndAssignedErrCode l combinedVcb e.errCodeName -let createIntegerFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefintionOrReference) (us:State) = - //let allCons = getIntSimplifiedConstraints r o.isUnsigned o.AllCons +let createIntegerFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Integer) (typeDefinition:TypeDefinitionOrReference) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> integerConstraint2ValidationCodeBlock r l (o.intClass) c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns @@ -651,38 +638,38 @@ let createIntegerFunctionByCons (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) isUns | [] -> None | _ -> let fncs, ns = allCons |> Asn1Fold.foldMap (fun us c -> integerConstraint2ValidationCodeBlock r l isUnsigned c us) 0 - let funcExp (p:CallerScope) = - let vp = fncs |> List.map (fun fnc -> fnc p) |> (ValidationCodeBlock_Multiple_And l) + let funcExp (p:CallerScope) = + let vp = fncs |> List.map (fun fnc -> fnc p) |> (ValidationCodeBlock_Multiple_And l) vp Some funcExp -let createRealFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createRealFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) (typeDefinition:TypeDefinitionOrReference) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> realConstraint2ValidationCodeBlock l c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let createBoolFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createBoolFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) (typeDefinition:TypeDefinitionOrReference) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> booleanConstraint2ValidationCodeBlock l c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefintionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = +let createOctetStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.OctetString) (typeDefinition:TypeDefinitionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> octetStringConstraint2ValidationCodeBlock r l t.id o equalFunc c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = +let createBitStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.BitString) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (equalFunc:EqualFunction) (printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> bitStringConstraint2ValidationCodeBlock r l t.id o equalFunc c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let createStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createStringFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.StringType) (typeDefinition:TypeDefinitionOrReference) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> ia5StringConstraint2ValidationCodeBlock r l t.id c us) {us with alphaIndex=0; alphaFuncs=[]} let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition ns.alphaFuncs [] [] [] (Some errorCodeComment) ns -let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefintionOrReference) (us:State) = - let conToStrFunc_basic (p:CallerScope) = +let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) (typeDefinition:TypeDefinitionOrReference) (us:State) = + let conToStrFunc_basic (p:CallerScope) = let namespacePrefix = l.lg.rtlModuleName match o.relativeObjectId with | false -> VCBExpression (sprintf "%sObjectIdentifier_isValid(%s)" namespacePrefix (l.lg.getPointer p.arg)) @@ -694,8 +681,8 @@ let createObjectIdentifierFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t: createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefintionOrReference) (us:State) = - let conToStrFunc_basic (p:CallerScope) = +let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) (typeDefinition:TypeDefinitionOrReference) (us:State) = + let conToStrFunc_basic (p:CallerScope) = let namespacePrefix = l.lg.rtlModuleName VCBExpression (sprintf "%sTimeType_isValid(%s)" namespacePrefix (l.lg.getPointer p.arg)) let fnc, ns = o.cons |> Asn1Fold.foldMap (fun us c -> timeConstraint2ValidationCodeBlock l (l.lg.typeDef o.typeDef) c us) us @@ -705,52 +692,52 @@ let createTimeTypeFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnA -let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefintionOrReference) (us:State) = +let createEnumeratedFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) (typeDefinition:TypeDefinitionOrReference) (us:State) = let fncs, ns = o.cons |> Asn1Fold.foldMap (fun us c -> enumeratedConstraint2ValidationCodeBlock l o typeDefinition c us) us let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t (funcBody l fncs) typeDefinition [] [] [] [] (Some errorCodeComment) ns -let convertMultipleVCBsToStatementAndSetErrorCode l p (errCode: ErroCode) vcbs = - let combinedVcb = - vcbs |> +let convertMultipleVCBsToStatementAndSetErrorCode l p (errCode: ErrorCode) vcbs = + let combinedVcb = + vcbs |> List.map (fun fnc -> fnc p) |> List.filter(fun vcb -> match vcb with | VCBTrue -> false | VCBFalse -> true | VCBExpression sExp -> true - | VCBStatement sStat -> true) |> + | VCBStatement sStat -> true) |> ValidationCodeBlock_Multiple_And l - let st = convertVCBToStatementAndAssigneErrCode l combinedVcb errCode.errCodeName - match st with - | ValidationStatementTrue _ -> [] - | ValidationStatementFalse st + let st = convertVCBToStatementAndAssignedErrCode l combinedVcb errCode.errCodeName + match st with + | ValidationStatementTrue _ -> [] + | ValidationStatementFalse st | ValidationStatement st -> [st] -let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefintionOrReference) (childType:Asn1Type) (equalFunc:EqualFunction) (us:State) = +let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.SequenceOf) (typeDefinition:TypeDefinitionOrReference) (childType:Asn1Type) (equalFunc:EqualFunction) (us:State) = let sequenceOf = l.isvalid.sequenceOf2 let callBaseTypeFunc = l.isvalid.call_base_type_func let vcbs, ns2 = o.cons |> Asn1Fold.foldMap(fun cs c -> sequenceOfConstraint2ValidationCodeBlock r l t.id o (childType:Asn1Type) equalFunc c cs) us - let i = sprintf "i%d" (t.id.SeqeuenceOfLevel + 1) + let i = sprintf "i%d" (t.id.SequenceOfLevel + 1) let chp p = {p with arg = l.lg.getArrayItem p.arg i childType.isIA5String} - let lv = SequenceOfIndex (t.id.SeqeuenceOfLevel + 1, None) + let lv = SequenceOfIndex (t.id.SequenceOfLevel + 1, None) let childFunc, childErrCodes, childAlphaFuncs, childLocalVars, nonEmbeddedChildValidFuncs = match childType.isValidFunction with | None -> None, [], [], [], [] | Some cvf -> match cvf.funcName with - | Some fncName -> - let f1 (p:CallerScope) = + | Some fncName -> + let f1 (p:CallerScope) = ValidationStatement (callBaseTypeFunc (l.lg.getPointer (chp p).arg) fncName None, []) Some f1, [], [], [], [cvf] - | None -> - let f1 (p:CallerScope) = cvf.funcBody (chp p) + | None -> + let f1 (p:CallerScope) = cvf.funcBody (chp p) Some f1, cvf.errCodes, cvf.alphaFuncs, cvf.localVariables, [] - - let funBody (errCode: ErroCode) (p:CallerScope) = + + let funBody (errCode: ErrorCode) (p:CallerScope) = let with_component_check, lllvs = convertMultipleVCBsToStatementAndSetErrorCode l p errCode vcbs |> List.unzip let childCheck = match childFunc with @@ -759,21 +746,18 @@ let createSequenceOfFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1Ac let innerStatement = chFunc p match innerStatement with | ValidationStatementTrue (_,_) -> [] - | ValidationStatementFalse (st,clv) -> [sequenceOf p.arg.p (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper st, lv::clv] - | ValidationStatement (st,clv) -> [sequenceOf p.arg.p (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper st, lv::clv] + | ValidationStatementFalse (st,clv) -> [sequenceOf (p.arg.joined l.lg) (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper st, lv::clv] + | ValidationStatement (st,clv) -> [sequenceOf (p.arg.joined l.lg) (l.lg.getAccess p.arg) i o.isFixedSize o.minSize.uper st, lv::clv] let childCheck, lllvs2 = childCheck |> List.unzip match (with_component_check@childCheck) |> DAstUtilFunctions.nestItems_ret l with - | None -> convertVCBToStatementAndAssigneErrCode l VCBTrue errCode.errCodeName + | None -> convertVCBToStatementAndAssignedErrCode l VCBTrue errCode.errCodeName | Some s ->ValidationStatement (s, (lllvs@lllvs2) |> List.collect id) - + let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t funBody typeDefinition childAlphaFuncs childLocalVars childErrCodes nonEmbeddedChildValidFuncs (Some errorCodeComment) ns2 -let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefintionOrReference) (children:SeqChildInfo list) (us:State) = - //if (t.id.AsString = "Subtypes.T3-s1") then - // printfn "%s" t.id.AsString - let child_always_present_or_absent = l.isvalid.Sequence_optional_child_always_present_or_absent +let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Sequence) (typeDefinition:TypeDefinitionOrReference) (children:SeqChildInfo list) (us:State) = let sequence_OptionalChild = l.isvalid.Sequence_OptionalChild let callBaseTypeFunc = l.isvalid.call_base_type_func let asn1Children = children |> List.choose(fun c -> match c with Asn1Child x -> Some x | AcnChild _ -> None) @@ -782,30 +766,32 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1Acn match child.Type.isValidFunction with | None -> None, us | Some (isValidFunction) -> - let func = + let func = (*component's is validation statement. If the component has a separate function then make a call otherwise embed the code*) fun (p:CallerScope) -> - let chp = {p with arg = l.lg.getSeqChild p.arg c_name child.Type.isIA5String false} + let newArg = l.lg.getSeqChild p.arg c_name child.Type.isIA5String child.Optionality.IsSome + let newArg = if l.lg.usesWrappedOptional && newArg.isOptional then newArg.asLast else newArg + let chp = {p with arg = newArg} match isValidFunction.funcName with - | Some fncName -> + | Some fncName -> ValidationStatement (callBaseTypeFunc (l.lg.getPointer chp.arg) fncName None, []) | None -> isValidFunction.funcBody chp - let childFnc = + let childFnc = (*handle optionality*) match child.Optionality with - | Some _ -> - let newFunc = - (fun (p:CallerScope) -> + | Some _ -> + let newFunc = + (fun (p:CallerScope) -> match func p with - | ValidationStatementTrue (st,lv) -> ValidationStatementTrue (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) c_name st, lv) - | ValidationStatementFalse (st,lv) -> ValidationStatement (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) c_name st, lv) - | ValidationStatement (st,lv) -> ValidationStatement (sequence_OptionalChild p.arg.p (l.lg.getAccess p.arg) c_name st, lv) ) + | ValidationStatementTrue (st,lv) -> ValidationStatementTrue (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) c_name st, lv) + | ValidationStatementFalse (st,lv) -> ValidationStatement (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) c_name st, lv) + | ValidationStatement (st,lv) -> ValidationStatement (sequence_OptionalChild (p.arg.joined l.lg) (l.lg.getAccess p.arg) c_name st, lv) ) newFunc | None -> func (*return new local variables, errorcodes or alphaFuncs*) match isValidFunction.funcName with - | Some fncName -> + | Some fncName -> Some(IsValidProcCall {|isValidStatement= childFnc; chidIsValidFunction=isValidFunction|}), us | None -> Some(IsValidEmbedded {|isValidStatement = childFnc; localVars = isValidFunction.localVariables; alphaFuncs = isValidFunction.alphaFuncs; childErrCodes = isValidFunction.errCodes|}), us @@ -820,66 +806,64 @@ let createSequenceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1Acn - let funBody (errCode: ErroCode) (p:CallerScope) = - let childrenChecks, lv = - let aaa, lv = - childrenContent |> - List.choose(fun z -> + let funBody (errCode: ErrorCode) (p:CallerScope) = + let childrenChecks, lv = + let aaa, lv = + childrenContent |> + List.choose(fun z -> let isValidStatement = match z with IsValidEmbedded c -> c.isValidStatement | IsValidProcCall c -> c.isValidStatement - match isValidStatement p with - | ValidationStatementTrue _ -> None - | ValidationStatementFalse (st,lv) + match isValidStatement p with + | ValidationStatementTrue _ -> None + | ValidationStatementFalse (st,lv) | ValidationStatement (st,lv) -> Some (st, lv)) |> List.unzip aaa |> DAstUtilFunctions.nestItems_ret l |> Option.toList, (lv |> List.collect id) - let with_component_check, lv2 = + let with_component_check, lv2 = convertMultipleVCBsToStatementAndSetErrorCode l p errCode vcbs |> List.unzip match (childrenChecks@with_component_check) |> DAstUtilFunctions.nestItems_ret l with - | None -> convertVCBToStatementAndAssigneErrCode l VCBTrue errCode.errCodeName + | None -> convertVCBToStatementAndAssignedErrCode l VCBTrue errCode.errCodeName | Some s ->ValidationStatement (s, lv@(lv2 |>List.collect id)) - - + + let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t funBody typeDefinition alphaFuncs localVars childrenErrCodes nonEmbeddedChildrenValidFuncs (Some errorCodeComment) ns2 -let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefintionOrReference) (defOrRef:TypeDefintionOrReference) (children:ChChildInfo list) (baseTypeValFunc : IsValidFunction option) (us:State) = +let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Choice) (typeDefinition:TypeDefinitionOrReference) (defOrRef:TypeDefinitionOrReference) (children:ChChildInfo list) (baseTypeValFunc : IsValidFunction option) (us:State) = let choice_OptionalChild = l.isvalid.Choice_OptionalChild - let expressionToStament = l.isvalid.ExpressionToStament let callBaseTypeFunc = l.isvalid.call_base_type_func let handleChild (child:ChChildInfo) (us:State) = let c_name = l.lg.getAsn1ChChildBackendName child - let alwaysAbsent = child.Optionality = (Some Asn1AcnAst.Asn1ChoiceOptionality.ChoiceAlwaysAbsent) let presentWhenName = l.lg.presentWhenName (Some defOrRef) child match child.chType.isValidFunction with | None -> None, us | Some (isValidFunction) -> - let func = + let func = (*alternative's is validation statement. If the alternative has a separate function then make a call otherwise embed the code*) fun (p:CallerScope) -> let chp = {p with arg = l.lg.getChChild p.arg c_name child.chType.isIA5String} match isValidFunction.funcName with - | Some fncName -> + | Some fncName -> ValidationStatement (callBaseTypeFunc (l.lg.getPointer chp.arg) fncName None, []) | None -> isValidFunction.funcBody chp - let childFnc = - let newFunc = - (fun (p:CallerScope) -> + let childFnc = + let newFunc = + (fun (p:CallerScope) -> let localTmpVarName = match ST.lang with | Scala -> child._scala_name | _ -> "" match func p with - | ValidationStatementTrue (st,lv) -> ValidationStatementTrue (choice_OptionalChild p.arg.p localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) - | ValidationStatementFalse (st,lv) -> ValidationStatement (choice_OptionalChild p.arg.p localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) - | ValidationStatement (st,lv) -> ValidationStatement (choice_OptionalChild p.arg.p localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) ) + | ValidationStatementTrue (st,lv) -> ValidationStatementTrue (choice_OptionalChild (p.arg.joined l.lg) localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) + | ValidationStatementFalse (st,lv) -> ValidationStatement (choice_OptionalChild (p.arg.joined l.lg) localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) + | ValidationStatement (st,lv) -> ValidationStatement (choice_OptionalChild (p.arg.joined l.lg) localTmpVarName (l.lg.getAccess p.arg) presentWhenName st, lv) ) newFunc (*return new local variables, errorcodes or alphaFuncs*) match isValidFunction.funcName with | None -> Some(IsValidEmbedded {|isValidStatement = childFnc; localVars = isValidFunction.localVariables; alphaFuncs = isValidFunction.alphaFuncs; childErrCodes = isValidFunction.errCodes |}), us - | Some fncName -> + | Some fncName -> Some(IsValidProcCall {|isValidStatement = childFnc; chidIsValidFunction=isValidFunction|}), us let childrenContent, ns1 = children |> Asn1Fold.foldMap (fun us child -> handleChild child us) us @@ -890,30 +874,30 @@ let createChoiceFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAs let nonEmbeddedChildrenValidFuncs = childrenContent |> List.choose(fun s -> match s with IsValidEmbedded c -> None | IsValidProcCall c -> Some c.chidIsValidFunction) let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.ChValue) = VCBTrue let vcbs, ns2 = o.cons |> Asn1Fold.foldMap(fun cs c -> choiceConstraint2ValidationCodeBlock r l t.id children valToStrFunc defOrRef c cs) ns1 - let funBody (errCode: ErroCode) (p:CallerScope) = - let childrenChecks, lv1 = - let aaa, lv1 = - childrenContent |> - List.choose(fun z -> + let funBody (errCode: ErrorCode) (p:CallerScope) = + let childrenChecks, lv1 = + let aaa, lv1 = + childrenContent |> + List.choose(fun z -> let isValidStatement = match z with IsValidEmbedded c -> c.isValidStatement | IsValidProcCall c -> c.isValidStatement - match isValidStatement p with - | ValidationStatementTrue _ -> None - | ValidationStatementFalse st + match isValidStatement p with + | ValidationStatementTrue _ -> None + | ValidationStatementFalse st | ValidationStatement st -> Some st) |> List.unzip aaa |> DAstUtilFunctions.nestItems_ret l |> Option.toList, (lv1|> List.collect id) - let with_component_check, lv2 = + let with_component_check, lv2 = let a, b = convertMultipleVCBsToStatementAndSetErrorCode l p errCode vcbs |> List.unzip a, (b |> List.collect id) match (with_component_check@childrenChecks) |> DAstUtilFunctions.nestItems_ret l with - | None -> convertVCBToStatementAndAssigneErrCode l VCBTrue errCode.errCodeName + | None -> convertVCBToStatementAndAssignedErrCode l VCBTrue errCode.errCodeName | Some s ->ValidationStatement (s, lv1@lv2) - + let errorCodeComment = o.cons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" createIsValidFunction r l t funBody typeDefinition alphaFuncs localVars childrenErrCodes nonEmbeddedChildrenValidFuncs (Some errorCodeComment) ns2 -let rec createReferenceTypeFunction_this_type (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (refTypeId:ReferenceToType) (refCons:Asn1AcnAst.AnyConstraint list) (typeDefinition:TypeDefintionOrReference) (resolvedType:Asn1Type) (us:State) = +let rec createReferenceTypeFunction_this_type (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (refTypeId:ReferenceToType) (refCons:Asn1AcnAst.AnyConstraint list) (typeDefinition:TypeDefinitionOrReference) (resolvedType:Asn1Type) (us:State) = match resolvedType.Kind with | Sequence sq -> let asn1Children = sq.children |> List.choose(fun c -> match c with Asn1Child x -> Some x | AcnChild _ -> None) @@ -930,7 +914,7 @@ let rec createReferenceTypeFunction_this_type (r:Asn1AcnAst.AstRoot) (l:Language cons |> Asn1Fold.foldMap (fun us c -> realConstraint2ValidationCodeBlock l c us) us | Boolean _ -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.BoolConstraint z -> Some z | _ -> None ) - cons |> Asn1Fold.foldMap (fun us c -> booleanConstraint2ValidationCodeBlock l c us) us + cons |> Asn1Fold.foldMap (fun us c -> booleanConstraint2ValidationCodeBlock l c us) us | OctetString oc -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.OctetStringConstraint z -> Some z | _ -> None ) cons |> Asn1Fold.foldMap (fun us c -> octetStringConstraint2ValidationCodeBlock r l refTypeId oc.baseInfo resolvedType.equalFunction c us) us @@ -939,7 +923,7 @@ let rec createReferenceTypeFunction_this_type (r:Asn1AcnAst.AstRoot) (l:Language cons |> Asn1Fold.foldMap (fun us c -> bitStringConstraint2ValidationCodeBlock r l refTypeId bs.baseInfo resolvedType.equalFunction c us) us | IA5String st -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.IA5StringConstraint z -> Some z | _ -> None ) - cons |> Asn1Fold.foldMap (fun us c -> ia5StringConstraint2ValidationCodeBlock r l refTypeId c us) {us with alphaIndex=0; alphaFuncs=[]} + cons |> Asn1Fold.foldMap (fun us c -> ia5StringConstraint2ValidationCodeBlock r l refTypeId c us) {us with alphaIndex=0; alphaFuncs=[]} | ObjectIdentifier _ -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.ObjectIdConstraint z -> Some z | _ -> None ) cons |> Asn1Fold.foldMap (fun us c -> objIdConstraint2ValidationCodeBlock l c us) us @@ -950,75 +934,68 @@ let rec createReferenceTypeFunction_this_type (r:Asn1AcnAst.AstRoot) (l:Language [],us | Enumerated en -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.EnumConstraint z -> Some z | _ -> None ) - cons |> Asn1Fold.foldMap (fun us c -> enumeratedConstraint2ValidationCodeBlock l en.baseInfo typeDefinition c us) us + cons |> Asn1Fold.foldMap (fun us c -> enumeratedConstraint2ValidationCodeBlock l en.baseInfo typeDefinition c us) us | Choice ch -> let valToStrFunc (p:CallerScope) (v:Asn1AcnAst.ChValue) = VCBTrue let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.ChoiceConstraint z -> Some z | _ -> None ) - cons |> Asn1Fold.foldMap(fun cs c -> choiceConstraint2ValidationCodeBlock r l refTypeId ch.children valToStrFunc typeDefinition c cs) us + cons |> Asn1Fold.foldMap(fun cs c -> choiceConstraint2ValidationCodeBlock r l refTypeId ch.children valToStrFunc typeDefinition c cs) us | SequenceOf sqo -> let cons = refCons |> List.choose(fun c -> match c with Asn1AcnAst.SequenceOfConstraint z -> Some z | _ -> None ) - cons |> Asn1Fold.foldMap(fun cs c -> sequenceOfConstraint2ValidationCodeBlock r l refTypeId sqo.baseInfo sqo.childType resolvedType.equalFunction c cs) us + cons |> Asn1Fold.foldMap(fun cs c -> sequenceOfConstraint2ValidationCodeBlock r l refTypeId sqo.baseInfo sqo.childType resolvedType.equalFunction c cs) us -let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefintionOrReference) (resolvedType:Asn1Type) (us:State) = +let createReferenceTypeFunction (r:Asn1AcnAst.AstRoot) (l:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ReferenceType) (typeDefinition:TypeDefinitionOrReference) (resolvedType:Asn1Type) (us:State) = let callBaseTypeFunc = l.isvalid.call_base_type_func - if (t.id.AsString = "TEST-CASE.T-STRUCT.member") then - printf "%s" t.id.AsString let vcbs,us = createReferenceTypeFunction_this_type r l t.id o.refCons typeDefinition resolvedType us - (* - let moduleName, typeDefinitionName = - let t1 = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName - let typeDef = l.lg.getTypeDefinition t1.FT_TypeDefintion - typeDef.programUnit, typeDef.typeName -*) - let moduleName, typeDefinitionName, baseTypeDefinitionName = + + let moduleName, typeDefinitionName, baseTypeDefinitionName = match typeDefinition with | ReferenceToExistingDefinition refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName, refToExist.typedefName | None -> ToC t.id.ModName, refToExist.typedefName, refToExist.typedefName - | TypeDefinition tdDef -> + | TypeDefinition tdDef -> match tdDef.baseType with | None -> ToC t.id.ModName, tdDef.typedefName, ToC2(r.args.TypePrefix + o.tasName.Value) - | Some refToExist -> + | Some refToExist -> match refToExist.programUnit with | Some md -> md, refToExist.typedefName, refToExist.typedefName | None -> ToC t.id.ModName, refToExist.typedefName, refToExist.typedefName let soTypeCasting = let actType = Asn1AcnAstUtilFunctions.GetActualTypeByName r o.modName o.tasName match t.ActualType.Kind, actType.Kind with - | Asn1AcnAst.Integer o, Asn1AcnAst.Integer res -> + | Asn1AcnAst.Integer o, Asn1AcnAst.Integer res -> match o.intClass = res.intClass with | true -> None | false -> Some typeDefinitionName | _ -> None - let baseFncName = + let baseFncName = match l.lg.hasModules with | false -> baseTypeDefinitionName + "_IsConstraintValid" - | true -> + | true -> match t.id.ModName = o.modName.Value with | true -> baseTypeDefinitionName + "_IsConstraintValid" | false -> moduleName + "." + baseTypeDefinitionName + "_IsConstraintValid" - let funBody (errCode: ErroCode) (p:CallerScope) = - let with_component_check, lv2 = + let funBody (errCode: ErrorCode) (p:CallerScope) = + let with_component_check, lv2 = convertMultipleVCBsToStatementAndSetErrorCode l p errCode vcbs |> List.unzip match resolvedType.isValidFunction with - | Some _ -> + | Some _ -> let funcBodyContent = callBaseTypeFunc (l.lg.getParamValue t p.arg Encode) baseFncName soTypeCasting match (funcBodyContent::with_component_check) |> DAstUtilFunctions.nestItems_ret l with - | None -> convertVCBToStatementAndAssigneErrCode l VCBTrue errCode.errCodeName + | None -> convertVCBToStatementAndAssignedErrCode l VCBTrue errCode.errCodeName | Some s ->ValidationStatement (s, (lv2 |>List.collect id)) - | None -> + | None -> match (with_component_check) |> DAstUtilFunctions.nestItems_ret l with - | None -> convertVCBToStatementAndAssigneErrCode l VCBTrue errCode.errCodeName + | None -> convertVCBToStatementAndAssignedErrCode l VCBTrue errCode.errCodeName | Some s ->ValidationStatement (s, (lv2 |>List.collect id)) let errorCodeComment = o.refCons |> List.map(fun z -> z.ASN1) |> Seq.StrJoin "" - + createIsValidFunction r l t funBody typeDefinition [] [] [] [] (Some errorCodeComment) us diff --git a/BackendAst/EncodeDecodeTestCase.fs b/BackendAst/EncodeDecodeTestCase.fs index 35553a317..ffccc7f08 100644 --- a/BackendAst/EncodeDecodeTestCase.fs +++ b/BackendAst/EncodeDecodeTestCase.fs @@ -23,7 +23,7 @@ let getFuncName (r:Asn1AcnAst.AstRoot) (sEncoding:string) (typeId:ReferenceToTy type StatementKind = - //|Update_DecIn of AcnTypes.AcnParameter + //|Update_DecIn of AcnTypes.AcnParameter |Encode_input |Decode_output |Validate_output @@ -39,17 +39,17 @@ let OptFlatMap fun1 u = | None -> None | Some uuu -> fun1 uuu -let rec getAmberDecode (t:Asn1AcnAst.Asn1Type) = +let rec getAmberDecode (t:Asn1AcnAst.Asn1Type) = match t.Kind with | Asn1AcnAst.IA5String _ -> "" | Asn1AcnAst.NumericString _ -> "" | Asn1AcnAst.ReferenceType z -> getAmberDecode z.resolvedType | _ -> "&" -let _createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : UPerFunction option) (decFunc : UPerFunction option) (us:State) = +let _createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : UPerFunction option) (decFunc : UPerFunction option) (us:State) = let sEnc = lm.lg.atc.uperPrefix - let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefintion) + let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefinition) let modName = ToC t.id.AcnAbsPath.Head let printCodec_body = lm.atc.PrintCodec_body @@ -62,17 +62,17 @@ let _createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1 let write_bitstreamToFile = lm.atc.Codec_write_bitstreamToFile let p = lm.lg.getParamType t Encode // t.getParamType l Encode - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg //p.arg.getStar l let sAmberDecode = getAmberDecode t let sAmberIsValid = getAmberDecode t - + match funcName with | None -> None, us - | Some funcName -> - - let printStatement stm sNestedContent = - let content= + | Some funcName -> + + let printStatement stm sNestedContent = + let content= match stm with |Encode_input -> option { let! encF = encFunc @@ -82,60 +82,60 @@ let _createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1 |Decode_output -> option { let! decF = decFunc let! decFunName = decF.funcName - return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode + return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode } - - |Validate_output -> + + |Validate_output -> option { let! f = isValidFunc let! fname = f.funcName return validateOutput modName fname sAmberIsValid } - |Compare_input_output -> + |Compare_input_output -> option { let! fname = eqFunc.isEqualFuncName return compareInputWithOutput modName fname varName sAmberIsValid - } + } |Write_bitstream_to_file -> option { return write_bitstreamToFile () - } + } joinItems (content.orElse "") sNestedContent match hasUperEncodeFunction encFunc with | true -> - let sNestedStatements = - let rec printStatements statements : string option = + let sNestedStatements = + let rec printStatements statements : string option = match statements with |[] -> None - |x::xs -> + |x::xs -> match printStatements xs with | None -> Some (printStatement x None) | Some childrenCont -> Some (printStatement x (Some childrenCont)) printStatements [Encode_input; Decode_output; Validate_output; Compare_input_output; Write_bitstream_to_file] - let func = + let func = printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName "" (sNestedStatements.orElse "") "UPER" let funcDef = printCodec_body_header funcName modName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName - let ret = + let ret = { EncodeDecodeTestFunc.funcName = funcName - func = func + func = func funcDef = funcDef } Some ret, us | false -> None, us -let createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : UPerFunction option) (decFunc : UPerFunction option) (us:State) = +let createUperEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : UPerFunction option) (decFunc : UPerFunction option) (us:State) = match r.args.generateAutomaticTestCases with | true -> _createUperEncDecFunction r lm t typeDefinition eqFunc isValidFunc encFunc decFunc us | false -> None, us -let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : AcnFunction option) (decFunc : AcnFunction option) (us:State) = +let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : AcnFunction option) (decFunc : AcnFunction option) (us:State) = //let sEnc = match ST.lang with | Scala -> "ACN" | _ -> lm.lg.atc.acnPrefix let sEnc = lm.lg.atc.acnPrefix - let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefintion) + let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefinition) let modName = ToC t.id.AcnAbsPath.Head let printCodec_body = lm.atc.PrintCodec_body @@ -148,7 +148,7 @@ let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let write_bitstreamToFile = lm.atc.Codec_write_bitstreamToFile let p = lm.lg.getParamType t Encode - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let sAmberDecode = getAmberDecode t let sAmberIsValid = getAmberDecode t @@ -158,9 +158,9 @@ let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A | true -> match funcName with | None -> None, us - | Some funcName -> - let printStatement stm sNestedContent = - let content= + | Some funcName -> + let printStatement stm sNestedContent = + let content= match stm with |Encode_input -> option { let! encF = encFunc @@ -170,32 +170,32 @@ let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A |Decode_output -> option { let! decF = decFunc let! decFunName = decF.funcName - return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode + return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode } - - |Validate_output -> + + |Validate_output -> option { let! f = isValidFunc let! fname = f.funcName return validateOutput modName fname sAmberIsValid } - |Compare_input_output -> + |Compare_input_output -> option { let! fname = eqFunc.isEqualFuncName return compareInputWithOutput modName fname varName sAmberIsValid - } + } |Write_bitstream_to_file -> option { return write_bitstreamToFile () - } + } joinItems (content.orElse "") sNestedContent match hasAcnEncodeFunction encFunc t.acnParameters with - | true -> - let sNestedStatements = - let rec printStatements statements : string option = + | true -> + let sNestedStatements = + let rec printStatements statements : string option = match statements with |[] -> None - |x::xs -> + |x::xs -> match printStatements xs with | None -> Some (printStatement x None) | Some childrenCont -> Some (printStatement x (Some childrenCont)) @@ -204,25 +204,25 @@ let _createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let func = printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName sEnc (sNestedStatements.orElse "") "ACN" let funcDef = printCodec_body_header funcName modName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName - - let ret = + + let ret = { EncodeDecodeTestFunc.funcName = funcName - func = func + func = func funcDef = funcDef } Some ret, us | false -> None, us -let createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : AcnFunction option) (decFunc : AcnFunction option) (us:State) = +let createAcnEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : AcnFunction option) (decFunc : AcnFunction option) (us:State) = match r.args.generateAutomaticTestCases with | true -> _createAcnEncDecFunction r lm t typeDefinition eqFunc isValidFunc encFunc decFunc us | false -> None, us -let _createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : XerFunctionRec) (decFunc : XerFunctionRec) (us:State) = +let _createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : XerFunctionRec) (decFunc : XerFunctionRec) (us:State) = let sEnc = lm.lg.atc.xerPrefix - let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefintion) + let funcName = getFuncName r sEnc t.id (lm.lg.getTypeDefinition t.FT_TypeDefinition) let modName = ToC t.id.AcnAbsPath.Head let printCodec_body = lm.atc.PrintCodec_body_XER @@ -235,17 +235,17 @@ let _createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let compareInputWithOutput = lm.atc.Codec_compare_input_with_output let p = lm.lg.getParamType t Encode - let varName = p.arg.p + let varName = p.arg.receiverId let sStar = lm.lg.getStar p.arg let sAmberDecode = getAmberDecode t let sAmberIsValid = getAmberDecode t - + match funcName with | None -> None, us - | Some funcName -> - - let printStatement stm sNestedContent = - let content= + | Some funcName -> + + let printStatement stm sNestedContent = + let content= match stm with |Encode_input -> option { let encF = encFunc @@ -255,30 +255,30 @@ let _createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A |Decode_output -> option { let decF = decFunc let! decFunName = decF.funcName - return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode + return decode modName decFunName (typeDefinition.longTypedefName2 lm.lg.hasModules) sEnc sAmberDecode } - - |Validate_output -> + + |Validate_output -> option { let! f = isValidFunc let! fname = f.funcName return validateOutput modName fname sAmberIsValid } - |Compare_input_output -> + |Compare_input_output -> option { let! fname = eqFunc.isEqualFuncName return compareInputWithOutput modName fname varName sAmberIsValid - } + } |Write_bitstream_to_file -> option { return write_bitstreamToFile () - } + } joinItems (content.orElse "") sNestedContent - let sNestedStatements = - let rec printStatements statements : string option = + let sNestedStatements = + let rec printStatements statements : string option = match statements with |[] -> None - |x::xs -> + |x::xs -> match printStatements xs with | None -> Some (printStatement x None) | Some childrenCont -> Some (printStatement x (Some childrenCont)) @@ -286,18 +286,18 @@ let _createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1A let func = printCodec_body modName funcName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName sEnc (sNestedStatements.orElse "") let funcDef = printCodec_body_header funcName modName (typeDefinition.longTypedefName2 lm.lg.hasModules) sStar varName - let ret = + let ret = { EncodeDecodeTestFunc.funcName = funcName - func = func + func = func funcDef = funcDef } Some ret, us -let createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefintionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : XerFunction) (decFunc : XerFunction) (us:State) = +let createXerEncDecFunction (r:Asn1AcnAst.AstRoot) (lm:LanguageMacros) (t:Asn1AcnAst.Asn1Type) (typeDefinition:TypeDefinitionOrReference) (eqFunc:EqualFunction) (isValidFunc: IsValidFunction option) (encFunc : XerFunction) (decFunc : XerFunction) (us:State) = match r.args.generateAutomaticTestCases with - | true -> + | true -> match encFunc, decFunc with | XerFunction encFunc, XerFunction decFunc -> _createXerEncDecFunction r lm t typeDefinition eqFunc isValidFunc encFunc decFunc us @@ -323,12 +323,12 @@ let foldGenericCon (c:GenericConstraint<'v>) = (fun _ e1 e2 s -> e1@e2, s) (fun _ v s -> [v] ,s) c - 0 |> fst + 0 |> fst let foldRangeCon getNext getPrev min max zero (c:RangeTypeConstraint<'v1,'v1>) = - foldRangeTypeConstraint + foldRangeTypeConstraint (fun _ e1 e2 b s -> e1@e2, s) //union (fun _ e1 e2 s -> e1@e2, s) //Intersection (fun _ e s -> [], s) //AllExcept @@ -336,12 +336,12 @@ let foldRangeCon getNext getPrev min max zero (c:RangeTypeConstraint<'v1,'v1>) (fun _ e s -> e, s) //RootConstraint (fun _ e1 e2 s -> e1@e2, s) //RootConstraint2 (fun _ v s -> [v] ,s) // SingleValueConstraint - (fun _ v1 v2 minIsIn maxIsIn s -> //RangeContraint + (fun _ v1 v2 minIsIn maxIsIn s -> //RangeConstraint [(if minIsIn then v1 else (getNext v1));(if maxIsIn then v2 else (getPrev v2))], s) - (fun _ v1 minIsIn s -> [(if minIsIn then v1 else (getNext v1)); max], s) //Contraint_val_MAX - (fun _ v2 maxIsIn s -> [min; (if maxIsIn then v2 else (getPrev v2))], s) //Contraint_MIN_val + (fun _ v1 minIsIn s -> [(if minIsIn then v1 else (getNext v1)); max], s) //Constraint_val_MAX + (fun _ v2 maxIsIn s -> [min; (if maxIsIn then v2 else (getPrev v2))], s) //Constraint_MIN_val c - 0 |> fst + 0 |> fst let foldSizableConstraint (c:SizableTypeConstraint<'v>) = foldSizableTypeConstraint2 @@ -367,14 +367,14 @@ let IntegerAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Typ let getPrev a = match a > min with true -> a - 1I | false -> min match allCons with | [] -> [min; 0I; max] |> Seq.distinct |> Seq.toList - | _ -> + | _ -> let ret = allCons |> List.collect (foldRangeCon getNext getPrev min max 0I ) |> Seq.distinct |> Seq.toList let aaa = ret |> List.filter (isValidValueRanged allCons) aaa let RealAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Real) = let allCons = o.AllCons - let min, max = + let min, max = match r.args.floatingPointSizeInBytes = 4I with | true -> (double Single.MinValue/10.0), (double Single.MaxValue/10.0) | false -> @@ -385,10 +385,10 @@ let RealAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) | Real_IEEE754_32_little_endian -> (double Single.MinValue), (double Single.MaxValue) | Real_IEEE754_64_little_endian -> Double.MinValue, Double.MaxValue - + match allCons with - | [] -> [min; 0.0; max] - | _ -> + | [] -> [min; 0.0; max] + | _ -> let ret = allCons |> List.collect (foldRangeCon id id min max 0.0 ) |> Seq.distinct |> Seq.toList let aaa = ret |> List.filter (isValidValueRanged allCons) aaa @@ -400,29 +400,29 @@ let EnumeratedAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1 | _ -> allItems |> List.filter (isValidValueGeneric o.AllCons (=)) let EnumeratedAutomaticTestCaseValues2 (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Enumerated) = - let allItems = o.items + let allItems = o.items match o.AllCons with | [] -> allItems | _ -> allItems |> List.filter (isValidValueGeneric o.AllCons (fun a b -> a = b.Name.Value)) - + let BooleanAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.Boolean) = let allItems = [true; false] match o.AllCons with | [] -> allItems | _ -> allItems |> List.filter (isValidValueGeneric o.AllCons (=)) - + let ObjectIdentifierAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.ObjectIdentifier) = let sv = o.AllCons |> List.map(fun c -> foldGenericCon c ) |> List.collect id match sv with | [] -> [[0I; 1I]; [0I .. r.args.objectIdentifierMaxLength - 1I]] | _ -> sv |> List.map (fun (resLis,_) -> resLis |> List.map(fun c -> DAstUtilFunctions.emitComponent c |> fst)) - + let TimeTypeAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type) (o:Asn1AcnAst.TimeType) = let sv = o.AllCons |> List.map(fun c -> foldGenericCon c ) |> List.collect id match sv with - | [] -> + | [] -> let tv = {Asn1TimeValue.hours = 0I; mins=0I; secs=0I; secsFraction = None} let tz = {Asn1TimeZoneValue.sign = 1I; hours = 2I; mins=0I} let dt = {Asn1DateValue.years = 2019I; months = 12I; days = 25I} @@ -442,14 +442,14 @@ let StringAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1Type let maxItems = 32767I match o.minSize.uper > maxItems with | true -> [] // the generated string will be very large - | false -> + | false -> match o.uperCharSet |> Seq.filter(fun c -> not (System.Char.IsControl c)) |> Seq.toList with - | chr::_ -> - let s1 = System.String(chr, int o.minSize.uper) + | chr::_ -> + let s1 = System.String(chr, int o.minSize.uper) match o.minSize.uper = o.maxSize.uper || o.maxSize.uper > maxItems with - | true -> [s1] + | true -> [s1] | false -> - let s2 = System.String(chr, int o.maxSize.uper) + let s2 = System.String(chr, int o.maxSize.uper) [s1;s2] | [] -> [] @@ -460,10 +460,10 @@ let OctetStringAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn | [] -> match o.minSize.uper > maxItems with | true -> [] // the generated string will be very large - | false -> + | false -> let s1 = [1 .. int o.minSize.uper] |> List.map (fun i -> 0uy) match o.minSize.uper = o.maxSize.uper || o.maxSize.uper > maxItems with - | true -> [s1] + | true -> [s1] | false -> let s2 = [1 .. int o.maxSize.uper] |> List.map (fun i -> 0uy) [s1;s2] @@ -476,10 +476,10 @@ let BitStringAutomaticTestCaseValues (r:Asn1AcnAst.AstRoot) (t:Asn1AcnAst.Asn1T | [] -> match o.minSize.uper > maxItems with | true -> [] // the generated string will be very large - | false -> + | false -> let s1 = System.String('0', int o.minSize.uper) match o.minSize.uper = o.maxSize.uper || o.maxSize.uper > maxItems with - | true -> [s1] + | true -> [s1] | false -> let s2 = System.String('0', int o.maxSize.uper) [s1;s2] diff --git a/BackendAst/GenerateAcnIcd.fs b/BackendAst/GenerateAcnIcd.fs index 21288c279..6fdf0bfd9 100644 --- a/BackendAst/GenerateAcnIcd.fs +++ b/BackendAst/GenerateAcnIcd.fs @@ -35,7 +35,7 @@ let PrintAcnAsHTML stgFileName (r:AstRoot) = let colorize (t: IToken, tasses: string array) = let lt = icd_acn.LeftDiple stgFileName () let gt = icd_acn.RightDiple stgFileName () - let containedIn = Array.exists (fun elem -> elem = t.Text) + let containedIn = Array.exists (fun elem -> elem = t.Text) let isAcnKeyword = acnTokens.Contains t.Text let isType = containedIn tasses let safeText = t.Text.Replace("<",lt).Replace(">",gt) @@ -54,19 +54,19 @@ let PrintAcnAsHTML stgFileName (r:AstRoot) = if isAcnKeyword then icd_acn.AcnKeyword stgFileName safeText else colored let tasNames = r.Files |> Seq.collect(fun f -> f.Modules) |> Seq.collect(fun x -> x.TypeAssignments) |> Seq.map(fun x -> x.Name.Value) |> Seq.toArray - + r.acnParseResults |> Seq.map(fun pr -> pr.fileName, pr.tokens) |> - Seq.map(fun (fName, tokens) -> + Seq.map(fun (fName, tokens) -> //let f = r.Files |> Seq.find(fun x -> Path.GetFileNameWithoutExtension(x.FileName) = Path.GetFileNameWithoutExtension(fName)) //let tasNames = f.Modules |> Seq.collect(fun x -> x.TypeAssignments) |> Seq.map(fun x -> x.Name.Value) |> Seq.toArray let content = tokens |> Seq.map(fun token -> colorize(token,tasNames)) - icd_acn.EmmitFilePart2 stgFileName (Path.GetFileName fName) (content |> Seq.StrJoin "") + icd_acn.EmitFilePart2 stgFileName (Path.GetFileName fName) (content |> Seq.StrJoin "") ) let PrintAcnAsHTML2 stgFileName (r:AstRoot) = - let fileTypeAssignments = - r.icdHashes.Values |> + let fileTypeAssignments = + r.icdHashes.Values |> Seq.collect id |> Seq.choose(fun z -> match z.tasInfo with @@ -92,14 +92,14 @@ let PrintAcnAsHTML2 stgFileName (r:AstRoot) = |acnLexer.COMMENT2 -> icd_acn.Comment stgFileName safeText |_ -> safeText if isAcnKeyword then icd_acn.AcnKeyword stgFileName safeText else colored - + r.acnParseResults |> Seq.map(fun pr -> pr.fileName, pr.tokens) |> - Seq.map(fun (fName, tokens) -> + Seq.map(fun (fName, tokens) -> //let f = r.Files |> Seq.find(fun x -> Path.GetFileNameWithoutExtension(x.FileName) = Path.GetFileNameWithoutExtension(fName)) //let tasNames = f.Modules |> Seq.collect(fun x -> x.TypeAssignments) |> Seq.map(fun x -> x.Name.Value) |> Seq.toArray let content = tokens |> Seq.map(fun token -> colorize(token)) - icd_acn.EmmitFilePart2 stgFileName (Path.GetFileName fName) (content |> Seq.StrJoin "") + icd_acn.EmitFilePart2 stgFileName (Path.GetFileName fName) (content |> Seq.StrJoin "") ) let foldGenericCon = GenerateUperIcd.foldGenericCon @@ -118,18 +118,18 @@ type SequenceRow = { noAlignToNextSize : string soUnit : string option } -let enumStg : GenerateUperIcd.StgCommentLineMacros = +let enumStg : GenerateUperIcd.StgCommentLineMacros = { - NewLine = icd_acn.NewLine - EmitEnumItem = icd_acn.EmitEnumItem - EmitEnumItemWithComment = icd_acn.EmitEnumItemWithComment + NewLine = icd_acn.NewLine + EmitEnumItem = icd_acn.EmitEnumItem + EmitEnumItemWithComment = icd_acn.EmitEnumItemWithComment EmitEnumInternalContents = icd_acn.EmitEnumInternalContents - } + } let handleNullType stgFileName (encodingPattern : AcnGenericTypes.PATTERN_PROP_VALUE option) defaultRetValue = match encodingPattern with | Some(AcnGenericTypes.PATTERN_PROP_BITSTR_VALUE bitStr) -> icd_acn.NullTypeWithBitPattern stgFileName bitStr.Value - | Some(AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE byteList )-> icd_acn.NullTypeWithBytePattern stgFileName (byteList |> List.map (fun z -> z.Value)) + | Some(AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE byteList )-> icd_acn.NullTypeWithBytePattern stgFileName (byteList |> List.map (fun z -> z.Value)) | None -> defaultRetValue @@ -138,7 +138,7 @@ let emitSequenceComponent (r:AstRoot) stgFileName (optionalLikeUperChildren:Asn1 let GetCommentLine = GenerateUperIcd.GetCommentLineFactory stgFileName enumStg let sClass = if i % 2 = 0 then (icd_acn.EvenRow stgFileName ()) else (icd_acn.OddRow stgFileName ()) let nIndex = BigInteger i - let sPresentWhen, bAlwaysAbsent = + let sPresentWhen, bAlwaysAbsent = match ch with | AcnChild _ -> "always", false | Asn1Child ch -> @@ -153,7 +153,7 @@ let emitSequenceComponent (r:AstRoot) stgFileName (optionalLikeUperChildren:Asn1 | Some(Asn1AcnAst.AlwaysAbsent) -> "never", true | Some(Asn1AcnAst.Optional opt) -> match opt.acnPresentWhen with - | None -> + | None -> let nBit = optionalLikeUperChildren |> Seq.findIndex(fun x -> x.Name.Value = ch.Name.Value) |> (+) 1 sprintf "when the %d%s bit of the bit mask is set" nBit (aux1 nBit), false | Some (AcnGenericTypes.PresenceWhenBool presWhen) -> @@ -164,60 +164,60 @@ let emitSequenceComponent (r:AstRoot) stgFileName (optionalLikeUperChildren:Asn1 let _, debugStr = AcnGenericCreateFromAntlr.printDebug acnExp sprintf "when %s is true" debugStr, false - let sType, sComment, sAsn1Constraints, nAlignToNextSize, soUnit = + let sType, sComment, sAsn1Constraints, nAlignToNextSize, soUnit = match ch with | Asn1Child ch -> - let sType = - let defaultRetValue = + let sType = + let defaultRetValue = match ch.Type.Kind with - | ReferenceType o when not o.baseInfo.hasExtraConstrainsOrChildrenOrAcnArgs -> - icd_acn.EmmitSeqChild_RefType stgFileName ch.Type.FT_TypeDefintion.[CommonTypes.C].asn1Name (ToC ch.Type.FT_TypeDefintion.[CommonTypes.C].asn1Name) + | ReferenceType o when not o.baseInfo.hasExtraConstrainsOrChildrenOrAcnArgs -> + icd_acn.EmitSeqChild_RefType stgFileName ch.Type.FT_TypeDefinition.[CommonTypes.C].asn1Name (ToC ch.Type.FT_TypeDefinition.[CommonTypes.C].asn1Name) | OctetString o -> "OCTET STRING" | _ -> match ch.Type.ActualType.Kind with | Sequence _ | Choice _ - | SequenceOf _ -> - icd_acn.EmmitSeqChild_RefType stgFileName ch.Type.id.AsString.RDD (ToC ch.Type.id.AsString.RDD) + | SequenceOf _ -> + icd_acn.EmitSeqChild_RefType stgFileName ch.Type.id.AsString.RDD (ToC ch.Type.id.AsString.RDD) | _ -> - icd_acn.EmmitSeqChild_RefType stgFileName ch.Type.FT_TypeDefintion.[CommonTypes.C].asn1Name (ToC ch.Type.FT_TypeDefintion.[CommonTypes.C].asn1Name) + icd_acn.EmitSeqChild_RefType stgFileName ch.Type.FT_TypeDefinition.[CommonTypes.C].asn1Name (ToC ch.Type.FT_TypeDefinition.[CommonTypes.C].asn1Name) match ch.Type.ActualType.Kind with - | DAst.NullType o when o.baseInfo.acnProperties.encodingPattern.IsSome -> + | DAst.NullType o when o.baseInfo.acnProperties.encodingPattern.IsSome -> handleNullType stgFileName o.baseInfo.acnProperties.encodingPattern defaultRetValue | _ -> defaultRetValue let soUnit = GenerateUperIcd.getUnits ch.Type - sType, GetCommentLine ch.Comments ch.Type, ch.Type.ConstraintsAsn1Str |> Seq.StrJoin "", AcnEncodingClasses.getAlignmentSize ch.Type.acnAligment, soUnit + sType, GetCommentLine ch.Comments ch.Type, ch.Type.ConstraintsAsn1Str |> Seq.StrJoin "", AcnEncodingClasses.getAlignmentSize ch.Type.acnAlignment, soUnit | AcnChild ch -> let commentLine = - ch.Comments |> Seq.StrJoin (enumStg.NewLine stgFileName ()) - + ch.Comments |> Seq.StrJoin (enumStg.NewLine stgFileName ()) - let sType,consAsStt = + + let sType,consAsStt = match ch.Type with - | Asn1AcnAst.AcnInteger o -> + | Asn1AcnAst.AcnInteger o -> let constAsStr = DAstAsn1.createAcnInteger (o.cons@o.withcons) |> Seq.StrJoin "" match o.inheritInfo with | None -> icd_acn.Integer stgFileName () , constAsStr - | Some inhInfo -> icd_acn.EmmitSeqChild_RefType stgFileName inhInfo.tasName (ToC inhInfo.tasName) , constAsStr - | Asn1AcnAst.AcnNullType o -> + | Some inhInfo -> icd_acn.EmitSeqChild_RefType stgFileName inhInfo.tasName (ToC inhInfo.tasName) , constAsStr + | Asn1AcnAst.AcnNullType o -> let sType = handleNullType stgFileName o.acnProperties.encodingPattern (icd_acn.NullType stgFileName ()) sType, "" | Asn1AcnAst.AcnBoolean o -> icd_acn.Boolean stgFileName (), "" - | Asn1AcnAst.AcnReferenceToEnumerated o -> icd_acn.EmmitSeqChild_RefType stgFileName o.tasName.Value (ToC o.tasName.Value), "" - | Asn1AcnAst.AcnReferenceToIA5String o -> icd_acn.EmmitSeqChild_RefType stgFileName o.tasName.Value (ToC o.tasName.Value), "" - sType, commentLine, consAsStt, AcnEncodingClasses.getAlignmentSize ch.Type.acnAligment, None + | Asn1AcnAst.AcnReferenceToEnumerated o -> icd_acn.EmitSeqChild_RefType stgFileName o.tasName.Value (ToC o.tasName.Value), "" + | Asn1AcnAst.AcnReferenceToIA5String o -> icd_acn.EmitSeqChild_RefType stgFileName o.tasName.Value (ToC o.tasName.Value), "" + sType, commentLine, consAsStt, AcnEncodingClasses.getAlignmentSize ch.Type.acnAlignment, None let name = ch.Name let noAlignToNextSize = if nAlignToNextSize = 0I then None else (Some nAlignToNextSize) let acnMaxSizeInBits = ch.acnMaxSizeInBits - nAlignToNextSize let acnMinSizeInBits = (if bAlwaysAbsent then 0I else ch.acnMinSizeInBits) - nAlignToNextSize let sMaxBits, sMaxBytes = acnMaxSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(acnMaxSizeInBits)/8.0)).ToString() let sMinBits, sMinBytes = acnMinSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(acnMinSizeInBits)/8.0)).ToString() - icd_acn.EmmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits noAlignToNextSize soUnit + icd_acn.EmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits noAlignToNextSize soUnit let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Type) (m:Asn1Module) (r:AstRoot) isAnonymousType : string list= let GetCommentLine = GenerateUperIcd.GetCommentLineFactory stgFileName enumStg - + let hasAcnDef = r.acnParseResults |> Seq.collect (fun p -> p.tokens) |> Seq.exists(fun x -> x.Text = tas.name) let sTasName = tas.name @@ -226,14 +226,14 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let sMinBits, sMinBytes = t.acnMinSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(t.acnMinSizeInBits)/8.0)).ToString() let sMaxBitsExplained = "" let sCommentLine = GetCommentLine tas.comments t - let myParams colSpan= + let myParams colSpan= t.acnParameters |> - List.mapi(fun i x -> + List.mapi(fun i x -> let sType = match x.asn1Type with | AcnGenericTypes.AcnParamType.AcnPrmInteger _ -> "INTEGER" | AcnGenericTypes.AcnParamType.AcnPrmBoolean _ -> "BOOLEAN" | AcnGenericTypes.AcnParamType.AcnPrmNullType _ -> "NULL" - | AcnGenericTypes.AcnParamType.AcnPrmRefType(_,ts) -> icd_acn.EmmitSeqChild_RefType stgFileName ts.Value (ToC ts.Value) + | AcnGenericTypes.AcnParamType.AcnPrmRefType(_,ts) -> icd_acn.EmitSeqChild_RefType stgFileName ts.Value (ToC ts.Value) icd_acn.PrintParam stgFileName (i+1).AsBigInt x.name sType colSpan) @@ -244,7 +244,7 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ [ret] match t.Kind with | Integer o -> - let sAsn1Constraints = o.AllCons |> List.map (foldRangeCon (fun z -> z.ToString())) |> Seq.StrJoin "" + let sAsn1Constraints = o.AllCons |> List.map (foldRangeCon (fun z -> z.ToString())) |> Seq.StrJoin "" handlePrimitive sAsn1Constraints | Real o -> let sAsn1Constraints = o.AllCons |> List.map (foldRangeCon (fun z -> z.ToString())) |> Seq.StrJoin "" @@ -263,10 +263,10 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ handlePrimitive sAsn1Constraints |ReferenceType o when o.baseInfo.encodingOptions.IsNone -> printType stgFileName tas o.resolvedType m r isAnonymousType - |Sequence seq -> - let optionalLikeUperChildren = - seq.Asn1Children - |> Seq.filter (fun x -> + |Sequence seq -> + let optionalLikeUperChildren = + seq.Asn1Children + |> Seq.filter (fun x -> match x.Optionality with | None -> false | Some (Asn1AcnAst.Optional opt) -> @@ -274,20 +274,20 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ | Some (AcnGenericTypes.PresenceWhenBool _) -> false | Some (AcnGenericTypes.PresenceWhenBoolExpression _) -> false | None -> true - | _ -> false) + | _ -> false) |> Seq.toList let SeqPreamble = match optionalLikeUperChildren with | [] -> None | _ -> - let arrsOptWihtNoPresentWhenChildren = - optionalLikeUperChildren |> Seq.mapi(fun i c -> icd_acn.EmmitSequencePreambleSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) + let arrsOptWihtNoPresentWhenChildren = + optionalLikeUperChildren |> Seq.mapi(fun i c -> icd_acn.EmitSequencePreambleSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) let nLen = optionalLikeUperChildren |> Seq.length - let ret = icd_acn.EmmitSeqOrChoiceRow stgFileName (icd_acn.OddRow stgFileName ()) 1I "Preamble" (icd_acn.EmmitSequencePreambleComment stgFileName arrsOptWihtNoPresentWhenChildren) "always" "Bit mask" "N.A." (nLen.ToString()) (nLen.ToString()) None None + let ret = icd_acn.EmitSeqOrChoiceRow stgFileName (icd_acn.OddRow stgFileName ()) 1I "Preamble" (icd_acn.EmitSequencePreambleComment stgFileName arrsOptWihtNoPresentWhenChildren) "always" "Bit mask" "N.A." (nLen.ToString()) (nLen.ToString()) None None Some ret let emitSequenceRow (i:int, curResult:string list) (ch:SeqChildInfo) = - let di, newLines = + let di, newLines = match ch with | AcnChild _ -> 1, [emitSequenceComponent r stgFileName optionalLikeUperChildren i ch] | Asn1Child ach -> @@ -298,23 +298,23 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let lengthLine = let sClass = if i % 2 = 0 then (icd_acn.EvenRow stgFileName ()) else (icd_acn.OddRow stgFileName ()) - icd_acn.EmmitSeqOrChoiceRow stgFileName sClass (BigInteger i) "length" "uper length determinant" "???" "OCTET STRING" "N/A" sMinBits sMaxBits None None + icd_acn.EmitSeqOrChoiceRow stgFileName sClass (BigInteger i) "length" "uper length determinant" "???" "OCTET STRING" "N/A" sMinBits sMaxBits None None 1, [emitSequenceComponent r stgFileName optionalLikeUperChildren i ch] | _ -> 1, [emitSequenceComponent r stgFileName optionalLikeUperChildren i ch] *) (i+di, curResult@newLines) - let arChildren idx = - seq.children |> + let arChildren idx = + seq.children |> Seq.fold emitSequenceRow (idx, []) |> snd -// let arChildren idx = -// seq.children |> -// Seq.mapi(fun i ch -> emitSequenceComponent r stgFileName optionalLikeUperChildren (idx + i) ch ) +// let arChildren idx = +// seq.children |> +// Seq.mapi(fun i ch -> emitSequenceComponent r stgFileName optionalLikeUperChildren (idx + i) ch ) // |> Seq.toList - let childTasses = - seq.children |> - Seq.map(fun ch -> + let childTasses = + seq.children |> + Seq.map(fun ch -> match ch with | Asn1Child ch -> match ch.Type.Kind with @@ -323,14 +323,14 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ match ch.Type.ActualType.Kind with | Sequence _ | Choice _ - | SequenceOf _ -> + | SequenceOf _ -> let chTas = {tas with name=ch.Type.id.AsString.RDD; t=ch.Type; comments = Array.concat [ tas.comments; [|sprintf "Acn inline encoding in the context of %s type and %s component" tas.name ch.Name.Value|]]; isBlue = true } printType stgFileName chTas ch.Type m r isAnonymousType | _ -> [] - | AcnChild _ -> [])|> + | AcnChild _ -> [])|> Seq.collect id |> Seq.toList let arRows = - match SeqPreamble with + match SeqPreamble with | None -> arChildren 1 | Some(prm) -> prm::(arChildren 2) let seqRet = icd_acn.EmitSequenceOrChoice stgFileName isAnonymousType sTasName (ToC sTasName) hasAcnDef "SEQUENCE" sMinBytes sMaxBytes sMaxBitsExplained sCommentLine arRows (myParams 4I) (sCommentLine.Split [|'\n'|]) @@ -343,17 +343,17 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let sPresentWhen = getPresence i ch - let sType = - let defaultRetValue = icd_acn.EmmitSeqChild_RefType stgFileName ch.chType.FT_TypeDefintion.[CommonTypes.C].asn1Name (ToC ch.chType.FT_TypeDefintion.[CommonTypes.C].asn1Name) + let sType = + let defaultRetValue = icd_acn.EmitSeqChild_RefType stgFileName ch.chType.FT_TypeDefinition.[CommonTypes.C].asn1Name (ToC ch.chType.FT_TypeDefinition.[CommonTypes.C].asn1Name) match ch.chType.Kind with | ReferenceType o when not o.baseInfo.hasExtraConstrainsOrChildrenOrAcnArgs -> defaultRetValue | _ -> match ch.chType.ActualType.Kind with | Sequence _ | Choice _ - | SequenceOf _ -> - icd_acn.EmmitSeqChild_RefType stgFileName ch.chType.id.AsString.RDD (ToC ch.chType.id.AsString.RDD) - | DAst.NullType o when o.baseInfo.acnProperties.encodingPattern.IsSome -> + | SequenceOf _ -> + icd_acn.EmitSeqChild_RefType stgFileName ch.chType.id.AsString.RDD (ToC ch.chType.id.AsString.RDD) + | DAst.NullType o when o.baseInfo.acnProperties.encodingPattern.IsSome -> handleNullType stgFileName o.baseInfo.acnProperties.encodingPattern defaultRetValue | _ -> defaultRetValue @@ -361,73 +361,73 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let sMaxBits, sMaxBytes = ch.chType.acnMaxSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(ch.chType.acnMaxSizeInBits)/8.0)).ToString() let sMinBits, sMinBytes = ch.chType.acnMinSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(ch.chType.acnMinSizeInBits)/8.0)).ToString() let soUnit = GenerateUperIcd.getUnits ch.chType - icd_acn.EmmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name.Value sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits None soUnit + icd_acn.EmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name.Value sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits None soUnit let children = chInfo.children let children = children |> List.filter(fun ch -> match ch.Optionality with Some (Asn1AcnAst.ChoiceAlwaysAbsent) -> false | _ -> true) - let arrRows = + let arrRows = match chInfo.ancEncClass with - | CEC_uper -> + | CEC_uper -> let ChIndex, curI = - //let optChild = chInfo.children |> Seq.mapi(fun i c -> icd_uper.EmmitChoiceIndexSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) + //let optChild = chInfo.children |> Seq.mapi(fun i c -> icd_uper.EmitChoiceIndexSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) match children.Length <= 1 with | true -> [], 1 | false -> - let sComment = icd_acn.EmmitChoiceIndexComment stgFileName () + let sComment = icd_acn.EmitChoiceIndexComment stgFileName () let indexSize = (GetChoiceUperDeterminantLengthInBits(BigInteger(Seq.length children))).ToString() - let ret = icd_acn.EmmitSeqOrChoiceRow stgFileName (icd_acn.OddRow stgFileName ()) (BigInteger 1) "ChoiceIndex" sComment "always" "unsigned int" "N.A." indexSize indexSize None None + let ret = icd_acn.EmitSeqOrChoiceRow stgFileName (icd_acn.OddRow stgFileName ()) (BigInteger 1) "ChoiceIndex" sComment "always" "unsigned int" "N.A." indexSize indexSize None None [ret], 2 - //icd_acn.EmmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name.Value sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits + //icd_acn.EmitSeqOrChoiceRow stgFileName sClass nIndex ch.Name.Value sComment sPresentWhen sType sAsn1Constraints sMinBits sMaxBits let getPresenceWhenNone_uper (i:int) (ch:ChChildInfo) = match children.Length <= 1 with | true -> "always" | false -> - let index = children |> Seq.findIndex (fun z -> z.Name.Value = ch.Name.Value) + let index = children |> Seq.findIndex (fun z -> z.Name.Value = ch.Name.Value) sprintf "ChoiceIndex = %d" index //sprintf "ChoiceIndex = %d" i let EmitChild (i:int) (ch:ChChildInfo) = EmitSeqOrChoiceChild i ch getPresenceWhenNone_uper let arChildren = children |> Seq.mapi(fun i ch -> EmitChild (curI + i) ch) |> Seq.toList ChIndex@arChildren - | CEC_enum (r,d) -> + | CEC_enum (r,d) -> let getPresence (i:int) (ch:ChChildInfo) = let refToStr id = match id with - | ReferenceToType sn -> sn |> List.rev |> List.head |> (fun x -> x.AsString) + | ReferenceToType sn -> sn |> List.rev |> List.head |> (fun x -> x.AsString) sprintf "%s = %s" (refToStr d.id) ch.Name.Value let EmitChild (i:int) (ch:ChChildInfo) = EmitSeqOrChoiceChild i ch getPresence children |> Seq.mapi(fun i ch -> EmitChild (1 + i) ch) |> Seq.toList - | CEC_presWhen -> + | CEC_presWhen -> let getPresence (i:int) (ch:ChChildInfo) = - let getPresenceSingle (pc:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = + let getPresenceSingle (pc:AcnGenericTypes.AcnPresentWhenConditionChoiceChild) = match pc with | AcnGenericTypes.PresenceInt (rp, intLoc) -> sprintf "%s=%A" rp.AsString intLoc.Value | AcnGenericTypes.PresenceStr (rp, strLoc) -> sprintf "%s=%A" rp.AsString strLoc.Value - ch.acnPresentWhenConditions |> Seq.map getPresenceSingle |> Seq.StrJoin " AND " + ch.acnPresentWhenConditions |> Seq.map getPresenceSingle |> Seq.StrJoin " AND " let EmitChild (i:int) (ch:ChChildInfo) = EmitSeqOrChoiceChild i ch getPresence children |> Seq.mapi(fun i ch -> EmitChild (1 + i) ch) |> Seq.toList let chRet = icd_acn.EmitSequenceOrChoice stgFileName isAnonymousType sTasName (ToC sTasName) hasAcnDef "CHOICE" sMinBytes sMaxBytes sMaxBitsExplained sCommentLine arrRows (myParams 4I) (sCommentLine.Split [|'\n'|]) - let childTasses = - chInfo.children |> - Seq.map(fun ch -> + let childTasses = + chInfo.children |> + Seq.map(fun ch -> match ch.chType.Kind with | ReferenceType o when not o.baseInfo.hasExtraConstrainsOrChildrenOrAcnArgs -> [] | _ -> match ch.chType.ActualType.Kind with | Sequence _ | Choice _ - | SequenceOf _ -> + | SequenceOf _ -> let chTas = {tas with name=ch.chType.id.AsString.RDD; t=ch.chType; comments = Array.concat [ tas.comments; [|sprintf "Acn inline encoding in the context of %s type and %s component" tas.name ch.Name.Value|]]; isBlue = true } printType stgFileName chTas ch.chType m r isAnonymousType - | _ -> [] )|> + | _ -> [] )|> Seq.collect id |> Seq.toList [chRet]@childTasses | IA5String o -> let nMin, nMax, encClass = o.baseInfo.minSize.acn, o.baseInfo.maxSize.acn, o.baseInfo.acnEncodingClass - let sType, characterSizeInBits = + let sType, characterSizeInBits = match encClass with | Asn1AcnAst.Acn_Enc_String_uPER characterSizeInBits -> "NUMERIC CHARACTER" , characterSizeInBits.ToString() | Asn1AcnAst.Acn_Enc_String_uPER_Ascii characterSizeInBits -> "ASCII CHARACTER" , characterSizeInBits.ToString() - | Asn1AcnAst.Acn_Enc_String_Ascii_Null_Teminated (characterSizeInBits, nullChars) -> "ASCII CHARACTER" , characterSizeInBits.ToString() + | Asn1AcnAst.Acn_Enc_String_Ascii_Null_Terminated (characterSizeInBits, nullChars) -> "ASCII CHARACTER" , characterSizeInBits.ToString() | Asn1AcnAst.Acn_Enc_String_Ascii_External_Field_Determinant (characterSizeInBits, rp) -> "ASCII CHARACTER" , characterSizeInBits.ToString() | Asn1AcnAst.Acn_Enc_String_CharIndex_External_Field_Determinant (characterSizeInBits, rp) -> "NUMERIC CHARACTER" , characterSizeInBits.ToString() let ChildRow (lineFrom:BigInteger) (i:BigInteger) = @@ -435,31 +435,31 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let nIndex = lineFrom + i let sFieldName = icd_acn.ItemNumber stgFileName i let sComment = "" - icd_acn.EmmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType "" characterSizeInBits characterSizeInBits + icd_acn.EmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType "" characterSizeInBits characterSizeInBits let NullRow (lineFrom:BigInteger) (i:BigInteger) = let sClass = if i % 2I = 0I then icd_acn.EvenRow stgFileName () else icd_acn.OddRow stgFileName () let nIndex = lineFrom + i let sFieldName = icd_acn.ItemNumber stgFileName i let sComment = "NULL Character" - icd_acn.EmmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType "" characterSizeInBits characterSizeInBits - + icd_acn.EmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType "" characterSizeInBits characterSizeInBits + let comment = "Special field used by ACN indicating the number of items." let sCon = t.ConstraintsAsn1Str |> Seq.StrJoin "" let sCon = if sCon.Trim() ="" then "N.A." else sCon let lenDetSize = GetNumberOfBitsForNonNegativeInteger ( (o.baseInfo.maxSize.acn - o.baseInfo.minSize.acn)) let arRows, sExtraComment = match encClass with - | Asn1AcnAst.Acn_Enc_String_uPER nSizeInBits -> - let lengthLine = icd_acn.EmmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) 1I "Length" comment "unsigned int" sCon (lenDetSize.ToString()) (lenDetSize.ToString()) + | Asn1AcnAst.Acn_Enc_String_uPER nSizeInBits -> + let lengthLine = icd_acn.EmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) 1I "Length" comment "unsigned int" sCon (lenDetSize.ToString()) (lenDetSize.ToString()) lengthLine::(ChildRow 1I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 1I ( nMax))::[], "" - | Asn1AcnAst.Acn_Enc_String_uPER_Ascii nSizeInBits -> - let lengthLine = icd_acn.EmmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) 1I "Length" comment "unsigned int" sCon (lenDetSize.ToString()) (lenDetSize.ToString()) + | Asn1AcnAst.Acn_Enc_String_uPER_Ascii nSizeInBits -> + let lengthLine = icd_acn.EmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) 1I "Length" comment "unsigned int" sCon (lenDetSize.ToString()) (lenDetSize.ToString()) lengthLine::(ChildRow 1I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 1I ( nMax))::[], "" - | Asn1AcnAst.Acn_Enc_String_Ascii_Null_Teminated (nSizeInBits, nullChars) -> + | Asn1AcnAst.Acn_Enc_String_Ascii_Null_Terminated (nSizeInBits, nullChars) -> (ChildRow 0I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 0I ( nMax))::(NullRow 0I ( (nMax+1I)))::[],"" - | Asn1AcnAst.Acn_Enc_String_Ascii_External_Field_Determinant (nSizeInBits, rp) -> + | Asn1AcnAst.Acn_Enc_String_Ascii_External_Field_Determinant (nSizeInBits, rp) -> (ChildRow 0I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 0I ( nMax))::[], sprintf "Length determined by external field %s" (rp.AsString) - | Asn1AcnAst.Acn_Enc_String_CharIndex_External_Field_Determinant (nSizeInBits, rp) -> + | Asn1AcnAst.Acn_Enc_String_CharIndex_External_Field_Determinant (nSizeInBits, rp) -> (ChildRow 0I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 0I ( nMax))::[], sprintf "Length determined by external field %s" (rp.AsString) let sCommentLine = match sCommentLine with | null | "" -> sExtraComment @@ -490,7 +490,7 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let nIndex = lineFrom + i let sFieldName = icd_acn.ItemNumber stgFileName i let sComment = "" - let sType, sAsn1Constraints, sMinBits, sMaxBits = + let sType, sAsn1Constraints, sMinBits, sMaxBits = match t.Kind with | SequenceOf(seqOf) -> let child = seqOf.childType @@ -499,9 +499,9 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ let sMaxBits, sMaxBytes = child.acnMaxSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(child.acnMaxSizeInBits)/8.0)).ToString() let sMinBits, sMinBytes = child.acnMinSizeInBits.ToString(), BigInteger(System.Math.Ceiling(double(child.acnMinSizeInBits)/8.0)).ToString() let sType = - icd_acn.EmmitSeqChild_RefType stgFileName child.FT_TypeDefintion.[CommonTypes.C].asn1Name (ToC child.FT_TypeDefintion.[CommonTypes.C].asn1Name) + icd_acn.EmitSeqChild_RefType stgFileName child.FT_TypeDefinition.[CommonTypes.C].asn1Name (ToC child.FT_TypeDefinition.[CommonTypes.C].asn1Name) // match child.Kind with -// | ReferenceType ref -> icd_acn.EmmitSeqChild_RefType stgFileName ref.baseInfo.tasName.Value (ToC ref.baseInfo.tasName.Value) +// | ReferenceType ref -> icd_acn.EmitSeqChild_RefType stgFileName ref.baseInfo.tasName.Value (ToC ref.baseInfo.tasName.Value) // | _ -> Kind2Name stgFileName child sType, ret, sMinBits, sMaxBits | OctetString _ -> "OCTET", "", "8", "8" @@ -511,20 +511,20 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ | None -> raise(BugErrorException "") | Some eo -> match eo.octOrBitStr with - | ContainedInOctString -> "OCTET", "", "8", "8" + | ContainedInOctString -> "OCTET", "", "8", "8" | ContainedInBitString -> "BIT", "", "1","1" | _ -> raise(BugErrorException "") - icd_acn.EmmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType sAsn1Constraints sMinBits sMaxBits + icd_acn.EmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType sAsn1Constraints sMinBits sMaxBits let sFixedLengthComment = sprintf "Length is Fixed equal to %A, so no length determinant is encoded." nMax let arRows, sExtraComment = match encClass, nMax >= 2I with - | Asn1AcnAst.SZ_EC_FIXED_SIZE, _ - | Asn1AcnAst.SZ_EC_LENGTH_EMBEDDED _, _ -> + | Asn1AcnAst.SZ_EC_FIXED_SIZE, _ + | Asn1AcnAst.SZ_EC_LENGTH_EMBEDDED _, _ -> let sizeUperRange = CommonTypes.Concrete(nMin, nMax) let sFixedLengthComment (nMax: BigInteger) = sprintf "Length is fixed to %A elements (no length determinant is needed)." nMax let LengthRow = - let nMin, nLengthSize = + let nMin, nLengthSize = match sizeUperRange with | CommonTypes.Concrete(a,b) when a=b -> 0I, 0I | CommonTypes.Concrete(a,b) -> (GetNumberOfBitsForNonNegativeInteger(b - a)), (GetNumberOfBitsForNonNegativeInteger(b - a)) @@ -532,10 +532,10 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ | CommonTypes.PosInf(b) -> 8I, 16I | CommonTypes.Full -> 8I, 16I let comment = "Special field used by ACN to indicate the number of items present in the array." - let ret = t.ConstraintsAsn1Str |> Seq.StrJoin "" //+++ t.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" + let ret = t.ConstraintsAsn1Str |> Seq.StrJoin "" //+++ t.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" let sCon = ( if ret.Trim() ="" then "N.A." else ret) - icd_acn.EmmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) (BigInteger 1) "Length" comment "unsigned int" sCon (nMin.ToString()) (nLengthSize.ToString()) + icd_acn.EmitChoiceChild stgFileName (icd_acn.OddRow stgFileName ()) (BigInteger 1) "Length" comment "unsigned int" sCon (nMin.ToString()) (nLengthSize.ToString()) match sizeUperRange with | CommonTypes.Concrete(a,b) when a=b && b<2I -> [ChildRow 0I 1I], "The array contains a single element." @@ -547,28 +547,28 @@ let rec printType stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (t:Asn1Typ | CommonTypes.Full -> LengthRow::(ChildRow 1I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 1I 65535I)::[], "" | CommonTypes.NegInf(_) -> raise(BugErrorException "") - | Asn1AcnAst.SZ_EC_ExternalField relPath,false -> + | Asn1AcnAst.SZ_EC_ExternalField relPath,false -> (ChildRow 0I 1I)::[], sprintf "Length is determined by the external field: %s" relPath.AsString - | Asn1AcnAst.SZ_EC_ExternalField relPath,true -> + | Asn1AcnAst.SZ_EC_ExternalField relPath,true -> (ChildRow 0I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 0I (nMax))::[], sprintf "Length determined by external field %s" relPath.AsString | Asn1AcnAst.SZ_EC_TerminationPattern bitPattern, false -> (ChildRow 0I 1I)::[], sprintf "Length is determined by the stop marker '%s'" bitPattern.Value | Asn1AcnAst.SZ_EC_TerminationPattern bitPattern, true -> (ChildRow 0I 1I)::(icd_acn.EmitRowWith3Dots stgFileName ())::(ChildRow 0I (nMax))::[], sprintf "Length is determined by the stop marker '%s'" bitPattern.Value - + let sCommentLine = match sCommentLine with | null | "" -> sExtraComment | _ -> sprintf "%s%s%s" sCommentLine (icd_acn.NewLine stgFileName ()) sExtraComment - + let sizeRet = icd_acn.EmitSizeable stgFileName false (*isAnonymousType*) sTasName (ToC sTasName) hasAcnDef (Kind2Name stgFileName t) sMinBytes sMaxBytes sMaxBitsExplained (makeEmptyNull sCommentLine) arRows (myParams 2I) (sCommentLine.Split [|'\n'|]) [sizeRet] - + | other -> raise (BugErrorException $"Unsupported kind for printType: {other}") let PrintTas stgFileName (tas:GenerateUperIcd.IcdTypeAssignment) (m:Asn1Module) (r:AstRoot) = //let isAnonymousType = blueTasses |> Seq.exists (fun x -> x = tas.Name.Value) let tasses = printType stgFileName tas tas.t m r tas.isBlue - tasses |> List.map (icd_acn.EmmitTass stgFileName ) |> Seq.StrJoin "\n" + tasses |> List.map (icd_acn.EmitTass stgFileName ) |> Seq.StrJoin "\n" let PrintModule stgFileName (m:Asn1Module) (f:Asn1File) (r:AstRoot) = @@ -576,16 +576,16 @@ let PrintModule stgFileName (m:Asn1Module) (f:Asn1File) (r:AstRoot) = //let sortedTas = m.TypeAssignments //spark_spec.SortTypeAssignments m r acn |> List.rev let icdTasses = GenerateUperIcd.getModuleIcdTasses m - let tases = icdTasses |> Seq.map (fun x -> PrintTas stgFileName x m r ) + let tases = icdTasses |> Seq.map (fun x -> PrintTas stgFileName x m r ) let comments = m.Comments |> Array.map (fun x -> x.Trim().Replace("--", "").Replace("/*", "").Replace("*/","")) let moduleName = m.Name.Value let title = if comments.Length > 0 then moduleName + " - " + comments.[0] else moduleName let commentsTail = if comments.Length > 1 then comments.[1..] else [||] - let acnFileName = + let acnFileName = match r.acnParseResults |> Seq.tryFind(fun (rp) -> rp.tokens |> Seq.exists (fun (token:IToken) -> token.Text = moduleName)) with | Some (rp) -> (Some (Path.GetFileName(rp.fileName))) | None -> None - + icd_acn.EmitModule stgFileName title (Path.GetFileName(f.FileName)) acnFileName commentsTail tases @@ -596,38 +596,38 @@ let emitCss (r:AstRoot) stgFileName outFileName = let cssContent = icd_acn.RootCss stgFileName () File.WriteAllText(outFileName, cssContent.Replace("\r", "")) -let selectTypeWithSameHash (lst:IcdTypeAss list) = +let selectTypeWithSameHash (lst:IcdTypeAss list) = match lst with | x1::[] -> x1 - | _ -> + | _ -> lst |> List.minBy( - fun z -> - let (ReferenceToType nodes) = z.linkId; + fun z -> + let (ReferenceToType nodes) = z.linkId; nodes.Length) - + let emitTypeCol stgFileName (r:AstRoot) (sType : IcdTypeCol) = match sType with | IcdPlainType label -> label | TypeHash hash -> let label = (selectTypeWithSameHash (r.icdHashes[hash])).name - icd_acn.EmmitSeqChild_RefType stgFileName label hash - + icd_acn.EmitSeqChild_RefType stgFileName label hash + let emitIcdRow stgFileName (r:AstRoot) _i (rw:IcdRow) = let i = match rw.idxOffset with Some z -> z | None -> 1 - let sComment = rw.comments |> Seq.StrJoin (icd_uper.NewLine stgFileName ()) + let sComment = rw.comments |> Seq.StrJoin (icd_uper.NewLine stgFileName ()) let sConstraint = match rw.sConstraint with None -> "N.A." | Some x -> x let sClass = if i % 2 = 0 then (icd_acn.EvenRow stgFileName ()) else (icd_acn.OddRow stgFileName ()) match rw.rowType with - |ThreeDOTs -> icd_acn.EmitRowWith3Dots stgFileName () - | _ -> icd_acn.EmmitSeqOrChoiceRow stgFileName sClass (BigInteger i) rw.fieldName sComment rw.sPresent (emitTypeCol stgFileName r rw.sType) sConstraint (rw.minLengtInBits.ToString()) (rw.maxLengtInBits.ToString()) None rw.sUnits + |ThreeDOTs -> icd_acn.EmitRowWith3Dots stgFileName () + | _ -> icd_acn.EmitSeqOrChoiceRow stgFileName sClass (BigInteger i) rw.fieldName sComment rw.sPresent (emitTypeCol stgFileName r rw.sType) sConstraint (rw.minLengthInBits.ToString()) (rw.maxLengthInBits.ToString()) None rw.sUnits let emitTas2 stgFileName (r:AstRoot) myParams (icdTas:IcdTypeAss) = let sCommentLine = icdTas.hash::icdTas.comments |> Seq.StrJoin (icd_uper.NewLine stgFileName ()) - let arRows = + let arRows = icdTas.rows |> List.mapi (fun i rw -> emitIcdRow stgFileName r (i+1) rw) - icd_acn.EmitSequenceOrChoice stgFileName false icdTas.name icdTas.hash false (icdTas.kind) (icdTas.minLengtInBytes.ToString()) (icdTas.maxLengtInBytes.ToString()) "sMaxBitsExplained" sCommentLine arRows (myParams 4I) (sCommentLine.Split [|'\n'|]) + icd_acn.EmitSequenceOrChoice stgFileName false icdTas.name icdTas.hash false (icdTas.kind) (icdTas.minLengthInBytes.ToString()) (icdTas.maxLengthInBytes.ToString()) "sMaxBitsExplained" sCommentLine arRows (myParams 4I) (sCommentLine.Split [|'\n'|]) (* let rec PrintType2 stgFileName (r:AstRoot) acnParams (icdTas:IcdTypeAss): string list = @@ -644,15 +644,15 @@ let rec PrintType2 stgFileName (r:AstRoot) acnParams (icdTas:IcdTypeAss): strin | None -> () } |> Seq.toList let printTas2 stgFileName (r:AstRoot) (ts:TypeAssignment) : string list = - let myParams colSpan= + let myParams colSpan= ts.Type.acnParameters |> - List.mapi(fun i x -> - let sType = + List.mapi(fun i x -> + let sType = match x.asn1Type with | AcnGenericTypes.AcnParamType.AcnPrmInteger _ -> "INTEGER" | AcnGenericTypes.AcnParamType.AcnPrmBoolean _ -> "BOOLEAN" | AcnGenericTypes.AcnParamType.AcnPrmNullType _ -> "NULL" - | AcnGenericTypes.AcnParamType.AcnPrmRefType(_,ts) -> icd_acn.EmmitSeqChild_RefType stgFileName ts.Value (ToC ts.Value) + | AcnGenericTypes.AcnParamType.AcnPrmRefType(_,ts) -> icd_acn.EmitSeqChild_RefType stgFileName ts.Value (ToC ts.Value) icd_acn.PrintParam stgFileName (i+1).AsBigInt x.name sType colSpan) PrintType2 stgFileName r myParams ts.Type.icdFunction.typeAss @@ -674,7 +674,7 @@ let rec getMySelfAndChildren (r:AstRoot) (icdTas:IcdTypeAss) = let PrintTasses2 stgFileName (r:AstRoot) : string list = let pdus = r.args.icdPdus |> Option.map Set.ofList - r.icdHashes.Values |> + r.icdHashes.Values |> Seq.collect id |> Seq.choose(fun z -> match z.tasInfo with @@ -692,11 +692,11 @@ let PrintTasses2 stgFileName (r:AstRoot) : string list = -let PrintAsn1FileInColorizedHtml (stgFileName:string) (r:AstRoot) (f:Asn1File) = +let PrintAsn1FileInColorizedHtml (stgFileName:string) (r:AstRoot) (f:Asn1File) = //let tryCreateRefType = CreateAsn1AstFromAntlrTree.CreateRefTypeContent let fileModules = f.Modules |> List.map(fun m -> m.Name.Value) |> Set.ofList - let fileTypeAssignments = - r.icdHashes.Values |> + let fileTypeAssignments = + r.icdHashes.Values |> Seq.collect id |> Seq.choose(fun z -> match z.tasInfo with @@ -704,15 +704,15 @@ let PrintAsn1FileInColorizedHtml (stgFileName:string) (r:AstRoot) (f:Asn1File) = | Some ts when fileModules.Contains ts.modName -> Some (ts.tasName, z.hash) | Some _ -> None ) |> Map.ofSeq - + //let blueTasses = f.Modules |> Seq.collect(fun m -> getModuleBlueTasses m) - let blueTassesWithLoc = - f.TypeAssignments |> - Seq.map(fun x -> x.Type) |> + let blueTassesWithLoc = + f.TypeAssignments |> + Seq.map(fun x -> x.Type) |> Seq.collect(fun x -> GetMySelfAndChildren x) |> Seq.choose(fun x -> match x.Kind with - |ReferenceType ref -> + |ReferenceType ref -> match f.TypeAssignments |> Seq.tryFind(fun y -> y.Name.Value = ref.baseInfo.tasName.Value) with | Some tas -> Some(ref.baseInfo.tasName.Value, tas.Type.Location.srcLine, tas.Type.Location.charPos) | None -> None @@ -745,10 +745,10 @@ let PrintAsn1FileInColorizedHtml (stgFileName:string) (r:AstRoot) (f:Asn1File) = |None -> if idx = 0 then t else f.Tokens.[idx-1] let uid = match fileTypeAssignments.TryFind t.Text with - |Some tasHash -> - if nextToken.Type = asn1Lexer.ASSIG_OP && prevToken.Type <> asn1Lexer.LID then + |Some tasHash -> + if nextToken.Type = asn1Lexer.ASSIG_OP && prevToken.Type <> asn1Lexer.LID then icd_uper.TasName stgFileName safeText tasHash - else + else icd_uper.TasName2 stgFileName safeText tasHash |None -> safeText let colored = @@ -764,23 +764,23 @@ let PrintAsn1FileInColorizedHtml (stgFileName:string) (r:AstRoot) (f:Asn1File) = |Some (s,_,_) -> icd_uper.BlueTas stgFileName (ToC s) safeText |None -> if isAsn1Token then icd_uper.Asn1Token stgFileName safeText else colored let asn1Content = f.Tokens |> Seq.mapi(fun i token -> colorize(token,i,blueTassesWithLoc)) - icd_uper.EmmitFilePart2 stgFileName (Path.GetFileName f.FileName ) (asn1Content |> Seq.StrJoin "") + icd_uper.EmitFilePart2 stgFileName (Path.GetFileName f.FileName ) (asn1Content |> Seq.StrJoin "") let DoWork (r:AstRoot) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (stgFileName:string) (asn1HtmlStgFileMacros:string option) outFileName = - let files1 = r.Files |> Seq.map (fun f -> PrintTasses stgFileName f r ) + let files1 = r.Files |> Seq.map (fun f -> PrintTasses stgFileName f r ) let files1b = PrintTasses2 stgFileName r - let bAcnParamsMustBeExplained = true + let bAcnParamsMustBeExplained = true let asn1HtmlMacros = match asn1HtmlStgFileMacros with | None -> stgFileName | Some x -> x let files2 = r.Files |> Seq.map (PrintAsn1FileInColorizedHtml asn1HtmlMacros r) - let files3 = PrintAcnAsHTML2 stgFileName r + let files3 = PrintAcnAsHTML2 stgFileName r let cssFileName = Path.ChangeExtension(outFileName, ".css") let htmlContent = icd_acn.RootHtml stgFileName files1 files2 bAcnParamsMustBeExplained files3 (Path.GetFileName(cssFileName)) let htmlContentb = icd_acn.RootHtml stgFileName files1b files2 bAcnParamsMustBeExplained files3 (Path.GetFileName(cssFileName)) - + File.WriteAllText(outFileName, htmlContent.Replace("\r","")) File.WriteAllText(outFileName.Replace(".html", "_new.html"), htmlContentb.Replace("\r","")) let cssFileName = Path.ChangeExtension(outFileName, ".css"); diff --git a/BackendAst/GenerateFiles.fs b/BackendAst/GenerateFiles.fs index d66111c9f..1300d77a0 100644 --- a/BackendAst/GenerateFiles.fs +++ b/BackendAst/GenerateFiles.fs @@ -56,15 +56,15 @@ let rec collectEqualFuncs (t:Asn1Type) = | ObjectIdentifier _ | TimeType _ | Enumerated _ -> () - | SequenceOf ch -> + | SequenceOf ch -> yield! collectEqualFuncs ch.childType | Sequence sq -> - for ch in sq.children do + for ch in sq.children do match ch with | Asn1Child ch -> yield! collectEqualFuncs ch.Type | AcnChild _ -> () | Choice ch -> - for c in ch.children do + for c in ch.children do yield! collectEqualFuncs c.chType | ReferenceType _ -> () yield t.equalFunction @@ -79,31 +79,31 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy | Sequence o -> o.Cons.IsEmpty | Choice o -> o.Cons.IsEmpty | _ -> false - - - let vases = pu.valueAssignments + + + let vases = pu.valueAssignments let arrsAnonymousValues = pu.sortedTypeAssignments |> List.choose(fun z -> z.Type.isValidFunction) |> List.collect (fun z -> z.anonymousVariables) |> Seq.distinctBy(fun z -> z.valueName) |> Seq.toList - + let requiresUPER = encodings |> Seq.exists ( (=) Asn1Encoding.UPER) let requiresAcn = encodings |> Seq.exists ( (=) Asn1Encoding.ACN) //let requiresXER = encodings |> Seq.exists ( (=) Asn1Encoding.XER) //header file //let typeDefs = tases |> List.choose(fun t -> t.getTypeDefinition l) - let typeDefs = - tases |> - List.map(fun tas -> - let type_defintion = //tas.Type.typeDefinition.completeDefinition - match tas.Type.typeDefintionOrReference with - | TypeDefinition td -> td.typedefBody () - | ReferenceToExistingDefinition _ -> raise(BugErrorException "Type Assignment with no Type Defintion") - let init_def = - match lm.lg.initMetod with + let typeDefs = + tases |> + List.map(fun tas -> + let type_definition = //tas.Type.typeDefinition.completeDefinition + match tas.Type.typeDefinitionOrReference with + | TypeDefinition td -> td.typedefBody () + | ReferenceToExistingDefinition _ -> raise(BugErrorException "Type Assignment with no Type Definition") + let init_def = + match lm.lg.initMethod with | Procedure -> //Some (GetMySelfAndChildren tas.Type |> List.choose(fun t -> t.initFunction.initProcedure) |> List.map(fun c -> c.def) |> Seq.StrJoin "\n") Some(getInitializationFunctions tas.Type.initFunction |> List.choose( fun i_f -> i_f.initProcedure) |> List.map(fun c -> c.def) |> Seq.StrJoin "\n" ) @@ -111,8 +111,8 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy Some(getInitializationFunctions tas.Type.initFunction |> List.choose( fun i_f -> i_f.initFunction) |> List.map(fun c -> c.def) |> Seq.StrJoin "\n" ) //Some (GetMySelfAndChildren tas.Type |> List.choose(fun t -> t.initFunction.initFunction ) |> List.map(fun c -> c.def) |> Seq.StrJoin "\n") let init_globals = - //we generate const globals only if requested by user and the init method is procedure - match r.args.generateConstInitGlobals && (lm.lg.initMetod = Procedure) with + //we generate const globals only if requested by user and the init method is procedure + match r.args.generateConstInitGlobals && (lm.lg.initMethod = Procedure) with | false -> None | true -> Some (GetMySelfAndChildren tas.Type |> List.choose(fun t -> t.initFunction.initGlobal ) |> List.map(fun c -> c.def) |> Seq.StrJoin "\n") @@ -122,16 +122,16 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy let equal_defs = //collectEqualFuncs tas.Type |> List.choose(fun ef -> ef.isEqualFuncDef) match r.args.GenerateEqualFunctions with - | true -> GetMySelfAndChildren tas.Type |> List.choose(fun t -> t.equalFunction.isEqualFuncDef ) + | true -> GetMySelfAndChildren tas.Type |> List.choose(fun t -> t.equalFunction.isEqualFuncDef ) | false -> [] - let isValidFuncs = + let isValidFuncs = //match tas.Type.isValidFunction with //| None -> [] - //| Some f -> + //| Some f -> //GetMySelfAndChildren3 printChildrenIsValidFuncs tas.Type |> List.choose(fun f -> f.isValidFunction ) |> List.choose(fun f -> f.funcDef) match tas.Type.isValidFunction with | None -> [] - | Some f -> + | Some f -> getValidFunctions f |> List.choose(fun f -> f.funcDef) @@ -141,49 +141,49 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy let xerEncFunc = match tas.Type.xerEncFunction with XerFunction z -> z.funcDef | XerFunctionDummy -> None let xerDecFunc = match tas.Type.xerDecFunction with XerFunction z -> z.funcDef | XerFunctionDummy -> None - let acnEncFunc = - match requiresAcn, tas.Type.acnEncFunction with + let acnEncFunc = + match requiresAcn, tas.Type.acnEncFunction with | true, Some x -> x.funcDef | _ -> None - let acnDecFunc = - match requiresAcn, tas.Type.acnDecFunction with + let acnDecFunc = + match requiresAcn, tas.Type.acnDecFunction with | true, Some x -> x.funcDef - | _ -> None + | _ -> None let allProcs = equal_defs@isValidFuncs@special_init_funcs@([init_globals;init_def;uPerEncFunc;uPerDecFunc;acnEncFunc; acnDecFunc;xerEncFunc;xerDecFunc] |> List.choose id) - lm.typeDef.Define_TAS type_defintion allProcs + lm.typeDef.Define_TAS type_definition allProcs ) - let arrsValues = + let arrsValues = vases |> List.map(fun gv -> printHeaderFileValueAssignment r pu.name lm gv) let arrsHeaderAnonymousValues = arrsAnonymousValues |> List.map(fun av -> lm.typeDef.PrintValueAssignment av.valueName av.typeDefinitionName "") - + let arrsPrototypes = [] //sFileNameWithNoExtUpperCase, sPackageName, arrsIncludedModules, arrsTypeAssignments, arrsValueAssignments, arrsPrototypes, arrsUtilityDefines, bHasEncodings, bXer let sFileNameWithNoExtUpperCase = (ToC (System.IO.Path.GetFileNameWithoutExtension pu.specFileName)) - let bXer = r.args.encodings |> Seq.exists ((=) XER) + let bXer = r.args.encodings |> Seq.exists ((=) XER) let arrsUtilityDefines = [] let puCorrName = match r.lang with | CommonTypes.ProgrammingLanguage.Scala -> ToC (pu.name) | _ -> pu.name - let defintionsContntent = + let definitionsContntent = lm.typeDef.PrintSpecificationFile sFileNameWithNoExtUpperCase puCorrName pu.importedProgramUnits typeDefs (arrsValues@arrsHeaderAnonymousValues) arrsPrototypes arrsUtilityDefines (not r.args.encodings.IsEmpty) bXer - + let fileName = Path.Combine(outDir, pu.specFileName) - File.WriteAllText(fileName, defintionsContntent.Replace("\r","")) + File.WriteAllText(fileName, definitionsContntent.Replace("\r","")) // test cases header file match r.args.generateAutomaticTestCases with | false -> () - | true -> - let typeDefs = + | true -> + let typeDefs = seq { for tas in tases do if r.args.encodings |> Seq.exists ((=) CommonTypes.UPER) then @@ -196,12 +196,12 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy let testcase_specFileName = Path.Combine(outDir, pu.testcase_specFileName) let tstCasesHdrContent = lm.atc.PrintAutomaticTestCasesSpecFile (ToC pu.testcase_specFileName) pu.name (pu.name::pu.importedProgramUnits) typeDefs File.WriteAllText(testcase_specFileName, tstCasesHdrContent.Replace("\r","")) - + //sourse file - let arrsTypeAssignments = - tases |> List.map(fun t -> - let initialize = - match lm.lg.initMetod with + let arrsTypeAssignments = + tases |> List.map(fun t -> + let initialize = + match lm.lg.initMethod with | InitMethod.Procedure -> //Some(GetMySelfAndChildren t.Type |> List.choose(fun y -> y.initFunction.initProcedure) |> List.map(fun c -> c.body) |> Seq.StrJoin "\n") Some(getInitializationFunctions t.Type.initFunction |> List.choose( fun i_f -> i_f.initProcedure) |> List.map(fun c -> c.body) |> Seq.StrJoin "\n" ) @@ -210,7 +210,7 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy Some(getInitializationFunctions t.Type.initFunction |> List.choose( fun i_f -> i_f.initFunction) |> List.map(fun c -> c.body) |> Seq.StrJoin "\n" ) let init_globals = - match r.args.generateConstInitGlobals && (lm.lg.initMetod = Procedure) with + match r.args.generateConstInitGlobals && (lm.lg.initMethod = Procedure) with | false -> None | true -> Some (GetMySelfAndChildren t.Type |> List.choose(fun t -> t.initFunction.initGlobal) |> List.map(fun c -> c.body) |> Seq.StrJoin "\n") @@ -228,10 +228,10 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy //GetMySelfAndChildren3 printChildrenIsValidFuncs t.Type |> List.choose(fun f -> f.isValidFunction ) |> List.choose(fun f -> f.func) match t.Type.isValidFunction with | None -> [] - | Some f -> + | Some f -> getValidFunctions f |> List.choose(fun f -> f.func) - let uperEncDec codec = + let uperEncDec codec = match requiresUPER with | true -> match codec with @@ -239,18 +239,18 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy | CommonTypes.Decode -> t.Type.uperDecFunction.func | false -> None - let xerEncDec codec = + let xerEncDec codec = match codec with - | CommonTypes.Encode -> + | CommonTypes.Encode -> match t.Type.xerEncFunction with | XerFunction z -> z.func | XerFunctionDummy -> None - | CommonTypes.Decode -> + | CommonTypes.Decode -> match t.Type.xerDecFunction with | XerFunction z -> z.func | XerFunctionDummy -> None - let ancEncDec codec = + let ancEncDec codec = match requiresAcn with | true -> match codec with @@ -261,23 +261,23 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy lm.src.printTass allProcs ) - let arrsValueAssignments, arrsSourceAnonymousValues = + let arrsValueAssignments, arrsSourceAnonymousValues = match lm.lg.requiresValueAssignmentsInSrcFile with - | true -> + | true -> let arrsValueAssignments = vases |> List.map (printSourceFileValueAssignment r pu.name lm) - let arrsSourceAnonymousValues = arrsAnonymousValues |> List.map (fun av -> lm.vars.PrintValueAssignment av.typeDefinitionName av.valueName av.valueExpresion) + let arrsSourceAnonymousValues = arrsAnonymousValues |> List.map (fun av -> lm.vars.PrintValueAssignment av.typeDefinitionName av.valueName av.valueExpression) arrsValueAssignments, arrsSourceAnonymousValues | false -> [], [] let rtlFiles = lm.lg.getRtlFiles r.args.encodings arrsTypeAssignments let arrsImportedFiles = rtlFiles@pu.importedUserModules@pu.importedProgramUnits |> List.distinct - let puCorrName = + let puCorrName = match r.lang with | CommonTypes.ProgrammingLanguage.Scala -> ToC (pu.name) | _ -> pu.name let srcBody = lm.src.printSourceFile puCorrName arrsImportedFiles pu.importedTypes (arrsValueAssignments@arrsSourceAnonymousValues@arrsTypeAssignments) - - let eqContntent = + + let eqContntent = match lm.lg.allowsSrcFilesWithNoFunctions with | true -> Some srcBody @@ -295,11 +295,11 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy //test cases sourse file match r.args.generateAutomaticTestCases with | false -> () - | true -> - let encDecFuncs = + | true -> + let encDecFuncs = seq { for tas in tases do - + if r.args.encodings |> Seq.exists ((=) CommonTypes.UPER) then yield (tas.Type.uperEncDecTestFunc |> Option.map (fun z -> z.func)) if r.args.encodings |> Seq.exists ((=) CommonTypes.XER) then @@ -313,14 +313,14 @@ let private printUnit (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: CommonTy let tstCasesHdrContent = match lm.lg.allowsSrcFilesWithNoFunctions with | true -> Some (lm.atc.PrintAutomaticTestCasesBodyFile pu.name pu.testcase_specFileName pu.importedProgramUnits [] encDecFuncs bXer) - | false -> + | false -> match encDecFuncs with | [] -> None | _ -> Some (lm.atc.PrintAutomaticTestCasesBodyFile pu.name pu.testcase_specFileName pu.importedProgramUnits [] encDecFuncs bXer) - + tstCasesHdrContent |> Option.iter(fun tstCasesHdrContent -> File.WriteAllText(testcase_SrcFileName, tstCasesHdrContent.Replace("\r",""))) - (defintionsContntent, srcBody) + (definitionsContntent, srcBody) @@ -328,14 +328,14 @@ let generateAll (di:DirInfo) (r:DAst.AstRoot) (lm:LanguageMacros) (encodings: C let generatedContent = r.programUnits |> List.map(printUnit r lm encodings di.srcDir) |> List.map snd |> Seq.StrJoin "\n" match r.args.generateAutomaticTestCases with | false -> () - | true -> + | true -> lm.lg.CreateMakeFile r di let arrsSrcTstFiles, arrsHdrTstFiles = DastTestCaseCreation.printAllTestCasesAndTestCaseRunner r lm di.srcDir lm.lg.CreateAuxFiles r di (arrsSrcTstFiles, arrsHdrTstFiles) generatedContent -let EmmitDefaultACNGrammar (r:AstRoot) outDir = +let EmitDefaultACNGrammar (r:AstRoot) outDir = let printTas (tas: TypeAssignment) = tas.Name.Value + "[]" let printModule (m:Asn1Module) = diff --git a/BackendAst/GenerateUperIcd.fs b/BackendAst/GenerateUperIcd.fs index 343118336..5c9de63cf 100644 --- a/BackendAst/GenerateUperIcd.fs +++ b/BackendAst/GenerateUperIcd.fs @@ -12,18 +12,18 @@ open DAstUtilFunctions open Antlr.Asn1 open Antlr.Runtime -let rec GetMySelfAndChildren (t:Asn1Type) = +let rec GetMySelfAndChildren (t:Asn1Type) = seq { yield t match t.Kind with | SequenceOf o -> yield! GetMySelfAndChildren o.childType | Sequence o -> - for ch in o.Asn1Children do + for ch in o.Asn1Children do yield! GetMySelfAndChildren ch.Type - | Choice o-> - for ch in o.children do + | Choice o-> + for ch in o.children do yield! GetMySelfAndChildren ch.chType - |_ -> () + |_ -> () } let rec getUnits (t:Asn1Type) = @@ -38,7 +38,7 @@ let foldRangeCon = DastValidate2.printRangeConAsAsn1 let Kind2Name (stgFileName:string) (t:Asn1Type) = match t.Kind with - | ReferenceType r -> + | ReferenceType r -> match r.baseInfo.encodingOptions with | None -> r.baseInfo.tasName.Value | Some eo -> @@ -53,7 +53,7 @@ let Kind2Name (stgFileName:string) (t:Asn1Type) = | Enumerated _ -> icd_uper.Enumerated stgFileName () | ObjectIdentifier a when a.baseInfo.relativeObjectId -> icd_uper.RelativeOid stgFileName () | ObjectIdentifier _ -> icd_uper.ObjectIdentifier stgFileName () - | IA5String s -> + | IA5String s -> match s.baseInfo.isNumeric with | true -> icd_uper.NumericString stgFileName () | false -> icd_uper.IA5String stgFileName () @@ -61,11 +61,12 @@ let Kind2Name (stgFileName:string) (t:Asn1Type) = | Real _ -> icd_uper.Real stgFileName () | Sequence _ -> icd_uper.Sequence stgFileName () | SequenceOf _ -> icd_uper.SequenceOf stgFileName () + | other -> raise (BugErrorException $"Unsupported kind for Kind2Name: {other}") let getTypeName (stgFileName:string) (t:Asn1Type) = - icd_acn.EmmitSeqChild_RefType stgFileName t.FT_TypeDefintion.[CommonTypes.C].asn1Name (ToC t.FT_TypeDefintion.[CommonTypes.C].asn1Name) + icd_acn.EmitSeqChild_RefType stgFileName t.FT_TypeDefinition.[CommonTypes.C].asn1Name (ToC t.FT_TypeDefinition.[CommonTypes.C].asn1Name) //match t.Kind with - //| ReferenceType ref -> icd_uper.EmmitSeqChild_RefType stgFileName ref.baseInfo.tasName.Value (ToC ref.baseInfo.tasName.Value) + //| ReferenceType ref -> icd_uper.EmitSeqChild_RefType stgFileName ref.baseInfo.tasName.Value (ToC ref.baseInfo.tasName.Value) //| _ -> Kind2Name stgFileName t @@ -88,8 +89,8 @@ type StgCommentLineMacros = { let GetCommentLineFactory (stgFileName:string) (stgs:StgCommentLineMacros) = let GetCommentLine (comments:string seq) (t:Asn1Type) = - let singleComment = comments |> Seq.StrJoin (stgs.NewLine stgFileName ()) - let ret = + let singleComment = comments |> Seq.StrJoin (stgs.NewLine stgFileName ()) + let ret = match (t.ActualType).Kind with | Enumerated enum -> let EmitItem (n:Asn1AcnAst.NamedItem) = @@ -97,12 +98,12 @@ let GetCommentLineFactory (stgFileName:string) (stgs:StgCommentLineMacros) = match comment.Trim() with | "" -> stgs.EmitEnumItem stgFileName n.Name.Value n.definitionValue | _ -> stgs.EmitEnumItemWithComment stgFileName n.Name.Value n.definitionValue comment - let itemsHtml = - enum.baseInfo.items |> - List.filter(fun z -> + let itemsHtml = + enum.baseInfo.items |> + List.filter(fun z -> let v = z.Name.Value Asn1Fold.isValidValueGeneric enum.AllCons (=) v ) |> - List.map EmitItem + List.map EmitItem let extraComment = stgs.EmitEnumInternalContents stgFileName (itemsHtml :> string seq) match singleComment.Trim() with | "" -> extraComment @@ -121,9 +122,9 @@ type IcdTypeAssignment = { let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t:Asn1Type) (r:AstRoot) color = let enumStg = { - NewLine = icd_uper.NewLine - EmitEnumItem = icd_uper.EmitEnumItem - EmitEnumItemWithComment = icd_uper.EmitEnumItemWithComment + NewLine = icd_uper.NewLine + EmitEnumItem = icd_uper.EmitEnumItem + EmitEnumItemWithComment = icd_uper.EmitEnumItemWithComment EmitEnumInternalContents = icd_uper.EmitEnumInternalContents } let GetCommentLine = GetCommentLineFactory stgFileName enumStg @@ -160,7 +161,7 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t handlePrimitive sAsn1Constraints |ReferenceType o when o.baseInfo.encodingOptions.IsNone -> printType stgFileName m tas o.resolvedType r color - |Sequence seq -> + |Sequence seq -> let EmitChild (i:int) (ch:Asn1Child) = let sClass = if i % 2 = 0 then (icd_uper.EvenRow stgFileName ()) else (icd_uper.OddRow stgFileName ()) let nIndex = BigInteger i @@ -175,28 +176,28 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t //+++ //let ret = ch.Type.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" //( if ret.Trim() ="" then "N.A." else ret) - + let sMinBits, sMinBytes, sMaxBits, sMaxBytes = getMinMaxBitsAndBytes ch.Type.uperMinSizeInBits ch.Type.uperMaxSizeInBits let sMaxBitsExplained = GetWhyExplanation stgFileName ch.Type r let soUnit = getUnits ch.Type - icd_uper.EmmitSequenceChild stgFileName sClass nIndex ch.Name.Value sComment sOptionality sType sAsn1Constraints sMinBits (sMaxBits+sMaxBitsExplained) soUnit + icd_uper.EmitSequenceChild stgFileName sClass nIndex ch.Name.Value sComment sOptionality sType sAsn1Constraints sMinBits (sMaxBits+sMaxBitsExplained) soUnit let SeqPreamble = - let optChild = seq.Asn1Children |> Seq.filter (fun x -> x.Optionality.IsSome) |> Seq.mapi(fun i c -> icd_uper.EmmitSequencePreambleSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) + let optChild = seq.Asn1Children |> Seq.filter (fun x -> x.Optionality.IsSome) |> Seq.mapi(fun i c -> icd_uper.EmitSequencePreambleSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) let nLen = optChild |> Seq.length if nLen > 0 then - let sComment = icd_uper.EmmitSequencePreambleComment stgFileName optChild - let ret = icd_uper.EmmitSequenceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "Preamble" sComment "No" "Bit mask" "N.A." (nLen.ToString()) (nLen.ToString()) None + let sComment = icd_uper.EmitSequencePreambleComment stgFileName optChild + let ret = icd_uper.EmitSequenceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "Preamble" sComment "No" "Bit mask" "N.A." (nLen.ToString()) (nLen.ToString()) None Some ret else None let sTasName = tas.name let sMaxBitsExplained = "" let sCommentLine = GetCommentLine tas.comments t - + let arChildren idx = seq.Asn1Children |> Seq.mapi(fun i ch -> EmitChild (idx + i) ch) |> Seq.toList let arRows = - match SeqPreamble with + match SeqPreamble with | None -> arChildren 1 | Some(prm) -> prm::(arChildren 2) @@ -214,12 +215,12 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t let sMinBits, sMinBytes, sMaxBits, sMaxBytes = getMinMaxBitsAndBytes ch.chType.uperMinSizeInBits ch.chType.uperMaxSizeInBits let sMaxBitsExplained = GetWhyExplanation stgFileName ch.chType r let soUnit = getUnits ch.chType - icd_uper.EmmitChoiceChild stgFileName sClass nIndex ch.Name.Value sComment sType sAsn1Constraints sMinBits (sMaxBits+sMaxBitsExplained) soUnit + icd_uper.EmitChoiceChild stgFileName sClass nIndex ch.Name.Value sComment sType sAsn1Constraints sMinBits (sMaxBits+sMaxBitsExplained) soUnit let ChIndex = - let optChild = chInfo.children |> Seq.mapi(fun i c -> icd_uper.EmmitChoiceIndexSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) - let sComment = icd_uper.EmmitChoiceIndexComment stgFileName optChild + let optChild = chInfo.children |> Seq.mapi(fun i c -> icd_uper.EmitChoiceIndexSingleComment stgFileName (BigInteger (i+1)) c.Name.Value) + let sComment = icd_uper.EmitChoiceIndexComment stgFileName optChild let indexSize = (GetChoiceUperDeterminantLengthInBits(BigInteger(Seq.length chInfo.children))).ToString() - icd_uper.EmmitChoiceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "ChoiceIndex" sComment "unsigned int" "N.A." indexSize indexSize None + icd_uper.EmitChoiceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "ChoiceIndex" sComment "unsigned int" "N.A." indexSize indexSize None let sTasName = tas.name let sMaxBitsExplained = "" let sCommentLine = GetCommentLine tas.comments t @@ -234,11 +235,11 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t let getCharSize charSetLength = let charSize = GetNumberOfBitsForNonNegativeInteger (BigInteger (charSetLength-1)) charSize.ToString() - let sType, sAsn1Constraints, sMinChildBits, sMaxChildBits, nMinLength, nMaxLength = + let sType, sAsn1Constraints, sMinChildBits, sMaxChildBits, nMinLength, nMaxLength = match t.Kind with | SequenceOf o -> let child = o.childType - let sAsn1Constraints = child.ConstraintsAsn1Str |> Seq.StrJoin ""//+++ child.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" + let sAsn1Constraints = child.ConstraintsAsn1Str |> Seq.StrJoin ""//+++ child.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" let ret = ( if sAsn1Constraints.Trim() ="" then "N.A." else sAsn1Constraints) let sMinBits, _, sMaxBits, _ = getMinMaxBitsAndBytes child.uperMinSizeInBits child.uperMaxSizeInBits let sMaxBitsExplained = GetWhyExplanation stgFileName child r @@ -254,7 +255,7 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t match eo.octOrBitStr with | ContainedInOctString -> "OCTET", "", "8", "8", eo.minSize, eo.maxSize | ContainedInBitString -> "BIT", "", "1","1", eo.minSize, eo.maxSize - + | _ -> raise(BugErrorException "") let sizeUperRange = CommonTypes.Concrete(nMinLength, nMaxLength) let ChildRow (lineFrom:BigInteger) (i:BigInteger) = @@ -262,10 +263,10 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t let nIndex = lineFrom + i let sFieldName = icd_uper.ItemNumber stgFileName i let sComment = "" - icd_uper.EmmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType sAsn1Constraints sMinChildBits sMaxChildBits None - + icd_uper.EmitChoiceChild stgFileName sClass nIndex sFieldName sComment sType sAsn1Constraints sMinChildBits sMaxChildBits None + let LengthRow = - let nMin, nLengthSize = + let nMin, nLengthSize = match sizeUperRange with | CommonTypes.Concrete(a,b) when a.uper=b.uper -> 0I, 0I | CommonTypes.Concrete(a,b) -> (GetNumberOfBitsForNonNegativeInteger(b.uper - a.uper)), (GetNumberOfBitsForNonNegativeInteger(b.uper - a.uper)) @@ -273,10 +274,10 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t | CommonTypes.PosInf(b) -> 8I, 16I | CommonTypes.Full -> 8I, 16I let comment = "Special field used by PER to indicate the number of items present in the array." - let ret = t.ConstraintsAsn1Str |> Seq.StrJoin "" //+++ t.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" + let ret = t.ConstraintsAsn1Str |> Seq.StrJoin "" //+++ t.Constraints |> Seq.map PrintAsn1.PrintConstraint |> Seq.StrJoin "" let sCon = ( if ret.Trim() ="" then "N.A." else ret) - icd_uper.EmmitChoiceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "Length" comment "unsigned int" sCon (nMin.ToString()) (nLengthSize.ToString()) None + icd_uper.EmitChoiceChild stgFileName (icd_uper.OddRow stgFileName ()) (BigInteger 1) "Length" comment "unsigned int" sCon (nMin.ToString()) (nLengthSize.ToString()) None let sTasName = tas.name let sMaxBitsExplained = "" @@ -284,7 +285,7 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t let sFixedLengthComment (nMax: BigInteger) = sprintf "Length is fixed to %A elements (no length determinant is needed)." nMax - let arRows, sExtraComment = + let arRows, sExtraComment = match sizeUperRange with | CommonTypes.Concrete(a,b) when a.uper=b.uper && b.uper<2I -> [ChildRow 0I 1I], "The array contains a single element." | CommonTypes.Concrete(a,b) when a.uper=b.uper && b.uper=2I -> (ChildRow 0I 1I)::(ChildRow 0I 2I)::[], (sFixedLengthComment b.uper) @@ -301,50 +302,51 @@ let rec printType (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (t icd_uper.EmitSizeable stgFileName color sTasName (ToC sTasName) (Kind2Name stgFileName t) sMinBytes sMaxBytes sMaxBitsExplained sCommentLine arRows (sCommentLine.Split [|'\n'|]) + | other -> raise (BugErrorException $"Unsupported kind for printType: {other}") let PrintTas (stgFileName:string) (m:Asn1Module) (tas:IcdTypeAssignment) (r:AstRoot) = let tasColor = match tas.isBlue with |true -> icd_uper.Blue stgFileName () |false -> icd_uper.Orange stgFileName () - icd_uper.EmmitTass stgFileName (printType stgFileName m tas tas.t r tasColor) + icd_uper.EmitTass stgFileName (printType stgFileName m tas tas.t r tasColor) let getModuleIcdTasses (m:Asn1Module) = - m.TypeAssignments |> + m.TypeAssignments |> Seq.collect(fun x -> GetMySelfAndChildren x.Type) |> //Seq.choose(fun x -> match x.Kind with ReferenceType ref -> Some (ref.baseInfo.modName.Value,ref.baseInfo.tasName.Value) |_ -> None) |> Seq.toList - Seq.choose(fun x -> + Seq.choose(fun x -> let comments = match x.tasInfo with - | Some tas -> + | Some tas -> match m.TypeAssignments |> List.tryFind(fun ts -> ts.Name.Value = tas.tasName) with | Some tas -> tas.Comments | None -> [||] | None -> [||] - let td = x.FT_TypeDefintion.[CommonTypes.C] + let td = x.FT_TypeDefinition.[CommonTypes.C] match td.BaseKind with | NewTypeDefinition -> Some {IcdTypeAssignment.name = td.asn1Name; comments=comments; t=x; isBlue = x.tasInfo.IsNone} //type | NewSubTypeDefinition -> Some {IcdTypeAssignment.name = td.asn1Name; comments=comments; t=x; isBlue = x.tasInfo.IsNone} | Reference2RTL -> None | Reference2OtherType -> None - - ) + + ) |> Seq.toList let PrintModule (stgFileName:string) (m:Asn1Module) (f:Asn1File) (r:AstRoot) = //let blueTasses = getModuleBlueTasses m |> Seq.map snd //let sortedTas = m.TypeAssignments //+++ spark_spec.SortTypeAssignments m r acn |> List.rev - //let tases = sortedTas |> Seq.map (fun x -> PrintTas stgFileName m x r blueTasses) + //let tases = sortedTas |> Seq.map (fun x -> PrintTas stgFileName m x r blueTasses) let icdTasses = getModuleIcdTasses m - let tases = icdTasses |> Seq.map (fun x -> PrintTas stgFileName m x r ) + let tases = icdTasses |> Seq.map (fun x -> PrintTas stgFileName m x r ) let comments = [] - icd_uper.EmmitModule stgFileName m.Name.Value comments tases + icd_uper.EmitModule stgFileName m.Name.Value comments tases let PrintFile1 (stgFileName:string) (f:Asn1File) (r:AstRoot) = - let modules = f.Modules |> Seq.map (fun m -> PrintModule stgFileName m f r ) - icd_uper.EmmitFile stgFileName (Path.GetFileName f.FileName) modules + let modules = f.Modules |> Seq.map (fun m -> PrintModule stgFileName m f r ) + icd_uper.EmitFile stgFileName (Path.GetFileName f.FileName) modules let asn1Tokens = [ "PLUS-INFINITY";"MINUS-INFINITY";"GeneralizedTime";"UTCTime";"mantissa";"base";"exponent";"UNION";"INTERSECTION"; "DEFINITIONS";"EXPLICIT";"TAGS";"IMPLICIT";"AUTOMATIC";"EXTENSIBILITY";"IMPLIED";"BEGIN";"END";"EXPORTS";"ALL"; @@ -354,15 +356,15 @@ let asn1Tokens = [ "PLUS-INFINITY";"MINUS-INFINITY";"GeneralizedTime";"UTCTime"; "PrintableString";"VisibleString";"IA5String";"TeletexString";"VideotexString";"GraphicString";"GeneralString"; "UniversalString";"BMPString";"UTF8String";"INCLUDES";"EXCEPT";"SET";"SEQUENCE";"CHOICE";"OF";"COMPONENTS"] |> Set.ofList -let PrintFile2 (stgFileName:string) (f:Asn1File) = +let PrintFile2 (stgFileName:string) (f:Asn1File) = let tasNames = f.Modules |> Seq.collect(fun x -> x.TypeAssignments) |> Seq.map(fun x -> x.Name.Value) |> Seq.toArray //let blueTasses = f.Modules |> Seq.collect(fun m -> getModuleBlueTasses m) - let blueTassesWithLoc = - f.TypeAssignments |> - Seq.map(fun x -> x.Type) |> + let blueTassesWithLoc = + f.TypeAssignments |> + Seq.map(fun x -> x.Type) |> Seq.collect(fun x -> GetMySelfAndChildren x) |> Seq.choose(fun x -> match x.Kind with - |ReferenceType ref -> + |ReferenceType ref -> match f.TypeAssignments |> Seq.tryFind(fun y -> y.Name.Value = ref.baseInfo.tasName.Value) with | Some tas -> Some(ref.baseInfo.tasName.Value, tas.Type.Location.srcLine, tas.Type.Location.charPos) | None -> None @@ -396,10 +398,10 @@ let PrintFile2 (stgFileName:string) (f:Asn1File) = |None -> if idx = 0 then t else f.Tokens.[idx-1] let uid = match isType with - |true -> - if nextToken.Type = asn1Lexer.ASSIG_OP && prevToken.Type <> asn1Lexer.LID then - icd_uper.TasName stgFileName safeText (ToC safeText) - else + |true -> + if nextToken.Type = asn1Lexer.ASSIG_OP && prevToken.Type <> asn1Lexer.LID then + icd_uper.TasName stgFileName safeText (ToC safeText) + else icd_uper.TasName2 stgFileName safeText (ToC safeText) |false -> safeText let colored = @@ -415,25 +417,25 @@ let PrintFile2 (stgFileName:string) (f:Asn1File) = |Some (s,_,_) -> icd_uper.BlueTas stgFileName (ToC s) safeText |None -> if isAsn1Token then icd_uper.Asn1Token stgFileName safeText else colored let asn1Content = f.Tokens |> Seq.mapi(fun i token -> colorize(token,i,tasNames,blueTassesWithLoc)) - icd_uper.EmmitFilePart2 stgFileName (Path.GetFileName f.FileName ) (asn1Content |> Seq.StrJoin "") + icd_uper.EmitFilePart2 stgFileName (Path.GetFileName f.FileName ) (asn1Content |> Seq.StrJoin "") let DoWork (r:AstRoot) (stgFileName:string) outFileName = - let files1 = r.Files |> Seq.map (fun f -> PrintFile1 stgFileName f r ) + let files1 = r.Files |> Seq.map (fun f -> PrintFile1 stgFileName f r ) let files2 = r.Files |> Seq.map (PrintFile2 stgFileName) let allTypes = r.Files |> List.collect(fun x -> x.TypeAssignments) |> List.map(fun x -> x.Type) |> Seq.collect(fun x -> GetMySelfAndChildren x ) - let bIntegerSizeMustBeExplained = allTypes |> Seq.exists(fun x -> match x.Kind with - | Integer o-> - match o.baseInfo.uperRange with - | CommonTypes.Full | CommonTypes.PosInf(_) | CommonTypes.NegInf(_) -> true - |_ ->false + let bIntegerSizeMustBeExplained = allTypes |> Seq.exists(fun x -> match x.Kind with + | Integer o-> + match o.baseInfo.uperRange with + | CommonTypes.Full | CommonTypes.PosInf(_) | CommonTypes.NegInf(_) -> true + |_ ->false | _ -> false) let bRealSizeMustBeExplained = allTypes |> Seq.exists(fun x -> match x.Kind with Real _ ->true | _ -> false) let bLengthSizeMustBeExplained = false let bWithComponentMustBeExplained = false - let bZeroBitsMustBeExplained = - allTypes |> - Seq.exists(fun x -> - match x.ActualType.Kind with + let bZeroBitsMustBeExplained = + allTypes |> + Seq.exists(fun x -> + match x.ActualType.Kind with | Integer o -> o.baseInfo.uperMinSizeInBits = 0I | _ -> false) let content = icd_uper.RootHtml stgFileName files1 files2 bIntegerSizeMustBeExplained bRealSizeMustBeExplained bLengthSizeMustBeExplained bWithComponentMustBeExplained bZeroBitsMustBeExplained diff --git a/BackendAst/GrammarGenerator.fs b/BackendAst/GrammarGenerator.fs index 5c8d2b835..bafaddc14 100644 --- a/BackendAst/GrammarGenerator.fs +++ b/BackendAst/GrammarGenerator.fs @@ -37,63 +37,63 @@ let genrateAcnIntProps (c:ParameterizedAsn1Ast.Asn1Constraint Option) = for encoding in [GP_PosInt; GP_TwosComplement; GP_Ascii; GP_BCD] do for sizeProp in [GP_Fixed (IntLoc.ByValue 64I); GP_NullTerminated ] do yield [ENCODING encoding; SIZE sizeProp] - for endianess in [AcnGenericTypes.LittleEndianness; AcnGenericTypes.BigEndianness] do - yield [ENCODING encoding; SIZE sizeProp; ENDIANNES endianess] + for endianness in [AcnGenericTypes.LittleEndianness; AcnGenericTypes.BigEndianness] do + yield [ENCODING encoding; SIZE sizeProp; ENDIANNESS endianness] for align in [AcnGenericTypes.NextByte; AcnGenericTypes.NextWord; AcnGenericTypes.NextDWord] do - yield [ENCODING encoding; SIZE sizeProp; ENDIANNES endianess; ALIGNTONEXT align] + yield [ENCODING encoding; SIZE sizeProp; ENDIANNESS endianness; ALIGNTONEXT align] } |> Seq.toList -let generatedIntConstraints (v1:BigInteger option) (v2:BigInteger option)= +let generatedIntConstraints (v1:BigInteger option) (v2:BigInteger option)= let gv v = {ParameterizedAsn1Ast.Asn1Value.Kind = ParameterizedAsn1Ast.IntegerValue (IntLoc.ByValue v); ParameterizedAsn1Ast.Asn1Value.Location = emptyLocation; ParameterizedAsn1Ast.Asn1Value.moduleName=""} let a = v1 |> Option.map gv let b = v1 |> Option.map gv - let svcs = + let svcs = seq { match a, b with | Some a, Some b -> - yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueContraint ("", a) - yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueContraint ("", b) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint("",a,b,true, true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint("",a,b,true, false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint("",a,b,false, true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint("",a,b,false, false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",a,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",a,false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",b,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",b,false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",a,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",a,false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",b,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",b,false) + yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueConstraint ("", a) + yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueConstraint ("", b) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint("",a,b,true, true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint("",a,b,true, false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint("",a,b,false, true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint("",a,b,false, false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",a,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",a,false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",b,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",b,false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",a,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",a,false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",b,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",b,false) | Some a, None -> - yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueContraint ("",a) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",a,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",a,false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",a,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",a,false) + yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueConstraint ("",a) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",a,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",a,false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",a,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",a,false) | None, Some b -> - yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueContraint ("",b) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",b,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX("",b,false) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",b,true) - yield ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val("",b,false) + yield ParameterizedAsn1Ast.Asn1Constraint.SingleValueConstraint ("",b) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",b,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX("",b,false) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",b,true) + yield ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val("",b,false) | None, None -> () } |> Seq.toList svcs -let genetateIntegers (name:string) = +let generateIntegers (name:string) = let nums = [ - BigInteger Int64.MinValue; BigInteger Int32.MinValue; BigInteger (int Int16.MinValue); BigInteger (int SByte.MinValue); 0I; + BigInteger Int64.MinValue; BigInteger Int32.MinValue; BigInteger (int Int16.MinValue); BigInteger (int SByte.MinValue); 0I; BigInteger (int SByte.MaxValue); BigInteger (int Byte.MaxValue); BigInteger (int Int16.MaxValue); BigInteger (int UInt16.MaxValue) BigInteger Int32.MaxValue; BigInteger UInt32.MaxValue; BigInteger Int64.MaxValue; BigInteger UInt64.MaxValue] let nums = [BigInteger Int64.MinValue; BigInteger Int64.MaxValue] - - let pairs = + + let pairs = seq { for a in nums do yield (Some a, None) @@ -106,18 +106,18 @@ let genetateIntegers (name:string) = for (i1,(a,b)) in (toIdxList pairs) do let cons = generatedIntConstraints a b |> List.map(fun c -> Some c) for (i2, c) in (toIdxList (None::cons)) do - let asn1Type = {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.Integer; ParameterizedAsn1Ast.Constraints = Option.toList c ; ParameterizedAsn1Ast.Location=emptyLocation; parameterizedTypeInstance = false; acnInfo = None;unitsOfMeasure = None; moduleName=""} + let asn1Type = {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.Integer; ParameterizedAsn1Ast.Constraints = Option.toList c ; ParameterizedAsn1Ast.Location=emptyLocation; parameterizedTypeInstance = false; acnInfo = None;unitsOfMeasure = None; moduleName=""} let acnSpec = genrateAcnIntProps c for (i3,s) in (toIdxList acnSpec) do let newName = sprintf "%s-%d-%d-%d" name i1 i2 i3 yield (newName, asn1Type, s) } |> Seq.toList - + let createAst files = seq { for f in files do - let intTasses = genetateIntegers "INT" |> List.map (fun (newName, asn1Type, acnProps) -> {GenTas.name = newName; Type = asn1Type; acnProps = acnProps}) + let intTasses = generateIntegers "INT" |> List.map (fun (newName, asn1Type, acnProps) -> {GenTas.name = newName; Type = asn1Type; acnProps = acnProps}) let modu = {GenMod.tases = intTasses; name = "TEST-CASE"} let file = {GenFile.name = f; mods = [modu]} yield file @@ -143,15 +143,15 @@ let rec printValue (v:Asn1Value) : string = let generatedAsn1Grammar (outDir:string) (ast:GenFile list) = - let rec printConstraint (c:Asn1Constraint) : string = + let rec printConstraint (c:Asn1Constraint) : string = match c with - | SingleValueContraint (_,v) -> stg_asn1.Print_SingleValueContraint (printValue v) - | RangeContraint (_, a,b,b1,b2) -> stg_asn1.Print_RangeContraint (printValue a) (printValue b) b1 b2 - | RangeContraint_val_MAX (_, a, b1) -> stg_asn1.Print_RangeContraint_val_MAX (printValue a) b1 - | RangeContraint_MIN_val (_, a, b1) -> stg_asn1.Print_RangeContraint_MIN_val (printValue a) b1 + | SingleValueConstraint (_,v) -> stg_asn1.Print_SingleValueConstraint (printValue v) + | RangeConstraint (_, a,b,b1,b2) -> stg_asn1.Print_RangeConstraint (printValue a) (printValue b) b1 b2 + | RangeConstraint_val_MAX (_, a, b1) -> stg_asn1.Print_RangeConstraint_val_MAX (printValue a) b1 + | RangeConstraint_MIN_val (_, a, b1) -> stg_asn1.Print_RangeConstraint_MIN_val (printValue a) b1 | TypeInclusionConstraint (_, md,ts) -> stg_asn1.Print_TypeInclusionConstraint(ts.Value) - | SizeContraint (_, sc) -> stg_asn1.Print_SizeContraint (printConstraint sc) - | AlphabetContraint (_, alpha) -> stg_asn1.Print_AlphabetContraint (printConstraint alpha) + | SizeConstraint (_, sc) -> stg_asn1.Print_SizeConstraint (printConstraint sc) + | AlphabetConstraint (_, alpha) -> stg_asn1.Print_AlphabetConstraint (printConstraint alpha) | UnionConstraint (_, c1,c2, _) -> stg_asn1.Print_UnionConstraint (printConstraint c1) (printConstraint c2) | IntersectionConstraint (_, c1,c2) -> stg_asn1.Print_IntersectionConstraint (printConstraint c1) (printConstraint c2) | AllExceptConstraint (_, c1) -> stg_asn1.Print_AllExceptConstraint (printConstraint c1) @@ -159,12 +159,12 @@ let generatedAsn1Grammar (outDir:string) (ast:GenFile list) = | RootConstraint (_, c1) -> stg_asn1.Print_RootConstraint (printConstraint c1) | RootConstraint2 (_, c1,c2) -> stg_asn1.Print_RootConstraint2 (printConstraint c1) (printConstraint c2) | WithComponentConstraint (_, c1,l) -> stg_asn1.Print_WithComponentConstraint (printConstraint c1) - | WithComponentsConstraint (_, ncs) -> + | WithComponentsConstraint (_, ncs) -> let print nc = - stg_asn1.Print_WithComponentsConstraint_child nc.Name.Value (match nc.Contraint with Some c -> printConstraint c | None -> "") (sprintf "%A" nc.Mark) + stg_asn1.Print_WithComponentsConstraint_child nc.Name.Value (match nc.Constraint with Some c -> printConstraint c | None -> "") (sprintf "%A" nc.Mark) stg_asn1.Print_WithComponentsConstraint (ncs |> List.map print) - let printAsn1Type (t:Asn1Type) : string = + let printAsn1Type (t:Asn1Type) : string = match t.Kind with | Integer -> stg_asn1.Print_Integer "" (t.Constraints |> List.map printConstraint) | _ -> raise(BugErrorException "Not Implemented yet") @@ -189,11 +189,11 @@ let generatedAcnGrammar (outDir:string) (ast:GenFile list) = | SIZE (GP_Fixed i) -> stg_acn.PP_Size_Fixed (i.Value) | SIZE (GP_SizeDeterminant fld) -> stg_acn.PP_Sixe_Fld (fld.AsString) | SIZE GP_NullTerminated -> stg_acn.PP_Size_NullTerminated () - | ALIGNTONEXT AcnGenericTypes.NextByte -> stg_acn.PP_Aligment_byte () - | ALIGNTONEXT AcnGenericTypes.NextWord -> stg_acn.PP_Aligment_word () - | ALIGNTONEXT AcnGenericTypes.NextDWord -> stg_acn.PP_Aligment_dword () - | ENDIANNES AcnGenericTypes.LittleEndianness -> stg_acn.PP_Endianness_little () - | ENDIANNES AcnGenericTypes.BigEndianness -> stg_acn.PP_Endianness_big () + | ALIGNTONEXT AcnGenericTypes.NextByte -> stg_acn.PP_Alignment_byte () + | ALIGNTONEXT AcnGenericTypes.NextWord -> stg_acn.PP_Alignment_word () + | ALIGNTONEXT AcnGenericTypes.NextDWord -> stg_acn.PP_Alignment_dword () + | ENDIANNESS AcnGenericTypes.LittleEndianness -> stg_acn.PP_Endianness_little () + | ENDIANNESS AcnGenericTypes.BigEndianness -> stg_acn.PP_Endianness_big () | _ -> raise(BugErrorException "Not Implemented yet") let printAcnType (t:ParameterizedAsn1Ast.Asn1Type) (acnProps: GenericAcnProperty list): string = @@ -212,8 +212,7 @@ let generatedAcnGrammar (outDir:string) (ast:GenFile list) = ast |> List.iter generateAcnFile let generateGrammars (path:string) = - + let genAst = createAst ["test-grammar"] generatedAsn1Grammar path genAst generatedAcnGrammar path genAst - \ No newline at end of file diff --git a/BackendAst/PrintAcn.fs b/BackendAst/PrintAcn.fs index 0c6e7f5cb..27098ec55 100644 --- a/BackendAst/PrintAcn.fs +++ b/BackendAst/PrintAcn.fs @@ -17,17 +17,17 @@ let printAcnParamType (pt:AcnGenericTypes.AcnParamType) = |AcnGenericTypes.AcnPrmRefType (md,ts) -> sprintf "%s" ts.Value let printAcnParam (p:AcnGenericTypes.AcnParameter) = - stg_acn.PrintParam p.name (printAcnParamType p.asn1Type) + stg_acn.PrintParam p.name (printAcnParamType p.asn1Type) let rec printTypeEncSpec (t:AcnTypeEncodingSpec) = - let props = + let props = t.acnProperties |> List.map(fun p -> match p with - | ENCODING enc -> + | ENCODING enc -> match enc with | GP_PosInt -> stg_acn.PP_Encoding_PosInt() | GP_TwosComplement -> stg_acn.PP_Encoding_TwosComplement() @@ -35,20 +35,20 @@ let rec printTypeEncSpec (t:AcnTypeEncodingSpec) = | GP_BCD -> stg_acn.PP_Encoding_BCD() | GP_IEEE754_32 -> stg_acn.PP_Encoding_IEEE754_32() | GP_IEEE754_64 -> stg_acn.PP_Encoding_IEEE754_64() - | SIZE siz -> + | SIZE siz -> match siz with | GP_Fixed size -> stg_acn.PP_Size_Fixed size.Value | GP_NullTerminated -> stg_acn.PP_Size_NullTerminated () | GP_SizeDeterminant relativePath -> stg_acn.PP_Sixe_Fld relativePath.AsString - | ALIGNTONEXT al -> + | ALIGNTONEXT al -> match al with - | AcnGenericTypes.NextByte -> stg_acn.PP_Aligment_byte() - | AcnGenericTypes.NextWord -> stg_acn.PP_Aligment_word() - | AcnGenericTypes.NextDWord -> stg_acn.PP_Aligment_dword() + | AcnGenericTypes.NextByte -> stg_acn.PP_Alignment_byte() + | AcnGenericTypes.NextWord -> stg_acn.PP_Alignment_word() + | AcnGenericTypes.NextDWord -> stg_acn.PP_Alignment_dword() | ENCODE_VALUES -> stg_acn.PP_EncodeValues () | SAVE_POSITION -> stg_acn.PP_SavePosition () - | PRESENT_WHEN prWhenList -> + | PRESENT_WHEN prWhenList -> let prCons = prWhenList |> List.map(fun pw -> @@ -62,14 +62,14 @@ let rec printTypeEncSpec (t:AcnTypeEncodingSpec) = stg_acn.PP_PresentWhen [debugStr] | TRUE_VALUE trueVal -> stg_acn.PP_TrueValue trueVal.Value | FALSE_VALUE falseVal -> stg_acn.PP_FalseValue falseVal.Value - | PATTERN pattern -> + | PATTERN pattern -> match pattern with | AcnGenericTypes.PATTERN_PROP_BITSTR_VALUE pat -> stg_acn.PP_NullValue pat.Value - | AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE v -> - let octStr = v |> List.map(fun b -> System.String.Format("{0:X2}", b.Value) ) |> Seq.StrJoin "" - stg_acn.PP_NullValue octStr + | AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE v -> + let octStr = v |> List.map(fun b -> System.String.Format("{0:X2}", b.Value) ) |> Seq.StrJoin "" + stg_acn.PP_NullValue octStr | CHOICE_DETERMINANT relPath -> stg_acn.PP_ChoiceDeterminant relPath.AsString - | ENDIANNES endian -> + | ENDIANNESS endian -> match endian with | AcnGenericTypes.LittleEndianness -> stg_acn.PP_Endianness_little () | AcnGenericTypes.BigEndianness -> stg_acn.PP_Endianness_big () @@ -80,11 +80,11 @@ let rec printTypeEncSpec (t:AcnTypeEncodingSpec) = | POST_ENCODING_FUNCTION (modFncName, fncName) -> match modFncName with None -> fncName.Value | Some modFncName -> modFncName.Value + "." + fncName.Value | PRE_DECODING_FUNCTION (modFncName, fncName) -> match modFncName with None -> fncName.Value | Some modFncName -> modFncName.Value + "." + fncName.Value ) - + let children = t.children |> List.map(fun ch -> - let sImplMode = + let sImplMode = match ch.asn1Type with | Some chType -> printAcnParamType chType | None -> null @@ -94,12 +94,12 @@ let rec printTypeEncSpec (t:AcnTypeEncodingSpec) = let printInASingleFile (r:AcnAst) outDir newFile (tasToPrint:TypeAssignmentInfo list)= - + let allTasses = r.files |> List.collect(fun f -> f.modules) |> List.collect (fun m -> m.typeAssignments) let tasToPrintSet = tasToPrint |> List.map(fun ts -> ts.tasName) |> Set.ofList - let modulesContent = - let tasses = - allTasses |> + let modulesContent = + let tasses = + allTasses |> List.filter(fun tas -> tasToPrintSet.Contains tas.name.Value) |> List.map(fun tas -> stg_acn.PrintTypeAssignment tas.name.Value (tas.acnParameters |> List.map printAcnParam ) [] (printTypeEncSpec tas.typeEncodingSpec)) diff --git a/BackendAst/PrintAsn1.fs b/BackendAst/PrintAsn1.fs index 216d34514..70259a95e 100644 --- a/BackendAst/PrintAsn1.fs +++ b/BackendAst/PrintAsn1.fs @@ -18,15 +18,15 @@ open Asn1Ast open FsUtils open CommonTypes -let rec PrintAsn1Value (v:Asn1Value) = +let rec PrintAsn1Value (v:Asn1Value) = match v.Kind with |IntegerValue(v) -> stg_asn1.Print_IntegerValue v.Value |RealValue(v) -> stg_asn1.Print_RealValue v.Value - |StringValue(parts,_) -> + |StringValue(parts,_) -> match parts with | (CStringValue v)::[] -> stg_asn1.Print_StringValue v - | _ -> stg_asn1.Print_SeqOfValue (parts |> List.map(fun p -> p.AsAsn1)) - |TimeValue v -> + | _ -> stg_asn1.Print_SeqOfValue (parts |> List.map(fun p -> p.AsAsn1)) + |TimeValue v -> stg_asn1.Print_TimeValue (asn1DateTimeValueToString v.Value) |BooleanValue(v) -> stg_asn1.Print_BooleanValue v.Value |BitStringValue(v) -> stg_asn1.Print_BitStringValue v.Value @@ -36,34 +36,34 @@ let rec PrintAsn1Value (v:Asn1Value) = |SeqValue(vals) -> stg_asn1.Print_SeqValue (vals |> Seq.map(fun (nm, v) -> stg_asn1.Print_SeqValue_Child nm.Value (PrintAsn1Value v) ) |> Seq.toArray) |ChValue(nm,v) -> stg_asn1.Print_ChValue nm.Value (PrintAsn1Value v) |NullValue -> stg_asn1.Print_NullValue() - |ObjOrRelObjIdValue coms -> + |ObjOrRelObjIdValue coms -> stg_asn1.Print_ObjOrRelObjIdValue (coms |> List.map DAstAsn1.printComponent) -let rec PrintConstraint (c:Asn1Constraint) = +let rec PrintConstraint (c:Asn1Constraint) = match c with - | SingleValueContraint(_, v) -> stg_asn1.Print_SingleValueContraint (PrintAsn1Value v) - | RangeContraint(_, v1, v2, b1, b2) -> stg_asn1.Print_RangeContraint (PrintAsn1Value v1) (PrintAsn1Value v2) b1 b2 - | RangeContraint_val_MAX(_, v, b1) -> stg_asn1.Print_RangeContraint_val_MAX (PrintAsn1Value v) b1 - | RangeContraint_MIN_val(_, v, b2) -> stg_asn1.Print_RangeContraint_MIN_val (PrintAsn1Value v) b2 - | RangeContraint_MIN_MAX -> stg_asn1.Print_RangeContraint_MIN_MAX() - | TypeInclusionConstraint(_, mn,nm)-> - stg_asn1.Print_TypeInclusionConstraint nm.Value - | SizeContraint(_, c) -> stg_asn1.Print_SizeContraint (PrintConstraint c) - | AlphabetContraint(_, c) -> stg_asn1.Print_AlphabetContraint (PrintConstraint c) - | UnionConstraint(_, c1,c2,virtualCon) -> + | SingleValueConstraint(_, v) -> stg_asn1.Print_SingleValueConstraint (PrintAsn1Value v) + | RangeConstraint(_, v1, v2, b1, b2) -> stg_asn1.Print_RangeConstraint (PrintAsn1Value v1) (PrintAsn1Value v2) b1 b2 + | RangeConstraint_val_MAX(_, v, b1) -> stg_asn1.Print_RangeConstraint_val_MAX (PrintAsn1Value v) b1 + | RangeConstraint_MIN_val(_, v, b2) -> stg_asn1.Print_RangeConstraint_MIN_val (PrintAsn1Value v) b2 + | RangeConstraint_MIN_MAX -> stg_asn1.Print_RangeConstraint_MIN_MAX() + | TypeInclusionConstraint(_, mn,nm)-> + stg_asn1.Print_TypeInclusionConstraint nm.Value + | SizeConstraint(_, c) -> stg_asn1.Print_SizeConstraint (PrintConstraint c) + | AlphabetConstraint(_, c) -> stg_asn1.Print_AlphabetConstraint (PrintConstraint c) + | UnionConstraint(_, c1,c2,virtualCon) -> match virtualCon with - | false -> stg_asn1.Print_UnionConstraint (PrintConstraint c1) (PrintConstraint c2) + | false -> stg_asn1.Print_UnionConstraint (PrintConstraint c1) (PrintConstraint c2) | true -> "" - | IntersectionConstraint(_, c1,c2) -> stg_asn1.Print_IntersectionConstraint (PrintConstraint c1) (PrintConstraint c2) - | AllExceptConstraint(_, c) -> stg_asn1.Print_AllExceptConstraint (PrintConstraint c) - | ExceptConstraint(_, c1,c2) -> stg_asn1.Print_ExceptConstraint (PrintConstraint c1) (PrintConstraint c2) - | RootConstraint(_, c) -> stg_asn1.Print_RootConstraint (PrintConstraint c) + | IntersectionConstraint(_, c1,c2) -> stg_asn1.Print_IntersectionConstraint (PrintConstraint c1) (PrintConstraint c2) + | AllExceptConstraint(_, c) -> stg_asn1.Print_AllExceptConstraint (PrintConstraint c) + | ExceptConstraint(_, c1,c2) -> stg_asn1.Print_ExceptConstraint (PrintConstraint c1) (PrintConstraint c2) + | RootConstraint(_, c) -> stg_asn1.Print_RootConstraint (PrintConstraint c) | RootConstraint2(_, c1,c2) -> stg_asn1.Print_RootConstraint2 (PrintConstraint c1) (PrintConstraint c2) | WithComponentConstraint(_, c,_) -> stg_asn1.Print_WithComponentConstraint (PrintConstraint c) - | WithComponentsConstraint(_, ncs) -> + | WithComponentsConstraint(_, ncs) -> let print_nc (nc:NamedConstraint) = - let sConstraint = match nc.Contraint with + let sConstraint = match nc.Constraint with | Some(c1) -> PrintConstraint c1 | None -> "" let sPresMark = match nc.Mark with @@ -72,7 +72,7 @@ let rec PrintConstraint (c:Asn1Constraint) = | MarkAbsent -> "ABSENT" | MarkOptional -> "OPTIONAL" stg_asn1.Print_WithComponentsConstraint_child nc.Name.Value sConstraint sPresMark - stg_asn1.Print_WithComponentsConstraint (ncs |> Seq.map print_nc |> Seq.toArray) + stg_asn1.Print_WithComponentsConstraint (ncs |> Seq.map print_nc |> Seq.toArray) let rec PrintType (t:Asn1Type) (m:Asn1Module) (bPrintInSingleModule:bool) = let cons = t.Constraints |> Seq.map PrintConstraint |> Seq.toArray @@ -88,7 +88,7 @@ let rec PrintType (t:Asn1Type) (m:Asn1Module) (bPrintInSingleModule:bool) = |ObjectIdentifier -> stg_asn1.Print_ObjectIdenitifier cons |RelativeObjectIdentifier -> stg_asn1.Print_RelativeObjectIdenitifier cons |Enumerated(items) -> - let printItem i (it:NamedItem) = + let printItem i (it:NamedItem) = let arrsMultilineComments, soSingleLineComment = match it.Comments |> Seq.toList with | [] -> [], None @@ -98,7 +98,7 @@ let rec PrintType (t:Asn1Type) (m:Asn1Module) (bPrintInSingleModule:bool) = stg_asn1.Print_Enumerated_child it.Name.Value it._value.IsSome (if it._value.IsSome then (PrintAsn1Value it._value.Value) else "") arrsMultilineComments soSingleLineComment bLastChild stg_asn1.Print_Enumerated (items |> Seq.mapi printItem |> Seq.toArray) cons |Choice(children) -> - let printChild i (c:ChildInfo) = + let printChild i (c:ChildInfo) = let arrsMultilineComments, soSingleLineComment = match c.Comments |> Seq.toList with | [] -> [], None @@ -108,26 +108,27 @@ let rec PrintType (t:Asn1Type) (m:Asn1Module) (bPrintInSingleModule:bool) = stg_asn1.Print_Choice_child c.Name.Value (PrintType c.Type m bPrintInSingleModule) arrsMultilineComments soSingleLineComment bLastChild stg_asn1.Print_Choice (children |> Seq.mapi printChild |> Seq.toArray) cons |Sequence(children) -> - let printChild i (c:ChildInfo) = + let printChild i (c:ChildInfo) = let arrsMultilineComments, soSingleLineComment = match c.Comments |> Seq.toList with | [] -> [], None | x::[] -> [], Some x | xs -> xs, None let bLastChild = i = children.Length - 1 - let bIsOptionalOrDefault, soDefValue = + let bIsOptionalOrDefault, soDefValue = match c.Optionality with |Some(Optional(dv)) -> true, match dv.defaultValue with Some v -> Some (PrintAsn1Value v) | None -> None |_ -> false, None stg_asn1.Print_Sequence_child c.Name.Value (PrintType c.Type m bPrintInSingleModule) bIsOptionalOrDefault soDefValue arrsMultilineComments soSingleLineComment bLastChild stg_asn1.Print_Sequence (children |> Seq.mapi printChild |> Seq.toArray) cons |SequenceOf(child) -> stg_asn1.Print_SequenceOf (PrintType child m bPrintInSingleModule) cons - //|ReferenceType(mname, name, _) -> - |ReferenceType(r) -> + //|ReferenceType(mname, name, _) -> + |ReferenceType(r) -> match bPrintInSingleModule || m.Name.Value = r.modName.Value with | true -> stg_asn1.Print_ReferenceType1 r.tasName.Value cons | false -> stg_asn1.Print_ReferenceType2 r.modName.Value r.tasName.Value cons - + |TimeType t -> stg_asn1.Print_TimeType cons + let PrintTypeAss (t:TypeAssignment) m bPrintInSingleModule = stg_asn1.PrintTypeAssignment t.Name.Value (PrintType t.Type m bPrintInSingleModule) t.Comments "::=" @@ -160,60 +161,61 @@ let DoWork (r:AstRoot) outDir newFileExt = let printInASingleFile (r:AstRoot) outDir newFile (pdu:string option)= - + let rec getTypeDependencies2 (tsMap:Map) (deep:bool) (t:Asn1Type) : (TypeAssignmentInfo list ) = match t.Kind with - | Integer _ -> [] - | Real _ -> [] - | IA5String _ -> [] - | NumericString _ -> [] - | OctetString _ -> [] - | NullType _ -> [] - | BitString _ -> [] - | Boolean _ -> [] - | Enumerated _ -> [] + | Integer -> [] + | Real -> [] + | IA5String -> [] + | NumericString -> [] + | OctetString -> [] + | NullType -> [] + | BitString _ -> [] + | Boolean -> [] + | Enumerated _ -> [] | ObjectIdentifier -> [] | RelativeObjectIdentifier -> [] - | SequenceOf sqof -> (getTypeDependencies2 tsMap deep sqof) + | TimeType _ -> [] + | SequenceOf sqof -> (getTypeDependencies2 tsMap deep sqof) | Sequence children -> (children |> List.collect (fun ch -> getTypeDependencies2 tsMap deep ch.Type)) | Choice children -> (children |> List.collect (fun ch -> getTypeDependencies2 tsMap deep ch.Type)) - | ReferenceType ref -> + | ReferenceType ref -> let thisRef = {TypeAssignmentInfo.modName = ref.modName.Value; TypeAssignmentInfo.tasName = ref.tasName.Value} match deep with | false -> [thisRef] - | true -> + | true -> let ts = tsMap.[thisRef] thisRef::(getTypeDependencies2 tsMap deep ts.Type) let allTasses = - r.Files |> - List.collect(fun f -> f.Modules) |> - List.collect(fun m -> + r.Files |> + List.collect(fun f -> f.Modules) |> + List.collect(fun m -> m.TypeAssignments |> List.map(fun ts -> ({TypeAssignmentInfo.modName = m.Name.Value; TypeAssignmentInfo.tasName = ts.Name.Value}, ts))) let modMap = r.Files |> List.collect(fun f -> f.Modules) |> List.map(fun m -> m.Name.Value, m) |> Map.ofList let tsMap = allTasses |> Map.ofList let allVasses = r.Files |> List.collect(fun f -> f.Modules) |> List.collect(fun m -> m.ValueAssignments |> List.map(fun vs -> m,vs)) - let allNodesToSort = + let allNodesToSort = allTasses |> List.map(fun (tasInfo,ts) -> (tasInfo, getTypeDependencies2 tsMap false ts.Type)) let independentNodes = allNodesToSort |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map(fun (n,l) -> n) let dependentNodes = allNodesToSort |> List.filter(fun (_,list) -> not (List.isEmpty list) ) - let sortedTypeAss = - DoTopologicalSort independentNodes dependentNodes - (fun cyclicTasses -> + let sortedTypeAss = + DoTopologicalSort independentNodes dependentNodes + (fun cyclicTasses -> match cyclicTasses with | [] -> BugErrorException "Impossible" | (m1,deps) ::_ -> - let printTas (md:TypeAssignmentInfo, deps: TypeAssignmentInfo list) = + let printTas (md:TypeAssignmentInfo, deps: TypeAssignmentInfo list) = sprintf "Type assignment '%s.%s' depends on : %s" md.modName md.tasName (deps |> List.map(fun z -> "'" + z.modName + "." + z.tasName + "'") |> Seq.StrJoin ", ") let cycTasses = cyclicTasses |> List.map printTas |> Seq.StrJoin "\n\tand\n" SemanticError(emptyLocation, sprintf "Cyclic Types detected:\n%s\n" cycTasses) ) - let tastToPrint = + let tastToPrint = match pdu with | None -> sortedTypeAss | Some pdu -> match allTasses |> Seq.tryFind(fun (_,ts) -> ts.Name.Value = pdu) with - | None -> + | None -> Console.Error.WriteLine("No type assignment with name {0} found", pdu) sortedTypeAss | Some (tsInfo,ts) -> diff --git a/BackendAst/createDefinitions.fs b/BackendAst/createDefinitions.fs index 67d3446f7..443df4260 100644 --- a/BackendAst/createDefinitions.fs +++ b/BackendAst/createDefinitions.fs @@ -23,7 +23,7 @@ let rec createTypeDeclaration (t:Asn1Type) (p:list) (r:AstRoot) = } match t.Kind with - | Integer -> + | Integer -> match (GetTypeUperRange t.Kind t.Constraints r) with | Concrete(a,b) when a >= 0I -> POS_INTEGER | Concrete(a,b) -> INTEGER @@ -33,16 +33,16 @@ let rec createTypeDeclaration (t:Asn1Type) (p:list) (r:AstRoot) = | Empty | Full -> INTEGER | Boolean -> BOOLEAN | Real -> REAL - | IA5String + | IA5String | NumericString -> STRING | NullType -> VOID_TYPE - | BitString(_) -> + | BitString(_) -> let nMin, nMax = SizeableTypeUperRange() let bsInfo = {BitStringTypeInfo.nBitLen = (TypeItemsCount t r); nBytesLen = (TypeCArrayItemsCount t r) } match (nMin=nMax) with | true -> FIX_SIZE_BIT_STRING bsInfo | false -> VAR_SIZE_BIT_STRING bsInfo - | OctetString -> + | OctetString -> let nMin, nMax = SizeableTypeUperRange() let nOctLen = TypeCArrayItemsCount t r match (nMin=nMax) with @@ -51,11 +51,11 @@ let rec createTypeDeclaration (t:Asn1Type) (p:list) (r:AstRoot) = | Enumerated(items) -> let PrintNamedItem (it:NamedItem,value:BigInteger) = match it._value with - | Some(vl) -> (it.CEnumName r C), (Ast.GetValueAsInt vl r) - | None -> (it.CEnumName r C), value - let result = + | Some(vl) -> (it.CEnumName r C), (Ast.GetValueAsInt vl r) + | None -> (it.CEnumName r C), value + let result = items |> Seq.mapi(fun i ch -> (ch, (BigInteger i)) ) |> Seq.toList - ENUM (result |> List.map PrintNamedItem ) + ENUM (result |> List.map PrintNamedItem ) | Choice(children) -> let choiceTypeInfo = { ChoiceTypeInfo.choiceIDForNone = (TypeLongName p)+"_NONE" @@ -66,27 +66,27 @@ let rec createTypeDeclaration (t:Asn1Type) (p:list) (r:AstRoot) = | Sequence(chldrn) -> let children = chldrn |> List.filter(fun x -> not x.AcnInsertedField) let sequenceTypeInfo = { - SequenceTypeInfo.optChildren = children |> List.filter(fun x -> x.Optionality.IsSome) |> List.map(fun x -> x.CName ProgrammingLanguage.C) - children = children |> List.map PrintChoiceSeqChild + SequenceTypeInfo.optChildren = children |> List.filter(fun x -> x.Optionality.IsSome) |> List.map(fun x -> x.CName ProgrammingLanguage.C) + children = children |> List.map PrintChoiceSeqChild } SEQUENCE sequenceTypeInfo | SequenceOf(child) -> let nMin, nMax = SizeableTypeUperRange() let sequenceOfTypeInfo = { SequenceOfTypeInfo.typeDef = createTypeDeclaration child (p@["#"]) r - length = (TypeCArrayItemsCount t r) - arrayPostfix = (TypeArrayPostfix child r) + length = (TypeCArrayItemsCount t r) + arrayPostfix = (TypeArrayPostfix child r) } match nMin=nMax with | true -> FIX_SIZE_SEQUENCE_OF sequenceOfTypeInfo | false -> VAR_SIZE_SEQUENCE_OF sequenceOfTypeInfo - | ReferenceType(m,tasName, _) -> + | ReferenceType(m,tasName, _) -> LOCAL_REFENCED_TYPE (GetTasCName tasName.Value r.TypePrefix) -let createTypeAss (r:AstRoot) (acn:AcnTypes.AcnAstResolved) (f:Asn1File) (m:Asn1Module) (t:TypeAssignment) = +let createTypeAss (r:AstRoot) (acn:AcnTypes.AcnAstResolved) (f:Asn1File) (m:Asn1Module) (t:TypeAssignment) = let errorCodes = [] let sName = t.GetCName r.TypePrefix let nMaxBitsInACN, nMaxBytesInACN = Acn.RequiredBitsForAcnEncodingInt t.Type [m.Name.Value; t.Name.Value] r acn @@ -94,47 +94,47 @@ let createTypeAss (r:AstRoot) (acn:AcnTypes.AcnAstResolved) (f:Asn1File) (m:Asn TasDefition.sTypeDecl = createTypeDeclaration t.Type [m.Name.Value; t.Name.Value] r sarrPostfix = TypeArrayPostfix t.Type r sName = sName - nMaxBitsInPER = uperGetMaxSizeInBitsAsInt t.Type.Kind t.Type.Constraints t.Type.Location r - nMaxBytesInPER = uperGetMaxSizeInBytesAsInt t.Type.Kind t.Type.Constraints t.Type.Location r + nMaxBitsInPER = uperGetMaxSizeInBitsAsInt t.Type.Kind t.Type.Constraints t.Type.Location r + nMaxBytesInPER = uperGetMaxSizeInBytesAsInt t.Type.Kind t.Type.Constraints t.Type.Location r nMaxBitsInACN = nMaxBitsInACN nMaxBytesInACN = nMaxBytesInACN - nMaxBytesInXER = XER_bl.GetMaxSizeInBytesForXER t.Type t.Name.Value r - sStar = (TypeStar t.Type r) + nMaxBytesInXER = XER_bl.GetMaxSizeInBytesForXER t.Type t.Name.Value r + sStar = (TypeStar t.Type r) errorCodes = [] isConstraintValidFnc = {TasIsConstraintValid.funcName = sprintf "%s_IsConstraintValid" sName} isEqualFnc = {TasIsEqual.funcName = sprintf "%s_Equal" sName} - inititalizeFnc = {TasInititalize.funcName = sprintf "%s_Initialize" sName} + initializeFnc = {TasInitialize.funcName = sprintf "%s_Initialize" sName} } let SortTypeAssignments (f:Asn1File) (r:AstRoot) (acn:AcnTypes.AcnAstResolved) = - let GetTypeDependencies (tas:TypeAssignment) = + let GetTypeDependencies (tas:TypeAssignment) = seq { for ch in (GetMySelfAndChildren tas.Type) do match ch.Kind with - | ReferenceType(_, tasName, _) -> yield tasName.Value; + | ReferenceType(_, tasName, _) -> yield tasName.Value; | _ -> () } |> Seq.distinct |> Seq.toList let allNodes = f.TypeAssignments |> List.map( fun tas -> (tas.Name.Value, GetTypeDependencies tas)) - let importedTypes = + let importedTypes = let thisFileModules = f.Modules |> List.map(fun x -> x.Name.Value) - f.Modules |> + f.Modules |> Seq.collect(fun m -> m.Imports) |> Seq.filter(fun m -> not (thisFileModules |> Seq.exists ((=) m.Name.Value) )) |> - Seq.collect(fun imp -> imp.Types) |> - Seq.map(fun x -> x.Value) |> + Seq.collect(fun imp -> imp.Types) |> + Seq.map(fun x -> x.Value) |> Seq.distinct |> Seq.toList let independentNodes = allNodes |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map(fun (n,l) -> n) let dependentNodes = allNodes |> List.filter(fun (_,list) -> not (List.isEmpty list) ) - let sortedTypeAss = - DoTopologicalSort (importedTypes @ independentNodes) dependentNodes - (fun c -> + let sortedTypeAss = + DoTopologicalSort (importedTypes @ independentNodes) dependentNodes + (fun c -> SemanticError - (emptyLocation, - sprintf - "Recursive types are not compatible with embedded systems.\nASN.1 grammar has cyclic dependencies: %A" + (emptyLocation, + sprintf + "Recursive types are not compatible with embedded systems.\nASN.1 grammar has cyclic dependencies: %A" c)) seq { for tasName in sortedTypeAss do @@ -149,19 +149,19 @@ let SortTypeAssignments (f:Asn1File) (r:AstRoot) (acn:AcnTypes.AcnAstResolved) = let createDefinitionsFile (r:AstRoot) (acn:AcnTypes.AcnAstResolved) (l:ProgrammingLanguage) (f:Asn1File) = let fileNameNoExtUpper = f.FileNameWithoutExtension.ToUpper() let allImportedModules = f.Modules |> Seq.collect(fun m -> m.Imports) |> Seq.map(fun imp -> imp.Name.Value) |> Seq.distinct - let includedModules = seq { + let includedModules = seq { for file in r.Files do if file.FileName <> f.FileName then if file.Modules |> Seq.exists (fun m -> allImportedModules |> Seq.exists(fun x -> x = m.Name.Value)) then - yield file.FileNameWithoutExtension } |> Seq.toList + yield file.FileNameWithoutExtension } |> Seq.toList let sortedTas = SortTypeAssignments f r acn //let protos = sortedTas |> Seq.map(fun (m,tas) -> PrintAcnProtos tas m f r acn ) { DefinitionsFile.fileName = Path.Combine(f.FileNameWithoutExtension+l.DefinitionsFileExt) fileNameNoExtUpper = (ToC fileNameNoExtUpper) - tases = sortedTas |> List.map (fun (m,tas) -> createTypeAss r acn f m tas ) + tases = sortedTas |> List.map (fun (m,tas) -> createTypeAss r acn f m tas ) } let DoWork (r:AstRoot) (acn:AcnTypes.AcnAstResolved) (l:ProgrammingLanguage) = - r.Files |> Seq.map (createDefinitionsFile r acn l) + r.Files |> Seq.map (createDefinitionsFile r acn l) diff --git a/BackendAst/print_debug.fs b/BackendAst/print_debug.fs index 78e3d55d2..3d3608839 100644 --- a/BackendAst/print_debug.fs +++ b/BackendAst/print_debug.fs @@ -23,71 +23,71 @@ let printUperRange (u:uperRange<'a>) = | Full -> "[MIN .. MAX]" // (-inf, +inf) let printCharSet (cs:char array) = - cs|> Seq.filter (fun c -> not (Char.IsControl c)) |> Seq.StrJoin "" + cs|> Seq.filter (fun c -> not (Char.IsControl c)) |> Seq.StrJoin "" let printSizeMinMax a b = sprintf "[%d .. %d]" a b -let printGenericConstraint printValue (c:GenericConstraint<'v>) = +let printGenericConstraint printValue (c:GenericConstraint<'v>) = foldGenericConstraint (fun r1 r2 b s -> stg_asn1.Print_UnionConstraint r1 r2, s) (fun r1 r2 s -> stg_asn1.Print_IntersectionConstraint r1 r2 , s) - (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) + (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_ExceptConstraint r1 r2, s) - (fun r s -> stg_asn1.Print_RootConstraint r, s) + (fun r s -> stg_asn1.Print_RootConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_RootConstraint2 r1 r2, s) - (fun v rv s -> stg_asn1.Print_SingleValueContraint (printValue v),s) - c + (fun v rv s -> stg_asn1.Print_SingleValueConstraint (printValue v),s) + c 0 -let printRangeConstraint0 printValue printValue2 (c:RangeTypeConstraint<'v1,'v2>) = +let printRangeConstraint0 printValue printValue2 (c:RangeTypeConstraint<'v1,'v2>) = foldRangeTypeConstraint (fun r1 r2 b s -> stg_asn1.Print_UnionConstraint r1 r2, s) (fun r1 r2 s -> stg_asn1.Print_IntersectionConstraint r1 r2 , s) - (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) + (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_ExceptConstraint r1 r2, s) - (fun r s -> stg_asn1.Print_RootConstraint r, s) + (fun r s -> stg_asn1.Print_RootConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_RootConstraint2 r1 r2, s) - (fun v rv s -> stg_asn1.Print_SingleValueContraint (printValue2 v),s) - (fun v1 v2 b1 b2 s -> stg_asn1.Print_RangeContraint (printValue v1) (printValue v2) b1 b2, s) - (fun v1 b s -> stg_asn1.Print_RangeContraint_val_MAX (printValue v1) b ,s ) - (fun v2 b s -> stg_asn1.Print_RangeContraint_MIN_val (printValue v2) b, s) - c + (fun v rv s -> stg_asn1.Print_SingleValueConstraint (printValue2 v),s) + (fun v1 v2 b1 b2 s -> stg_asn1.Print_RangeConstraint (printValue v1) (printValue v2) b1 b2, s) + (fun v1 b s -> stg_asn1.Print_RangeConstraint_val_MAX (printValue v1) b ,s ) + (fun v2 b s -> stg_asn1.Print_RangeConstraint_MIN_val (printValue v2) b, s) + c 0 -let printRangeConstraint printValue (c:RangeTypeConstraint<'v1,'v1>) = - printRangeConstraint0 printValue printValue c +let printRangeConstraint printValue (c:RangeTypeConstraint<'v1,'v1>) = + printRangeConstraint0 printValue printValue c -let printSizableConstraint printValue (c:SizableTypeConstraint<'v>) = +let printSizableConstraint printValue (c:SizableTypeConstraint<'v>) = foldSizableTypeConstraint2 (fun r1 r2 b s -> stg_asn1.Print_UnionConstraint r1 r2, s) (fun r1 r2 s -> stg_asn1.Print_IntersectionConstraint r1 r2 , s) - (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) + (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_ExceptConstraint r1 r2, s) - (fun r s -> stg_asn1.Print_RootConstraint r, s) + (fun r s -> stg_asn1.Print_RootConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_RootConstraint2 r1 r2, s) - (fun v rv s -> stg_asn1.Print_SingleValueContraint (printValue v),s) - (fun sc s -> - let sizeCon,_ = printRangeConstraint (fun ui -> ui.ToString()) sc - stg_asn1.Print_SizeContraint sizeCon, s) - c + (fun v rv s -> stg_asn1.Print_SingleValueConstraint (printValue v),s) + (fun sc s -> + let sizeCon,_ = printRangeConstraint (fun ui -> ui.ToString()) sc + stg_asn1.Print_SizeConstraint sizeCon, s) + c 0 -let printAlphaConstraint printValue (c:IA5StringConstraint) = +let printAlphaConstraint printValue (c:IA5StringConstraint) = foldStringTypeConstraint2 (fun r1 r2 b s -> stg_asn1.Print_UnionConstraint r1 r2, s) (fun r1 r2 s -> stg_asn1.Print_IntersectionConstraint r1 r2 , s) - (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) + (fun r s -> stg_asn1.Print_AllExceptConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_ExceptConstraint r1 r2, s) - (fun r s -> stg_asn1.Print_RootConstraint r, s) + (fun r s -> stg_asn1.Print_RootConstraint r, s) (fun r1 r2 s -> stg_asn1.Print_RootConstraint2 r1 r2, s) - (fun v rv s -> stg_asn1.Print_SingleValueContraint (printValue v),s) - (fun sc s -> - let sizeCon,_ = printRangeConstraint (fun ui -> ui.ToString()) sc - stg_asn1.Print_SizeContraint sizeCon, s) - (fun sc s -> - let sizeCon,_ = printRangeConstraint0 (fun ui -> "\"" + ui.ToString() + "\"") (fun ui -> "\"" + ui.ToString() + "\"") sc - stg_asn1.Print_AlphabetContraint sizeCon, s) - c + (fun v rv s -> stg_asn1.Print_SingleValueConstraint (printValue v),s) + (fun sc s -> + let sizeCon,_ = printRangeConstraint (fun ui -> ui.ToString()) sc + stg_asn1.Print_SizeConstraint sizeCon, s) + (fun sc s -> + let sizeCon,_ = printRangeConstraint0 (fun ui -> "\"" + ui.ToString() + "\"") (fun ui -> "\"" + ui.ToString() + "\"") sc + stg_asn1.Print_AlphabetConstraint sizeCon, s) + c 0 @@ -106,9 +106,9 @@ and printReferenceToValue (r:AstRoot) (p:PRINT_CONTENT) (ReferenceToValue (path, | false -> p1 + "." + p2 | CON -> PrintAsn1GenericValue r r.valsMap.[(ReferenceToValue (path, vpath))] - -and PrintAsn1GenericValue (r:AstRoot) (v:Asn1GenericValue) = + +and PrintAsn1GenericValue (r:AstRoot) (v:Asn1GenericValue) = match v with |IntegerValue(v) -> stg_asn1.Print_IntegerValue v.Value |RealValue(v) -> stg_asn1.Print_RealValue v.Value @@ -143,20 +143,20 @@ and PrintType (r:AstRoot) (t:Asn1Type) = |BitString x -> stg_asn1.Print_BitString (cmb x |> List.map (printCon printSizableConstraint (fun x -> stg_asn1.Print_BitStringValue x.Value ) ) ) |OctetString x -> stg_asn1.Print_OctetString (cmb x |> List.map (printCon printSizableConstraint (fun x -> stg_asn1.Print_OctetStringValue x.Value) ) ) |NullType _ -> stg_asn1.Print_NullType [] - |IA5String x -> + |IA5String x -> stg_asn1.Print_IA5String2 (printSizeMinMax x.minSize x.maxSize) (printCharSet x.charSet ) (cmb x |> List.map (printCon printAlphaConstraint (fun x -> x.ToString()) ) ) |Enumerated x -> let items = x.items |> List.map(fun itm -> stg_asn1.Print_Enumerated_child itm.name true (itm.Value.ToString() )) - let cons = cmb x |> List.map (printCon printGenericConstraint (fun x -> x.ToString()) ) + let cons = cmb x |> List.map (printCon printGenericConstraint (fun x -> x.ToString()) ) stg_asn1.Print_Enumerated items cons |Choice x -> let printChild (c:ChChildInfo) = stg_asn1.Print_Choice_child c.name (printReferenceToType r CON c.chType.id) - let cons = cmb x |> List.map (printCon printGenericConstraint (fun chv -> stg_asn1.Print_ChValue chv.Value.name (printReferenceToValue r CON chv.Value.Value.id) ) ) + let cons = cmb x |> List.map (printCon printGenericConstraint (fun chv -> stg_asn1.Print_ChValue chv.Value.name (printReferenceToValue r CON chv.Value.Value.id) ) ) stg_asn1.Print_Choice (x.children |> Seq.map printChild |> Seq.toArray) cons |Sequence x -> - let printChild (c:SeqChildInfo) = - let bIsOptionalOrDefault, soDefValue = + let printChild (c:SeqChildInfo) = + let bIsOptionalOrDefault, soDefValue = match c.optionality with | Some(CAst.AlwaysAbsent) -> true, None | Some(CAst.AlwaysPresent) -> true, None @@ -166,19 +166,19 @@ and PrintType (r:AstRoot) (t:Asn1Type) = | Some v -> true, Some (printReferenceToValue r CON v.id) | None -> false, None stg_asn1.Print_Sequence_child c.name (printReferenceToType r CON c.chType.id) bIsOptionalOrDefault soDefValue - let cons = cmb x |> List.map (printCon printGenericConstraint (fun sqv -> stg_asn1.Print_SeqValue (sqv.Value |> List.map(fun nmv -> stg_asn1.Print_SeqValue_Child nmv.name (printReferenceToValue r CON nmv.Value.id) ) ) ) ) + let cons = cmb x |> List.map (printCon printGenericConstraint (fun sqv -> stg_asn1.Print_SeqValue (sqv.Value |> List.map(fun nmv -> stg_asn1.Print_SeqValue_Child nmv.name (printReferenceToValue r CON nmv.Value.id) ) ) ) ) stg_asn1.Print_Sequence (x.children |> Seq.map printChild |> Seq.toArray) cons - |SequenceOf x -> - let cons = cmb x |> List.map (printCon printSizableConstraint (fun sqofv -> stg_asn1.Print_SeqOfValue (sqofv.Value |> Seq.map (fun v -> printReferenceToValue r CON v.id) |> Seq.toArray) ) ) + |SequenceOf x -> + let cons = cmb x |> List.map (printCon printSizableConstraint (fun sqofv -> stg_asn1.Print_SeqOfValue (sqofv.Value |> Seq.map (fun v -> printReferenceToValue r CON v.id) |> Seq.toArray) ) ) stg_asn1.Print_SequenceOf (printReferenceToType r CON x.childType.id) cons -let PrintTypeAss (r:AstRoot) (t:Asn1Type) = +let PrintTypeAss (r:AstRoot) (t:Asn1Type) = let nm = match t.asn1Name with Some x -> x | None -> "anonymous" let bnm = t.baseType |> Option.map (fun t -> printReferenceToType r REF t.id) stg_asn1.PrintTypeAssignment2 (printReferenceToType r REF t.id) bnm nm (PrintType r t) -let PrintValueAss (r:AstRoot) (v:Asn1GenericValue) = +let PrintValueAss (r:AstRoot) (v:Asn1GenericValue) = stg_asn1.PrintValueAssignment (printReferenceToValue r REF v.id) (printReferenceToType r REF v.refToType) (PrintAsn1GenericValue r v) let PrintModule (r:AstRoot) (m:Asn1Module) = diff --git a/BackendAst/validate.fs b/BackendAst/validate.fs index 0ae7966a1..b71090a2a 100644 --- a/BackendAst/validate.fs +++ b/BackendAst/validate.fs @@ -11,14 +11,14 @@ open CloneTree open BackendAst -let rec getCharComparisonBoolExp (path:list) (c:Asn1Constraint) (m:Asn1Module) (r:AstRoot) : CharComparisonBoolExp option= - let p = AccessPath "pVal[i]" +let rec getCharComparisonBoolExp (path:list) (c:Asn1Constraint) (m:Asn1Module) (r:AstRoot) : CharComparisonBoolExp option= + let p = AccessPath "pVal[i]" let tasName = path.Tail.Head match c with - | SingleValueContraint(v) -> + | SingleValueConstraint(v) -> let strVal = GetValueAstring v r Some (AlphaStringContainsChar(p, strVal)) - | RangeContraint(a,b,minIsIn,maxIsIn) -> + | RangeConstraint(a,b,minIsIn,maxIsIn) -> let char1 = GetValueAstring a r let char2 = GetValueAstring b r let b1 = match minIsIn with @@ -28,25 +28,25 @@ let rec getCharComparisonBoolExp (path:list) (c:Asn1Constraint) (m:Asn1M | true -> AlphaGreaterThanOrEq (p, char2.Chars 0) | false -> AlphaGreaterThan(p, char2.Chars 0) Some(AlphaAnd(b1,b2)) - | RangeContraint_val_MAX(a,minIsIn) -> + | RangeConstraint_val_MAX(a,minIsIn) -> let char1 = GetValueAstring a r match minIsIn with | true -> Some (AlphaLessThanOrEq(p, char1.Chars 0)) | false -> Some (AlphaLessThan(p, char1.Chars 0)) - | RangeContraint_MIN_val(b,maxIsIn) -> + | RangeConstraint_MIN_val(b,maxIsIn) -> let char2 = GetValueAstring b r match maxIsIn with | true -> Some(AlphaGreaterThanOrEq (p, char2.Chars 0)) | false -> Some(AlphaGreaterThan(p, char2.Chars 0)) - | RangeContraint_MIN_MAX -> None - | RootConstraint2(c1,c2) - | UnionConstraint(c1, c2,_) -> + | RangeConstraint_MIN_MAX -> None + | RootConstraint2(c1,c2) + | UnionConstraint(c1, c2,_) -> let k1 = getCharComparisonBoolExp path c1 m r let k2 = getCharComparisonBoolExp path c2 m r match k1,k2 with | Some k1, Some k2 -> Some(AlphaOr(k1, k2)) | _ -> None - | IntersectionConstraint(c1,c2) -> + | IntersectionConstraint(c1,c2) -> let k1 = getCharComparisonBoolExp path c1 m r let k2 = getCharComparisonBoolExp path c2 m r match k1,k2 with @@ -54,12 +54,12 @@ let rec getCharComparisonBoolExp (path:list) (c:Asn1Constraint) (m:Asn1M | Some k1, None -> Some k1 | None, Some k2 -> Some k2 | None, None -> None - | AllExceptConstraint(c1) -> + | AllExceptConstraint(c1) -> let k1 = getCharComparisonBoolExp path c1 m r match k1 with | Some k1 -> Some(AlphaNot k1) | None -> raise(BugErrorException "Always false case !!!") - | ExceptConstraint(c1,c2) -> + | ExceptConstraint(c1,c2) -> let k1 = getCharComparisonBoolExp path c1 m r let k2 = getCharComparisonBoolExp path c2 m r match k1,k2 with @@ -72,15 +72,15 @@ let rec getCharComparisonBoolExp (path:list) (c:Asn1Constraint) (m:Asn1M -let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:Asn1Constraint) (m:Asn1Module) (r:AstRoot) : BackendBooleanExpression option= - let p = AccessPath ""//(GetConstraintTypeAccessPath path t r) +let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:Asn1Constraint) (m:Asn1Module) (r:AstRoot) : BackendBooleanExpression option= + let p = AccessPath ""//(GetConstraintTypeAccessPath path t r) let tasName = path.Tail.Head match c with - | SingleValueContraint(v) -> + | SingleValueConstraint(v) -> let unamevar = Ast.GetValueID v let uvar = {UnnamedVariableDeclaration.privateName = unamevar; typereference=("",""); value="" } match t.Type.Kind with - | BitString -> + | BitString -> match (GetTypeUperRange t.Type.Kind t.Type.Constraints r) with | Concrete(min, max) when min = max -> Some (FixSizeBitStringEq (p, uvar)) | Concrete(min, max) -> Some (VarSizeBitStringEq (p, uvar)) @@ -90,10 +90,10 @@ let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:As | Concrete(min, max) when min = max -> Some (FixSizeOctStringEq (p, uvar)) | Concrete(min, max) -> Some (VarSizeOctStringEq (p, uvar)) | _ -> raise(BugErrorException "") - | _ -> + | _ -> let primaryExp = variable.getBackendPrimaryExpression v t.Type m r Some (EqExp(p, primaryExp)) - | RangeContraint(a,b,minIsIn,maxIsIn) -> + | RangeConstraint(a,b,minIsIn,maxIsIn) -> let aNum = variable.getBackendPrimaryNumericExpression a t.Type m r let bNum = variable.getBackendPrimaryNumericExpression b t.Type m r let b1 = match minIsIn with @@ -103,19 +103,19 @@ let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:As | true -> GreaterThanOrEqExp(p, bNum) | false -> GreaterThanExp(p, bNum) Some(AndConstraintExp(b1,b2)) - | RangeContraint_val_MAX(a,minIsIn) -> + | RangeConstraint_val_MAX(a,minIsIn) -> let aNum = variable.getBackendPrimaryNumericExpression a t.Type m r match minIsIn with | true -> Some(LessThanOrEqExp(p, aNum)) | false -> Some(LessThanExp(p, aNum)) - | RangeContraint_MIN_val(b,maxIsIn) -> + | RangeConstraint_MIN_val(b,maxIsIn) -> let bNum = variable.getBackendPrimaryNumericExpression b t.Type m r match maxIsIn with | true -> Some(GreaterThanOrEqExp(p, bNum)) | false -> Some(GreaterThanExp(p, bNum)) - | RangeContraint_MIN_MAX -> None - | SizeContraint(inCon) -> getBackendBooleanExpression (LengthOf t.Type) path inCon m r - | AlphabetContraint(inCon) -> + | RangeConstraint_MIN_MAX -> None + | SizeConstraint(inCon) -> getBackendBooleanExpression (LengthOf t.Type) path inCon m r + | AlphabetConstraint(inCon) -> let charCompExp = getCharComparisonBoolExp path inCon m r match charCompExp with | None -> None @@ -123,14 +123,14 @@ let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:As let alphaFuncName = ToC ((path |> Seq.skip 1).StrJoin("_").Replace("#","elem")) let alphabetCheckFunc = { AlphabetCheckFunc.funcName = alphaFuncName; con = charCompExp} Some (CallAlphaFunc(p, alphabetCheckFunc)) - | RootConstraint2(c1,c2) - | UnionConstraint(c1, c2,_) -> + | RootConstraint2(c1,c2) + | UnionConstraint(c1, c2,_) -> let k1 = getBackendBooleanExpression t path c1 m r let k2 = getBackendBooleanExpression t path c2 m r match k1,k2 with | Some k1, Some k2 -> Some(OrConstraintExp(k1, k2)) | _ -> None - | IntersectionConstraint(c1,c2) -> + | IntersectionConstraint(c1,c2) -> let k1 = getBackendBooleanExpression t path c1 m r let k2 = getBackendBooleanExpression t path c2 m r match k1,k2 with @@ -138,12 +138,12 @@ let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:As | Some k1, None -> Some k1 | None, Some k2 -> Some k2 | None, None -> None - | AllExceptConstraint(c1) -> + | AllExceptConstraint(c1) -> let k1 = getBackendBooleanExpression t path c1 m r match k1 with | Some k1 -> Some(NotConstraintExp (k1)) | None -> raise(BugErrorException "Always false case !!!") - | ExceptConstraint(c1,c2) -> + | ExceptConstraint(c1,c2) -> let k1 = getBackendBooleanExpression t path c1 m r let k2 = getBackendBooleanExpression t path c2 m r match k1,k2 with @@ -155,8 +155,8 @@ let rec getBackendBooleanExpression (t:ConstraintType) (path:list) (c:As | TypeInclusionConstraint(modName,tasName) -> let actualType = GetActualTypeByNameAllConsIncluded modName tasName r let arrCons = actualType.Constraints |> Seq.map(fun c -> getBackendBooleanExpression t path c m r) |> Seq.choose id |> Seq.toList - - arrCons |> + + arrCons |> List.fold (fun s c -> match s with | None -> Some c | Some c0 -> Some (OrConstraintExp (c0, c))) None diff --git a/CommonTypes/AbstractMacros.fs b/CommonTypes/AbstractMacros.fs index b851bbd8b..447c2ad9a 100644 --- a/CommonTypes/AbstractMacros.fs +++ b/CommonTypes/AbstractMacros.fs @@ -67,15 +67,15 @@ Generated by the C stg macros with the following command abstract member Define_new_bit_string_named_bit : td:FE_SizeableTypeDefinition -> sTargetLangBitName:string -> sHexValue:string -> sComment:string -> string; abstract member Define_new_bit_string : td:FE_SizeableTypeDefinition -> nMin:BigInteger -> nMax:BigInteger -> bFixedSize:bool -> nMaxOctets:BigInteger -> arrsNamedBits:seq -> string; abstract member Define_subType_bit_string : td:FE_SizeableTypeDefinition -> prTd:FE_SizeableTypeDefinition -> soParentTypePackage:string option -> bFixedSize:bool -> string; - abstract member Define_new_sequence_of : td:FE_SizeableTypeDefinition -> nMin:BigInteger -> nMax:BigInteger -> bFixedSize:bool -> sChildType:string -> soChildDefintion:string option -> string; - abstract member Define_subType_sequence_of : td:FE_SizeableTypeDefinition -> prTd:FE_SizeableTypeDefinition -> soParentTypePackage:string option -> bFixedSize:bool -> soChildDefintion:string option -> string; + abstract member Define_new_sequence_of : td:FE_SizeableTypeDefinition -> nMin:BigInteger -> nMax:BigInteger -> bFixedSize:bool -> sChildType:string -> soChildDefinition:string option -> string; + abstract member Define_subType_sequence_of : td:FE_SizeableTypeDefinition -> prTd:FE_SizeableTypeDefinition -> soParentTypePackage:string option -> bFixedSize:bool -> soChildDefinition:string option -> string; abstract member Define_new_sequence_child_bit : sName:string -> string; - abstract member Define_new_sequence_child : sName:string -> sType:string -> string; + abstract member Define_new_sequence_child : sName:string -> sType:string -> bIsOptional:bool -> string; abstract member Define_new_sequence_save_pos_child : td:FE_SequenceTypeDefinition -> sName:string -> nMaxBytesInACN:BigInteger -> string; - abstract member Define_new_sequence : td:FE_SequenceTypeDefinition -> arrsChildren:seq -> arrsOptionalChildren:seq -> arrsChildldrenDefintions:seq -> arrsNullFieldsSavePos:seq -> string; + abstract member Define_new_sequence : td:FE_SequenceTypeDefinition -> arrsChildren:seq -> arrsOptionalChildren:seq -> arrsChildrenDefinitions:seq -> arrsNullFieldsSavePos:seq -> string; abstract member Define_subType_sequence : td:FE_SequenceTypeDefinition -> prTd:FE_SequenceTypeDefinition -> soParentTypePackage:string option -> arrsOptionalChildren:seq -> string; abstract member Define_new_choice_child : sName:string -> sType:string -> sPresent:string -> string; - abstract member Define_new_choice : td:FE_ChoiceTypeDefinition -> sChoiceIDForNone:string -> sFirstChildNamePresent:string -> arrsChildren:seq -> arrsPresent:seq -> arrsCombined:seq -> nIndexMax:BigInteger -> arrsChildldrenDefintions:seq -> string; + abstract member Define_new_choice : td:FE_ChoiceTypeDefinition -> sChoiceIDForNone:string -> sFirstChildNamePresent:string -> arrsChildren:seq -> arrsPresent:seq -> arrsCombined:seq -> nIndexMax:BigInteger -> arrsChildrenDefinitions:seq -> string; abstract member Define_subType_choice : td:FE_ChoiceTypeDefinition -> prTd:FE_ChoiceTypeDefinition -> soParentTypePackage:string option -> string; abstract member Define_SubType_int_range : soParentTypePackage:string option -> sParentType:string -> noMin:BigInteger option -> noMax:BigInteger option -> string; @@ -105,9 +105,9 @@ Generated by the C stg macros with the following command abstract member PrintNullValue : unit -> string; abstract member PrintOctetStringValue : td:FE_SizeableTypeDefinition -> bIsFixedSize:bool -> arruBytes:seq -> nCount:BigInteger -> string; abstract member PrintBitStringValue : td:FE_SizeableTypeDefinition -> bIsFixedSize:bool -> arrsBits:seq -> nCount:BigInteger -> arruBytes:seq -> nBytesCount:BigInteger -> string; - abstract member PrintBitOrOctetStringValueAsCompoundLitteral : td:FE_SizeableTypeDefinition -> bIsFixedSize:bool -> arruBytes:seq -> nCount:BigInteger -> string; - abstract member PrintOctetArrayAsCompoundLitteral : arruBytes:seq -> string; - abstract member PrintBitArrayAsCompoundLitteral : arruBits:seq -> string; + abstract member PrintBitOrOctetStringValueAsCompoundLiteral : td:FE_SizeableTypeDefinition -> bIsFixedSize:bool -> arruBytes:seq -> nCount:BigInteger -> string; + abstract member PrintOctetArrayAsCompoundLiteral : arruBytes:seq -> string; + abstract member PrintBitArrayAsCompoundLiteral : arruBits:seq -> string; abstract member PrintObjectIdentifierValue : td:FE_PrimitiveTypeDefinition -> arrnValues:seq -> nCount:BigInteger -> string; abstract member PrintObjectIdentifierValueAsCompoundLiteral : arrnValues:seq -> nCount:BigInteger -> string; abstract member PrintTimeValueAsCompoundLiteral_Asn1LocalTime : td:FE_PrimitiveTypeDefinition -> tv:Asn1TimeValue -> string; @@ -137,8 +137,8 @@ Generated by the C stg macros with the following command abstract member JoinItems : sPart:string -> soNestedPart:string option -> string; abstract member JoinItems2_ret : sPart:string -> sNestedPart:string -> string; abstract member JoinItems2_ret_result : sPart:string -> sNestedPart:string -> string; - abstract member PrintEqualDefintionPrimitive : sFuncName:string -> sTypeDefName:string -> string; - abstract member PrintEqualDefintionComposite : sFuncName:string -> sTypeDefName:string -> string; + abstract member PrintEqualDefinitionPrimitive : sFuncName:string -> sTypeDefName:string -> string; + abstract member PrintEqualDefinitionComposite : sFuncName:string -> sTypeDefName:string -> string; abstract member PrintEqualPrimitive : sFuncName:string -> sTypeDefName:string -> sContent:string -> string; abstract member PrintEqualComposite : sFuncName:string -> sTypeDefName:string -> sContent:string -> arrsLocalVars:seq -> string; abstract member equalTypeAssignment_def : sVarName1:string -> sVarName2:string -> sStar:string -> sFuncName:string -> sTypeDefName:string -> string; @@ -149,7 +149,7 @@ Generated by the C stg macros with the following command abstract member isEqual_BitString : p1:string -> p2:string -> bIsFixedSize:bool -> nFixedSize:BigInteger -> string; abstract member isEqual_OctetString : p1:string -> p2:string -> bIsFixedSize:bool -> nFixedSize:BigInteger -> string; abstract member isObjectIdentifier_equal : p1:string -> p2:string -> string; - abstract member isEqual_Choice_Child : choiceTypeDefName:Object -> sCid:string -> sInnerStatement:string -> sTmpVarName1:string -> sTmpVarName2:string -> string; + abstract member isEqual_Choice_Child : sChoiceTypeDefName:string -> sCid:string -> sInnerStatement:string -> sTmpVarName1:string -> sTmpVarName2:string -> string; abstract member isEqual_Choice : p1:string -> p2:string -> sAccess:string -> arrsChildren:seq -> string; abstract member isEqual_Sequence_child : p1:string -> p2:string -> sAcc:string -> bIsOptional:bool -> sChName:string -> soInnerStatement:string option -> string; abstract member isEqual_SequenceOf_var_size : p1:string -> p2:string -> sAcc:string -> i:string -> soInnerStatement:string option -> string; @@ -162,7 +162,6 @@ Generated by the C stg macros with the following command [] type IIsValid () = abstract member rtlModuleName : unit -> string; - abstract member getStringSize : p:string -> string; abstract member JoinItems : sPart:string -> soNestedPart:string option -> string; abstract member JoinTwoIfFirstOk : sStr1:string -> sStr2:string -> string; abstract member JoinItems2 : sPart:string -> sNestedPart:string -> string; @@ -184,28 +183,28 @@ Generated by the C stg macros with the following command abstract member ExpLte : sExp1:string -> sExp2:string -> string; abstract member ExpOr : sExp1:string -> sExp2:string -> string; abstract member ExpAnd : sExp1:string -> sExp2:string -> string; - abstract member ExpAndMulit : arrsExp:seq -> string; + abstract member ExpAndMulti : arrsExp:seq -> string; abstract member ExpNot : sExp:string -> string; abstract member StrLen : sExp:string -> string; abstract member ArrayLen : sExp:string -> sAcc:string -> string; - abstract member ExpressionToStament : sExp1:string -> string; - abstract member StatementOrStament : sStat1:string -> sStat2:string -> string; - abstract member ExpressionOrStament : sExp1:string -> sStat2:string -> string; + abstract member ExpressionToStatement : sExp1:string -> string; + abstract member StatementOrStatement : sStat1:string -> sStat2:string -> string; + abstract member ExpressionOrStatement : sExp1:string -> sStat2:string -> string; abstract member StatementOrExpression : sStat1:string -> sExp2:string -> string; - abstract member StatementAndStament : sStat1:string -> sStat2:string -> string; - abstract member ExpressionAndStament : sExp1:string -> sStat2:string -> string; + abstract member StatementAndStatement : sStat1:string -> sStat2:string -> string; + abstract member ExpressionAndStatement : sExp1:string -> sStat2:string -> string; abstract member StatementAndExpression : sStat1:string -> sExp2:string -> string; abstract member StatementNot : sStat:string -> string; - abstract member StatementExceptStament : sStat1:string -> sStat2:string -> string; - abstract member ExpressionExceptStament : sExp1:string -> sStat2:string -> string; + abstract member StatementExceptStatement : sStat1:string -> sStat2:string -> string; + abstract member ExpressionExceptStatement : sExp1:string -> sStat2:string -> string; abstract member StatementExceptExpression : sStat1:string -> sExp2:string -> string; abstract member StatementForLoop : p:string -> sAcc:string -> i:string -> bIsFixedSize:bool -> nFixedSize:BigInteger -> sInnerStatement:string -> string; abstract member Print_AlphabetCheckFunc : sFuncName:string -> arrsAlphaConBody:seq -> string; - abstract member SingleValContraint : p:string -> v:string -> string; + abstract member SingleValConstraint : p:string -> v:string -> string; abstract member stringContainsChar : sStrVal:string -> p:string -> string; - abstract member RangeContraint : p:string -> v1:string -> v2:string -> bMin:bool -> bMax:bool -> string; - abstract member RangeContraint_val_MAX : p:string -> v:string -> bMin:bool -> string; - abstract member RangeContraint_MIN_val : p:string -> v:string -> bMax:bool -> string; + abstract member RangeConstraint : p:string -> v1:string -> v2:string -> bMin:bool -> bMax:bool -> string; + abstract member RangeConstraint_val_MAX : p:string -> v:string -> bMin:bool -> string; + abstract member RangeConstraint_MIN_val : p:string -> v:string -> bMax:bool -> string; abstract member AND_Constraint : sCon1:string -> sCon2:string -> string; abstract member OR_Constraint : sCon1:string -> sCon2:string -> string; abstract member AllExceptConstraint : sCon:string -> string; @@ -218,7 +217,7 @@ Generated by the C stg macros with the following command abstract member Sequence_OptionalChild : p:string -> sAcc:string -> sChName:string -> sInnerStatement:string -> string; abstract member Sequence_optional_child_always_present_or_absent : p:string -> sAcc:string -> sChName:string -> sErrCode:string -> sPresOrAbs:string -> string; abstract member Sequence_optional_child_always_present_or_absent_expr : p:string -> sAcc:string -> sChName:string -> sPresOrAbs:string -> string; - abstract member Choice_OptionalChild : p:string -> pLocal:Object -> sAcc:string -> sChPresent:string -> sInnerStatement:string -> string; + abstract member Choice_OptionalChild : p:string -> sPLocal:string -> sAcc:string -> sChPresent:string -> sInnerStatement:string -> string; abstract member Choice_child_always_present_Exp : p:string -> sAcc:string -> sChPresent:string -> string; abstract member Choice_child_always_absent_Exp : p:string -> sAcc:string -> sChPresent:string -> string; abstract member choice_child : sChPresent:string -> sChildBody:string -> bAlwaysAbsent:bool -> string; @@ -241,7 +240,7 @@ Generated by the C stg macros with the following command abstract member initInteger : sVal:string -> nValue:BigInteger -> string; abstract member initReal : sVal:string -> dValue:double -> string; abstract member initBoolean : sVal:string -> bValue:bool -> string; - abstract member initObjectIdentifier_vali : p:string -> sAcc:string -> sI:string -> nIntVal:BigInteger -> string; + abstract member initObjectIdentifier_valid : p:string -> sAcc:string -> sI:string -> nIntVal:BigInteger -> string; abstract member initObjectIdentifier : p:string -> sAcc:string -> nSize:BigInteger -> arrsValues:seq -> string; abstract member init_Asn1LocalTime : p:string -> sAcc:string -> tv:Asn1TimeValue -> string; abstract member init_Asn1UtcTime : p:string -> sAcc:string -> tv:Asn1TimeValue -> string; @@ -279,12 +278,12 @@ Generated by the C stg macros with the following command abstract member initBitStringAtPos_def : sVarName:string -> sStar:string -> sFuncName:string -> sTypeDefName:string -> sNamedBit:string -> string; abstract member initTypeConstant_def : sTypeDecl:string -> sConstantName:string -> sValue:string -> string; abstract member initTypeConstant_body : sTypeDecl:string -> sConstantName:string -> sValue:string -> string; - abstract member initFixSizeOctetString : nMax:BigInteger -> bZeroSizedArray:bool -> string; - abstract member initVarSizeOctetString : nMin:BigInteger -> nMax:BigInteger -> string; - abstract member initFixSizeBitString : nMax:BigInteger -> nMaxOctets:BigInteger -> string; - abstract member initVarSizeBitString : nMin:BigInteger -> nMax:BigInteger -> nMaxOctets:BigInteger -> string; - abstract member initFixSizeSequenceOfExpr : nMax:BigInteger -> sChildExp:string -> string; - abstract member initVarSizeSequenceOfExpr : nMin:BigInteger -> nMax:BigInteger -> sChildExp:string -> string; + abstract member initFixSizeOctetString : sTypeDefName:string -> nMax:BigInteger -> bZeroSizedArray:bool -> string; + abstract member initVarSizeOctetString : sTypeDefName:string -> nMin:BigInteger -> nMax:BigInteger -> string; + abstract member initFixSizeBitString : sTypeDefName:string -> nMax:BigInteger -> nMaxOctets:BigInteger -> string; + abstract member initVarSizeBitString : sTypeDefName:string -> nMin:BigInteger -> nMax:BigInteger -> nMaxOctets:BigInteger -> string; + abstract member initFixSizeSequenceOfExpr : sTypeDefName:string -> nMax:BigInteger -> sChildExp:string -> string; + abstract member initVarSizeSequenceOfExpr : sTypeDefName:string -> nMin:BigInteger -> nMax:BigInteger -> sChildExp:string -> string; abstract member initObjectIdentifierAsExpr : unit -> string; abstract member init_Asn1LocalTimeExpr : unit -> string; abstract member init_Asn1UtcTimeExpr : unit -> string; @@ -293,9 +292,9 @@ Generated by the C stg macros with the following command abstract member init_Asn1Date_LocalTimeExpr : unit -> string; abstract member init_Asn1Date_UtcTimeExpr : unit -> string; abstract member init_Asn1Date_LocalTimeWithTimeZoneExpr : unit -> string; - abstract member initSequenceChildExpr : sChildName:string -> sChildExpr:string -> string; + abstract member initSequenceChildExpr : sChildName:string -> sChildExpr:string -> bIsOptional:bool -> string; abstract member initSequenceOptionalChildExpr : sChildName:string -> nPresenceBit:BigInteger -> string; - abstract member initSequenceExpr : arrsChildren:seq -> arrsOptionalChildren:seq -> string; + abstract member initSequenceExpr : sTypeDefName:string -> sTypeDefNameExist:string -> arrsChildren:seq -> arrsOptionalChildren:seq -> string; abstract member initChoiceExpr : sChildName:string -> sChildKind:string -> sChildExpr:string -> string; @@ -305,14 +304,14 @@ Generated by the C stg macros with the following command abstract member call_base_type_func : p:string -> sFuncName:string -> codec:Codec -> string; abstract member EmitTypeAssignment_def_err_code : sErrCode:string -> nErrValue:BigInteger -> string; abstract member EmitTypeAssignment_def : sVarName:string -> sStar:string -> sFuncName:string -> sTypeDefName:string -> arrsErrcodes:seq -> bEmptyEncodingSpace:bool -> nMaxBytesInPER:BigInteger -> nMaxBitsInPER:BigInteger -> soSparkAnnotations:string option -> bReqBytesForEncodingIsZero:bool -> codec:Codec -> string; - abstract member EmitTypeAssignment : sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitilialExp:string -> bReqBytesForEncodingIsZero:bool -> bBsIsUnreferenced:bool -> bVarNameIsUnreferenced:bool -> soInitFuncName:string option -> codec:Codec -> string; + abstract member EmitTypeAssignment : sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitialExp:string -> bReqBytesForEncodingIsZero:bool -> bBsIsUnreferenced:bool -> bVarNameIsUnreferenced:bool -> soInitFuncName:string option -> codec:Codec -> string; abstract member InternalItem_oct_str : p:string -> sAcc:string -> i:string -> sErrCode:string -> codec:Codec -> string; abstract member InternalItem_string_with_alpha : p:string -> sErrCode:string -> td:FE_StringTypeDefinition -> i:string -> nLastItemIndex:BigInteger -> arrnAlphabetAsciiCodes:seq -> nAlphabetLength:BigInteger -> nCharIndexSize:BigInteger -> codec:Codec -> string; abstract member InternalItem_string_no_alpha : p:string -> sErrCode:string -> i:string -> codec:Codec -> string; abstract member IntFullyConstraint : p:string -> nMin:BigInteger -> nMax:BigInteger -> nBits:BigInteger -> sSsuffix:string -> sErrCode:string -> codec:Codec -> string; abstract member IntFullyConstraintPos : p:string -> nMin:BigInteger -> nMax:BigInteger -> nBits:BigInteger -> sSsuffix:string -> sErrCode:string -> codec:Codec -> string; - abstract member IntUnconstraint : p:string -> sErrCode:string -> bCoverageIgnore:bool -> codec:Codec -> string; - abstract member IntUnconstraintMax : p:string -> nMax:BigInteger -> soCheckExp:string option -> sErrCode:string -> codec:Codec -> string; + abstract member IntUnconstrained : p:string -> sErrCode:string -> bCoverageIgnore:bool -> codec:Codec -> string; + abstract member IntUnconstrainedMax : p:string -> nMax:BigInteger -> soCheckExp:string option -> sErrCode:string -> codec:Codec -> string; abstract member IntSemiConstraint : p:string -> nMin:BigInteger -> sErrCode:string -> codec:Codec -> string; abstract member IntSemiConstraintPos : p:string -> nMin:BigInteger -> sErrCode:string -> codec:Codec -> string; abstract member IntNoneRequired : p:string -> nConst:BigInteger -> sErrCode:string -> codec:Codec -> string; @@ -327,19 +326,20 @@ Generated by the C stg macros with the following command abstract member Enumerated : p:string -> td:FE_EnumeratedTypeDefinition -> arrsItem:seq -> nMin:BigInteger -> nMax:BigInteger -> nBits:BigInteger -> sErrCode:string -> nLastItemIndex:BigInteger -> sFirstItemName:string -> codec:Codec -> string; abstract member choice_child : p:string -> sAcc:string -> sChildID:string -> nChildIndex:BigInteger -> nIndexSizeInBits:BigInteger -> nLastItemIndex:BigInteger -> sChildContent:string -> sChildName:string -> sChildTypeDef:string -> sChoiceTypeName:string -> sChildInitExpr:string -> bIsSequence:bool -> bIsEnum:bool -> codec:Codec -> string; abstract member choice : p:string -> sAcc:string -> arrsChildren:seq -> nLastItemIndex:BigInteger -> sChoiceIndexName:string -> sErrCode:string -> td:FE_ChoiceTypeDefinition -> nIndexSizeInBits:BigInteger -> codec:Codec -> string; - abstract member sequence_presence_bit : p:string -> sAcc:string -> sChName:string -> sErrCode:string -> codec:Codec -> string; - abstract member sequence_presence_bit_fix : p:string -> sAcc:string -> sChName:string -> sErrCode:string -> sVal:string -> codec:Codec -> string; + abstract member sequence_presence_bit : p:string -> sAcc:string -> sChName:string -> soExistVar:string option -> sErrCode:string -> codec:Codec -> string; + abstract member sequence_presence_bit_fix : p:string -> sAcc:string -> sChName:string -> soExistVar:string option -> sErrCode:string -> sVal:string -> codec:Codec -> string; abstract member sequence_mandatory_child : sChName:string -> sChildContent:string -> codec:Codec -> string; - abstract member sequence_optional_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> codec:Codec -> string; - abstract member sequence_default_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> sInitWithDefaultValue:string -> codec:Codec -> string; - abstract member str_FixedSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nFixedSize:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> codec:Codec -> string; - abstract member str_VarSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> codec:Codec -> string; - abstract member seqOf_FixedSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nFixedSize:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> codec:Codec -> string; - abstract member seqOf_VarSize : p:string -> sAcc:string -> sTasName:string -> i:string -> sInternalItem:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> sErrCode:string -> codec:Codec -> string; - abstract member octect_FixedSize : p:string -> sAcc:string -> nFixedSize:BigInteger -> codec:Codec -> string; - abstract member octect_VarSize : p:string -> sAcc:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> sErrCode:string -> codec:Codec -> string; - abstract member bitString_FixSize : p:string -> sAcc:string -> nFixedSize:BigInteger -> sErrCode:string -> codec:Codec -> string; - abstract member bitString_VarSize : p:string -> sAcc:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> sErrCode:string -> nSizeInBits:BigInteger -> codec:Codec -> string; + abstract member sequence_optional_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soExistVar:string option -> soChildExpr:string option -> sChildTypedef:string -> codec:Codec -> string; + abstract member sequence_default_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soExistVar:string option -> soChildExpr:string option -> sChildTypedef:string -> sInitWithDefaultValue:string -> codec:Codec -> string; + abstract member sequence_build : p:string -> sTypeDefName:string -> arrsChildren:seq -> string; + abstract member str_FixedSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nFixedSize:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> soInitExpr:string option -> codec:Codec -> string; + abstract member str_VarSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> soInitExpr:string option -> codec:Codec -> string; + abstract member seqOf_FixedSize : p:string -> sTasName:string -> i:string -> sInternalItem:string -> nFixedSize:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> sChildInitExpr:string -> codec:Codec -> string; + abstract member seqOf_VarSize : p:string -> sAcc:string -> sTasName:string -> i:string -> sInternalItem:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> nAlignSize:BigInteger -> sChildInitExpr:string -> sErrCode:string -> codec:Codec -> string; + abstract member octet_FixedSize : sTypeDefName:string -> p:string -> sAcc:string -> nFixedSize:BigInteger -> codec:Codec -> string; + abstract member octet_VarSize : sTypeDefName:string -> p:string -> sAcc:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> nSizeInBits:BigInteger -> sErrCode:string -> codec:Codec -> string; + abstract member bitString_FixSize : sTypeDefName:string -> p:string -> sAcc:string -> nFixedSize:BigInteger -> sErrCode:string -> codec:Codec -> string; + abstract member bitString_VarSize : sTypeDefName:string -> p:string -> sAcc:string -> nSizeMin:BigInteger -> nSizeMax:BigInteger -> sErrCode:string -> nSizeInBits:BigInteger -> codec:Codec -> string; abstract member FixedSize_Fragmentation_sqf_64K : p:string -> sAcc:string -> sCurOffset:string -> sCurBlockSize:string -> sBlockIndex:string -> nBlocks64K:BigInteger -> sInternalItem:string -> sBLI:string -> sRemainingItemsVar:string -> bIsBitStringType:bool -> sErrCodeName:string -> codec:Codec -> string; abstract member FixedSize_Fragmentation_sqf_small_block : p:string -> sAcc:string -> sInternalItem:string -> nBlockSize:BigInteger -> sBlockId:string -> sCurOffset:string -> sCurBlockSize:string -> sBLI:string -> sRemainingItemsVar:string -> bIsBitStringType:bool -> sErrCodeName:string -> codec:Codec -> string; abstract member FixedSize_Fragmentation_sqf_remaining : p:string -> sAcc:string -> sInternalItem:string -> bRemainingItemsWithinByte:bool -> nRemainingItemsVar:BigInteger -> sCurOffset:string -> sBLI:string -> sRemainingItemsVar:string -> bIsBitStringType:bool -> sErrCodeName:string -> codec:Codec -> string; @@ -348,6 +348,7 @@ Generated by the C stg macros with the following command abstract member octet_string_containing_func : p:string -> sFuncName:string -> sReqBytesForUperEncoding:string -> nBits:BigInteger -> nMinSize:BigInteger -> nMaxSize:BigInteger -> codec:Codec -> string; abstract member bit_string_containing_func : p:string -> sFuncName:string -> sReqBytesForUperEncoding:string -> sReqBitsForUperEncoding:string -> nBits:BigInteger -> nMinSize:BigInteger -> nMaxSize:BigInteger -> codec:Codec -> string; abstract member sparkAnnotations : sTypeDefName:string -> codec:Codec -> string; + abstract member Null_declare : p:string -> string; abstract member decode_nullType : p:string -> string; abstract member decode_empty_sequence_emptySeq : p:string -> string; abstract member JoinItems : sPart:string -> soNestedPart:string option -> string; @@ -361,8 +362,8 @@ Generated by the C stg macros with the following command abstract member EmitTypeAssignment_def_err_code : sErrCode:string -> nErrValue:BigInteger -> soErrorCodeComment:string option -> string; abstract member EmitAcnParameter : sName:string -> sType:string -> string; abstract member EmitTypeAssignment_primitive_def : sVarName:string -> sStar:string -> sFuncName:string -> sTypeDefName:string -> arrsErrcodes:seq -> bEmptyEncodingSpace:bool -> nMaxBytesInACN:BigInteger -> nMaxBitsInACN:BigInteger -> arrsAcnPrms:seq -> soSparkAnnotations:string option -> codec:Codec -> string; - abstract member EmitTypeAssignment_primitive : sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitilialExp:string -> arrsAcnPrms:seq -> arrsAcnParamNames:seq -> bEmptyEncodingSpace:bool -> bBsIsUnreferenced:bool -> bVarNameIsUnreferenced:bool -> soInitFuncName:string option -> codec:Codec -> string; - abstract member alignToNext : sMainBody:string -> sAligmentValue:string -> nAligmentValue:BigInteger -> codec:Codec -> string; + abstract member EmitTypeAssignment_primitive : sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitialExp:string -> arrsAcnPrms:seq -> arrsAcnParamNames:seq -> bEmptyEncodingSpace:bool -> bBsIsUnreferenced:bool -> bVarNameIsUnreferenced:bool -> soInitFuncName:string option -> codec:Codec -> string; + abstract member alignToNext : sMainBody:string -> sAlignmentValue:string -> nAlignmentValue:BigInteger -> codec:Codec -> string; abstract member PositiveInteger_ConstSize : p:string -> sSsuffix:string -> sErrCode:string -> nFixedSize:BigInteger -> soMF:string option -> soMFM:string option -> nUperMin:BigInteger -> nUperMax:BigInteger -> codec:Codec -> string; abstract member PositiveInteger_ConstSize_8 : p:string -> sSsuffix:string -> sErrCode:string -> soMF:string option -> soMFM:string option -> nUperMin:BigInteger -> nUperMax:BigInteger -> codec:Codec -> string; abstract member PositiveInteger_ConstSize_big_endian_16 : p:string -> sSsuffix:string -> sErrCode:string -> soMF:string option -> soMFM:string option -> nUperMin:BigInteger -> nUperMax:BigInteger -> codec:Codec -> string; @@ -394,42 +395,42 @@ Generated by the C stg macros with the following command abstract member Real_32_little_endian : p:string -> sSuffix:string -> sErrCode:string -> codec:Codec -> string; abstract member Real_64_little_endian : p:string -> sErrCode:string -> codec:Codec -> string; abstract member Boolean : p:string -> ptr:string -> bEncValIsTrue:bool -> nSize:BigInteger -> arruTrueValueAsByteArray:seq -> arruFalseValueAsByteArray:seq -> arrsBits:seq -> sErrCode:string -> codec:Codec -> string; + abstract member Null_declare : p:string -> string; abstract member Null_pattern : p:string -> arruNullValueAsByteArray:seq -> nSize:BigInteger -> arrsBits:seq -> sErrCode:string -> bSavePosition:bool -> codec:Codec -> string; abstract member Null_pattern2 : p:string -> arruNullValueAsByteArray:seq -> nSize:BigInteger -> arrsBits:seq -> sErrCode:string -> bSavePosition:bool -> codec:Codec -> string; abstract member Enumerated_item : p:string -> sName:string -> sEnumHolder:string -> nItemIdxOrVal:BigInteger -> sIntVal:string -> codec:Codec -> string; abstract member EnumeratedEncIdx : p:string -> td:FE_EnumeratedTypeDefinition -> arrsItem:seq -> sActualCodecFunc:string -> sIntVal:string -> codec:Codec -> string; abstract member EnumeratedEncValues : p:string -> td:FE_EnumeratedTypeDefinition -> arrsItem:seq -> sActualCodecFunc:string -> sErrCode:string -> sFirstItemName:string -> sIntVal:string -> codec:Codec -> string; abstract member Acn_String_Ascii_FixSize : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> codec:Codec -> string; - abstract member Acn_String_Ascii_Null_Teminated : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> arruNullBytes:seq -> codec:Codec -> string; + abstract member Acn_String_Ascii_Null_Terminated : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> arruNullBytes:seq -> codec:Codec -> string; abstract member Acn_String_Ascii_External_Field_Determinant : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> sExtFld:string -> codec:Codec -> string; abstract member Acn_String_Ascii_Internal_Field_Determinant : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> nAsn1Min:BigInteger -> nInternalLengthDeterminantSizeInBits:BigInteger -> codec:Codec -> string; abstract member Acn_String_CharIndex_FixSize : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> arrnAlphabetAsciiCodes:seq -> nCharSetSize:BigInteger -> td:FE_StringTypeDefinition -> nCharSize:BigInteger -> codec:Codec -> string; abstract member Acn_String_CharIndex_External_Field_Determinant : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> arrnAlphabetAsciiCodes:seq -> nCharSetSize:BigInteger -> sExtFld:string -> td:FE_StringTypeDefinition -> nCharSize:BigInteger -> codec:Codec -> string; abstract member Acn_IA5String_CharIndex_External_Field_Determinant : p:string -> sErrCode:string -> nAsn1Max:BigInteger -> sExtFld:string -> td:FE_StringTypeDefinition -> nCharSize:BigInteger -> codec:Codec -> string; - abstract member oct_external_field : p:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> codec:Codec -> string; - abstract member oct_external_field_fix_size : p:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> codec:Codec -> string; - abstract member sqf_external_field : p:string -> sAcc:string -> i:string -> sInternalItem:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> codec:Codec -> string; - abstract member sqf_external_field_fix_size : p:string -> sAcc:string -> i:string -> sInternalItem:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> codec:Codec -> string; + abstract member oct_external_field : sTypedefName:string -> p:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> codec:Codec -> string; + abstract member oct_external_field_fix_size : sTypedefName:string -> p:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> codec:Codec -> string; + abstract member sqf_external_field : sTypeDefName:string -> p:string -> sAcc:string -> i:string -> sInternalItem:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> sChildInitExpr:string -> codec:Codec -> string; + abstract member sqf_external_field_fix_size : sTypeDefName:string -> p:string -> sAcc:string -> i:string -> sInternalItem:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> nAlignSize:BigInteger -> sErrCode:string -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> sChildInitExpr:string -> codec:Codec -> string; abstract member oct_sqf_null_terminated : p:string -> sAcc:string -> i:string -> sInternalItem:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> arruNullBytes:seq -> nBitPatternLength:BigInteger -> sErrCode:string -> nIntItemMinSize:BigInteger -> nIntItemMaxSize:BigInteger -> codec:Codec -> string; - abstract member bit_string_external_field : p:string -> sErrCode:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> codec:Codec -> string; - abstract member bit_string_external_field_fixed_size : p:string -> sErrCode:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> codec:Codec -> string; - abstract member bit_string_null_terminated : p:string -> sErrCode:string -> sAcc:string -> i:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> arruNullBytes:seq -> nBitPatternLength:BigInteger -> codec:Codec -> string; + abstract member bit_string_external_field : sTypeDefName:string -> p:string -> sErrCode:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> codec:Codec -> string; + abstract member bit_string_external_field_fixed_size : sTypeDefName:string -> p:string -> sErrCode:string -> sAcc:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> sExtFld:string -> codec:Codec -> string; + abstract member bit_string_null_terminated : sTypeDefName:string -> p:string -> sErrCode:string -> sAcc:string -> i:string -> noSizeMin:BigInteger option -> nSizeMax:BigInteger -> arruNullBytes:seq -> nBitPatternLength:BigInteger -> codec:Codec -> string; abstract member RefTypeParam_tmpVar : sName:string -> sTypeDecl:string -> string; abstract member ReferenceType1 : p:string -> sName:string -> bAcnEncodeFuncRequiresResult:bool -> arrsArgs:seq -> arrsLocalPrms:seq -> codec:Codec -> string; - abstract member sequence_presense_optChild : p:string -> sAcc:string -> sChName:string -> sErrCode:string -> codec:Codec -> string; - abstract member sequence_presense_optChild_pres_acn_expression : p:string -> sAcc:string -> sChName:string -> sAcnExpression:string -> sErrCode:string -> codec:Codec -> string; - abstract member sequence_presense_optChild_pres_bool : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> codec:Codec -> string; - abstract member sequence_presense_optChild_pres_int : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> nIntVal:BigInteger -> codec:Codec -> string; - abstract member sequence_presense_optChild_pres_str : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> sVal:string -> codec:Codec -> string; + abstract member sequence_presence_optChild : p:string -> sAcc:string -> sChName:string -> soExistVar:string option -> sErrCode:string -> codec:Codec -> string; + abstract member sequence_presence_optChild_pres_acn_expression : p:string -> sAcc:string -> sChName:string -> sAcnExpression:string -> soExistVar:string option -> sErrCode:string -> codec:Codec -> string; + abstract member sequence_presence_optChild_pres_bool : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> codec:Codec -> string; + abstract member sequence_presence_optChild_pres_int : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> nIntVal:BigInteger -> codec:Codec -> string; + abstract member sequence_presence_optChild_pres_str : p:string -> sAcc:string -> sChName:string -> sExtFldName:string -> sVal:string -> codec:Codec -> string; abstract member sequence_save_bitStream_start : sBitStreamPositionsLocalVar:string -> codec:Codec -> string; abstract member sequence_save_bitstream : sBitStreamPositionsLocalVar:string -> sChName:string -> codec:Codec -> string; abstract member sequence_acn_child : sChName:string -> sChildContent:string -> sErrCode:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; abstract member sequence_mandatory_child : sChName:string -> sChildContent:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; - abstract member sequence_always_present_child : p:string -> sAcc:string -> sChName:string -> soChildContent:string option -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; - abstract member sequence_always_absent_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; - abstract member sequence_optional_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; - abstract member sequence_optional_always_present_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; - abstract member sequence_default_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> sInitWithDefaultValue:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; + abstract member sequence_always_present_child : p:string -> sAcc:string -> sChName:string -> soChildContent:string option -> soChildExpr:string option -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; + abstract member sequence_always_absent_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> sChildTypedef:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; + abstract member sequence_optional_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> soExistVar:string option -> soChildExpr:string option -> sChildTypedef:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; + abstract member sequence_default_child : p:string -> sAcc:string -> sChName:string -> sChildContent:string -> sInitWithDefaultValue:string -> soExistVar:string option -> soChildExpr:string option -> sChildTypedef:string -> soSaveBitStrmPosStatement:string option -> codec:Codec -> string; abstract member sequence_call_post_encoding_function : p:string -> sFncName:string -> sBitStreamStartPos:string -> sBitStreamPositionsNullPos:string -> string; abstract member sequence_call_post_decoding_validator : p:string -> sFncName:string -> sBitStreamStartPos:string -> sBitStreamPositionsNullPos:string -> string; abstract member ChoiceChildAlwaysAbsent : p:string -> sAcc:string -> sChildID:string -> nChildIndex:BigInteger -> sErrorCodeName:string -> codec:Codec -> string; @@ -444,20 +445,20 @@ Generated by the C stg macros with the following command abstract member Choice_Enum : p:string -> sAcc:string -> arrsChildren:seq -> sEnmExtFld:string -> sErrCode:string -> codec:Codec -> string; abstract member SizeDependency : v:string -> sCount:string -> nMin:BigInteger -> nMax:BigInteger -> bCheckRange:bool -> sTypedefName:string -> string; abstract member SizeDependencyFixedSize : v:string -> nFixedSize:BigInteger -> string; - abstract member ChoiceDependencyEnum_Item : v:string -> sChildCID:string -> sChildCIDHolder:string -> sEnumCName:string -> string; - abstract member ChoiceDependencyEnum : sChPath:string -> sAcc:string -> arrsChoiceEnumItems:seq -> string; + abstract member ChoiceDependencyEnum_Item : v:string -> sChildCID:string -> sChildCIDHolder:string -> sEnumCName:string -> bIsOptional:bool -> string; + abstract member ChoiceDependencyEnum : sV:string -> sChPath:string -> sAcc:string -> arrsChoiceEnumItems:seq -> bIsOptional:bool -> sDefaultExpr:string -> string; abstract member PresenceDependency : v:string -> sSeqPath:string -> sAcc:string -> sChildName:string -> string; abstract member ChoiceDependencyIntPres_child : v:string -> sChildNamePrese:string -> nChildRetVal:BigInteger -> string; abstract member ChoiceDependencyStrPres_child : v:string -> sChildNamePrese:string -> sChildRetVal:string -> arrsNullChars:seq -> string; - abstract member ChoiceDependencyPres : sChPath:string -> sAcc:string -> arrsChoiceItems:seq -> string; + abstract member ChoiceDependencyPres : v:string -> sChPath:string -> sAcc:string -> arrsChoiceItems:seq -> string; abstract member MultiAcnUpdate_checkEqual_pri0 : p1:string -> p2:string -> string; abstract member MultiAcnUpdate_checkEqual_str0 : p1:string -> p2:string -> string; - abstract member MultiAcnUpdate_get_first_init_value_pri : sV0:string -> sVi:string -> bIsFirst:bool -> string; - abstract member MultiAcnUpdate_get_first_init_value_str : sV0:string -> sVi:string -> bIsFirst:bool -> string; - abstract member MultiAcnUpdate_checkEqual_pri : sV0:string -> sVi:string -> string; - abstract member MultiAcnUpdate_checkEqual_str : sV0:string -> sVi:string -> string; - abstract member MultiAcnUpdate : v:string -> sV0:string -> sErrCode:string -> arrsLocalDeclarations:seq -> arrsLocalUpdateStatements:seq -> arrsGetFirstIntValue:seq -> arrsLocalCheckEquality:seq -> string; - abstract member checkAccessPath : arrsCheckPaths:seq -> sUpdateStatement:string -> string; + abstract member MultiAcnUpdate_get_first_init_value_pri : sV0:string -> sVi:string -> sChPath:string -> bIsFirst:bool -> bIsSingleElement:bool -> string; + abstract member MultiAcnUpdate_get_first_init_value_str : sV0:string -> sVi:string -> sChPath:string -> bIsFirst:bool -> bIsSingleElement:bool -> string; + abstract member MultiAcnUpdate_checkEqual_pri : sV0:string -> sVi:string -> sChPath:string -> bIsAlwaysInit:bool -> string; + abstract member MultiAcnUpdate_checkEqual_str : sV0:string -> sVi:string -> sChPath:string -> bIsAlwaysInit:bool -> string; + abstract member MultiAcnUpdate : v:string -> sV0:string -> sErrCode:string -> arrsLocalDeclarations:seq -> arrsLocalUpdateStatements:seq -> arrsGetFirstIntValue:seq -> bIsFirstIntValueSingle:bool -> arrsLocalCheckEquality:seq -> sDefaultExpr:string -> string; + abstract member checkAccessPath : arrsCheckPaths:seq -> sUpdateStatement:string -> v:string -> sInitExpr:string -> string; abstract member SizeDependency_oct_str_containing : p:string -> sFuncName:string -> sReqBytesForUperEncoding:string -> v:string -> bIsOctet:bool -> sComment:string -> string; abstract member octet_string_containing_ext_field_func : p:string -> sFuncName:string -> sReqBytesForUperEncoding:string -> sExtField:string -> sErrCode:string -> soInner:string option -> codec:Codec -> string; abstract member bit_string_containing_ext_field_func : p:string -> sFuncName:string -> sReqBytesForUperEncoding:string -> sReqBitsForUperEncoding:string -> sExtField:string -> sErrCode:string -> codec:Codec -> string; @@ -472,7 +473,7 @@ Generated by the C stg macros with the following command abstract member rtlModuleName : unit -> string; abstract member EmitTypeAssignment_def_err_code : sErrCode:string -> nErrValue:BigInteger -> string; abstract member EmitTypeAssignment_def : sVarName:string -> sStar:string -> sFuncName:string -> sTypeDefName:string -> arrsErrcodes:seq -> bEmptyEncodingSpace:bool -> nMaxBytesInXER:BigInteger -> soSparkAnnotations:string option -> codec:Codec -> string; - abstract member EmitTypeAssignment : sTasName:string -> sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitilialExp:string -> codec:Codec -> string; + abstract member EmitTypeAssignment : sTasName:string -> sVarName:string -> sStar:string -> sFuncName:string -> soIValidFuncName:string option -> sTypeDefName:string -> arrsLocalVariables:seq -> sContent:string -> soSparkAnnotations:string option -> sInitialExp:string -> codec:Codec -> string; abstract member Integer : p:string -> sTag:string -> nLevel:BigInteger -> soCheckExp:string option -> sErrCode:string -> codec:Codec -> string; abstract member IntegerPos : p:string -> sTag:string -> nLevel:BigInteger -> soCheckExp:string option -> sErrCode:string -> codec:Codec -> string; abstract member Boolean : p:string -> sTag:string -> nLevel:BigInteger -> soCheckExp:string option -> sErrCode:string -> codec:Codec -> string; diff --git a/CommonTypes/AcnGenericTypes.fs b/CommonTypes/AcnGenericTypes.fs index 755b22a46..63b3a14f7 100644 --- a/CommonTypes/AcnGenericTypes.fs +++ b/CommonTypes/AcnGenericTypes.fs @@ -8,20 +8,20 @@ open CommonTypes open Antlr.Runtime.Tree open Antlr.Runtime -type RelativePath = +type RelativePath = | RelativePath of StringLoc list with - member this.AsString = + member this.AsString = match this with RelativePath p -> p |> Seq.StrJoin "." - member this.location = + member this.location = match this with RelativePath p -> p |> List.map(fun z -> z.Location) |> List.head override this.ToString() = this.AsString type AcnEndianness = | LittleEndianness - | BigEndianness + | BigEndianness -type AcnAligment = +type AcnAlignment = | NextByte | NextWord | NextDWord @@ -41,7 +41,7 @@ type AcnExpression = | MinusUnaryExpression of SrcLoc*AcnExpression | AdditionExpression of SrcLoc*AcnExpression*AcnExpression | SubtractionExpression of SrcLoc*AcnExpression*AcnExpression - | MultipicationExpression of SrcLoc*AcnExpression*AcnExpression + | MultiplicationExpression of SrcLoc*AcnExpression*AcnExpression | DivisionExpression of SrcLoc*AcnExpression*AcnExpression | ModuloExpression of SrcLoc*AcnExpression*AcnExpression | LessThanEqualExpression of SrcLoc*AcnExpression*AcnExpression @@ -54,8 +54,8 @@ type AcnExpression = | OrExpression of SrcLoc*AcnExpression*AcnExpression -let foldAcnExpression intConstFnc acnIntConstFnc realConstFnc boolConstFnc asn1LongFldFnc notUnExpFnc mnUnExpFnc - addFnc subFnc mulFnc divFnc modFnc lteFnc ltFnc gteFnc gtFnc eqFnc neqFnc andFnc orFnc (exp:AcnExpression) (s:'UserState) = +let foldAcnExpression intConstFnc acnIntConstFnc realConstFnc boolConstFnc asn1LongFldFnc notUnExpFnc mnUnExpFnc + addFnc subFnc mulFnc divFnc modFnc lteFnc ltFnc gteFnc gtFnc eqFnc neqFnc andFnc orFnc (exp:AcnExpression) (s:'UserState) = let rec loopExpression (exp:AcnExpression) (s:'UserState) = match exp with | IntegerConstantExp x -> intConstFnc x s @@ -63,61 +63,61 @@ let foldAcnExpression intConstFnc acnIntConstFnc realConstFnc boolConstFnc asn1L | RealConstantExp x -> realConstFnc x s | BooleanConstantExp x -> boolConstFnc x s | Asn1LongField x -> asn1LongFldFnc x s - | NotUnaryExpression (l,e1) -> + | NotUnaryExpression (l,e1) -> let re1, s1 = loopExpression e1 s notUnExpFnc l re1 s1 - | MinusUnaryExpression (l,e1) -> + | MinusUnaryExpression (l,e1) -> let re1, s1 = loopExpression e1 s mnUnExpFnc l re1 s1 - | AdditionExpression (l,e1, e2) -> + | AdditionExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 addFnc l re1 re2 s2 - | SubtractionExpression (l,e1, e2) -> + | SubtractionExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 subFnc l re1 re2 s2 - | MultipicationExpression (l,e1, e2) -> + | MultiplicationExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 mulFnc l re1 re2 s2 - | DivisionExpression (l,e1, e2) -> + | DivisionExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 divFnc l re1 re2 s2 - | ModuloExpression (l,e1, e2) -> + | ModuloExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 modFnc l re1 re2 s2 - | LessThanEqualExpression (l,e1, e2) -> + | LessThanEqualExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 lteFnc l re1 re2 s2 - | LessThanExpression (l,e1, e2) -> + | LessThanExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 ltFnc l re1 re2 s2 - | GreaterThanEqualExpression (l,e1, e2) -> + | GreaterThanEqualExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 gteFnc l re1 re2 s2 - | GreaterThanExpression (l,e1, e2) -> + | GreaterThanExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 gtFnc l re1 re2 s2 - | EqualExpression (l,e1, e2) -> + | EqualExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 eqFnc l re1 re2 s2 - | NotEqualExpression (l,e1, e2) -> + | NotEqualExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 neqFnc l re1 re2 s2 - | AndExpression (l,e1, e2) -> + | AndExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 andFnc l re1 re2 s2 - | OrExpression (l,e1, e2) -> + | OrExpression (l,e1, e2) -> let re1, s1 = loopExpression e1 s let re2, s2 = loopExpression e2 s1 orFnc l re1 re2 s2 @@ -127,7 +127,7 @@ let foldAcnExpression intConstFnc acnIntConstFnc realConstFnc boolConstFnc asn1L type NonBooleanExpressionType = | IntExpType | RealExpType -with +with override this.ToString() = match this with | IntExpType -> "integer expression" @@ -136,7 +136,7 @@ with type ExpressionType = | BoolExpression | NonBooleanExpression of NonBooleanExpressionType -with +with override this.ToString() = match this with | BoolExpression -> "boolean expression" @@ -154,31 +154,31 @@ let validateAcnExpression handleLongField (exp:AcnExpression) = | ValResultOK expType -> match expType with | BoolExpression -> (ValResultError (l, "Expecting numeric expression"), 0) - | NonBooleanExpression net1-> + | NonBooleanExpression net1-> match e2 with | ValResultError _ -> (e2,s) | ValResultOK expType -> match expType with | BoolExpression -> (ValResultError (l, "Expecting numeric expression"), 0) - | NonBooleanExpression net2 -> + | NonBooleanExpression net2 -> match net1 = net2 with - | true -> (ValResultOK (NonBooleanExpression net1), 0) + | true -> (ValResultOK (NonBooleanExpression net1), 0) | false -> (ValResultError (l, (sprintf "Expecting %s expression" (net1.ToString()))), 0) - - let numericComparativeBinaryOperator l e1 e2 s = + + let numericComparativeBinaryOperator l e1 e2 s = match e1 with | ValResultError _ -> (e1,s) | ValResultOK expType -> match expType with | BoolExpression -> (ValResultError (l, "Expecting numeric expression"), 0) - | NonBooleanExpression net1-> + | NonBooleanExpression net1-> match e2 with | ValResultError _ -> (e2,s) | ValResultOK expType -> match expType with | BoolExpression -> (ValResultError (l, "Expecting numeric expression"), 0) - | NonBooleanExpression net2 -> (ValResultOK BoolExpression, 0) - let eqNeqOperator l e1 e2 s = + | NonBooleanExpression net2 -> (ValResultOK BoolExpression, 0) + let eqNeqOperator l e1 e2 s = match e1 with | ValResultError _ -> (e1,s) | ValResultOK expType1 -> @@ -186,29 +186,29 @@ let validateAcnExpression handleLongField (exp:AcnExpression) = | ValResultError _ -> (e2,s) | ValResultOK expType2 -> match expType1 = expType2 with - | true -> (ValResultOK BoolExpression , 0) + | true -> (ValResultOK BoolExpression , 0) | false -> (ValResultError (l, (sprintf "Expecting %s expression" (expType1.ToString()))), 0) - - let andOrBinaryOperator l e1 e2 s = + + let andOrBinaryOperator l e1 e2 s = match e1 with | ValResultError _ -> (e1,s) | ValResultOK expType -> match expType with | NonBooleanExpression _ -> (ValResultError (l, "Expecting boolean expression"), 0) - | BoolExpression -> + | BoolExpression -> match e2 with | ValResultError _ -> (e2,s) | ValResultOK expType -> match expType with | NonBooleanExpression _ -> (ValResultError (l, "Expecting boolean expression"), 0) - | BoolExpression -> (ValResultOK BoolExpression, 0) + | BoolExpression -> (ValResultOK BoolExpression, 0) foldAcnExpression (fun i s -> (ValResultOK (NonBooleanExpression IntExpType)) , 0) (fun i s -> (ValResultOK (NonBooleanExpression IntExpType)) , 0) (fun i s -> (ValResultOK (NonBooleanExpression RealExpType)) , 0) (fun i s -> (ValResultOK BoolExpression) , 0) - (fun lf s -> (handleLongField lf) , 0) //we have to resolve the lf path and decide if its numeric or boolean expression. + (fun lf s -> (handleLongField lf) , 0) //we have to resolve the lf path and decide if its numeric or boolean expression. (fun l (e1) s -> //NotUnaryExpression match e1 with | ValResultError _ -> (e1,s) @@ -234,34 +234,34 @@ let validateAcnExpression handleLongField (exp:AcnExpression) = numericComparativeBinaryOperator (*gt*) eqNeqOperator (*equal*) eqNeqOperator (*not equal*) - andOrBinaryOperator (*and*) - andOrBinaryOperator (*or*) + andOrBinaryOperator (*and*) + andOrBinaryOperator (*or*) exp 0 |> fst -// present when property defintion +// present when property definition // this property is not part of the ACN type itself but part of the AcnChildInfo -type PresenceWhenBool = - | PresenceWhenBool of RelativePath - | PresenceWhenBoolExpression of AcnExpression - +type PresenceWhenBool = + | PresenceWhenBool of RelativePath + | PresenceWhenBoolExpression of AcnExpression + type AcnPresentWhenConditionChoiceChild = | PresenceInt of RelativePath*IntLoc | PresenceStr of RelativePath*StringLoc with - member this.valueAsString = + member this.valueAsString = match this with | PresenceInt (_,v) -> v.Value.ToString() | PresenceStr (_,v) -> v.Value - member this.relativePath = + member this.relativePath = match this with | PresenceInt (rp,_) | PresenceStr (rp,_) -> rp - member this.location = + member this.location = match this with | PresenceInt (rp,intLoc) -> intLoc.Location | PresenceStr (rp,strLoc) -> strLoc.Location - member this.kind = + member this.kind = match this with | PresenceInt _ -> 1 | PresenceStr _ -> 2 @@ -278,13 +278,13 @@ type AcnIntEncoding = | IntAscii | BCD -type MappingFunction = +type MappingFunction = | MappingFunction of (StringLoc option)*StringLoc -type PostEncodingFunction = +type PostEncodingFunction = | PostEncodingFunction of (StringLoc option)*StringLoc -type PreDecodingFunction = +type PreDecodingFunction = | PreDecodingFunction of (StringLoc option)*StringLoc @@ -347,8 +347,17 @@ type ObjectIdTypeAcnProperties = { type AcnBooleanEncoding = - | TrueValue of StringLoc + | TrueValue of StringLoc | FalseValue of StringLoc +with + member this.bitVal = + match this with + | TrueValue bv -> bv + | FalseValue bv -> bv + member this.isTrue = + match this with + | TrueValue _ -> true + | FalseValue _ -> false type BooleanAcnProperties = { encodingPattern : AcnBooleanEncoding option @@ -375,7 +384,7 @@ type AcnParamType = | AcnPrmNullType of SrcLoc | AcnPrmRefType of StringLoc*StringLoc with - override this.ToString() = + override this.ToString() = match this with | AcnPrmInteger _ -> "INTEGER" | AcnPrmBoolean _ -> "BOOLEAN" @@ -383,7 +392,7 @@ with | AcnPrmRefType (md,ts) -> sprintf "%s.%s" md.Value ts.Value override x.Equals(yobj) = match yobj with - | :? AcnParamType as other -> + | :? AcnParamType as other -> match x, other with | AcnPrmInteger _ , AcnPrmInteger _ -> true | AcnPrmBoolean _ , AcnPrmBoolean _ -> true @@ -391,7 +400,7 @@ with | AcnPrmRefType (md,ts) , AcnPrmRefType (md2,ts2) -> md=md2 && ts=ts2 | _ -> false | _ -> false - override x.GetHashCode() = + override x.GetHashCode() = match x with | AcnPrmInteger _ -> 1 | AcnPrmBoolean _ -> 2 @@ -399,22 +408,22 @@ with | AcnPrmRefType (md,ts) -> md.GetHashCode() ^^^ ts.GetHashCode() - + type AcnParameter = { name : string asn1Type : AcnParamType loc : SrcLoc id : ReferenceToType } -with +with member this.c_name = ToC this.name type GenericAcnPresentWhenCondition = - | GP_PresenceBool of RelativePath + | GP_PresenceBool of RelativePath | GP_PresenceInt of RelativePath*IntLoc - | GP_PresenceStr of RelativePath*StringLoc - + | GP_PresenceStr of RelativePath*StringLoc + type GenAcnEncodingProp = | GP_PosInt | GP_TwosComplement @@ -423,26 +432,26 @@ type GenAcnEncodingProp = | GP_IEEE754_32 | GP_IEEE754_64 -type GenSizeProperty = +type GenSizeProperty = | GP_Fixed of IntLoc - | GP_NullTerminated + | GP_NullTerminated | GP_SizeDeterminant of RelativePath -type GenericAcnProperty = +type GenericAcnProperty = | ENCODING of GenAcnEncodingProp | SIZE of GenSizeProperty - | ALIGNTONEXT of AcnAligment - | ENCODE_VALUES - | SAVE_POSITION + | ALIGNTONEXT of AcnAlignment + | ENCODE_VALUES + | SAVE_POSITION | PRESENT_WHEN of GenericAcnPresentWhenCondition list - | PRESENT_WHEN_EXP of AcnExpression + | PRESENT_WHEN_EXP of AcnExpression | TRUE_VALUE of StringLoc | FALSE_VALUE of StringLoc | PATTERN of PATTERN_PROP_VALUE | CHOICE_DETERMINANT of RelativePath - | ENDIANNES of AcnEndianness + | ENDIANNESS of AcnEndianness | ENUM_SET_VALUE of IntLoc | TERMINATION_PATTERN of StringLoc //bit pattern | MAPPING_FUNCTION of (StringLoc option)*StringLoc @@ -457,7 +466,7 @@ type AcnTypeEncodingSpec = { children : ChildSpec list loc : SrcLoc comments : string list - postion : SrcLoc*SrcLoc //start pos, end pos + position : SrcLoc*SrcLoc //start pos, end pos antlrSubTree :ITree option } diff --git a/CommonTypes/CommonTypes.fs b/CommonTypes/CommonTypes.fs index 4dcb1bbc0..febcde61a 100644 --- a/CommonTypes/CommonTypes.fs +++ b/CommonTypes/CommonTypes.fs @@ -9,25 +9,78 @@ open System.IO open Antlr.Runtime.Tree open Antlr.Runtime -let c_keyworkds = [ "auto"; "break"; "case"; "char"; "const"; "continue"; "default"; "do"; "double"; "else"; "enum"; "extern"; "float"; "for"; "goto"; "if"; "int"; "long"; "register"; "return"; "short"; "signed"; "sizeof"; "static"; "struct"; "switch"; "typedef"; "union"; "unsigned"; "void"; "volatile"; "while"; ] -let scala_keyworkds = [ "abstract"; "case"; "catch"; "class"; "def"; "do"; "else"; "enum"; "export"; "extends"; "false"; "final"; "finally"; "float"; "for"; "given"; "if"; "implicit"; "import"; "int"; "lazy"; "match"; "new"; "null"; "object"; "override"; "package"; "private"; "protected"; "return"; "sealed"; "super"; "then"; "throw"; "trait"; "true"; "try"; "type"; "val"; "var"; "while"; "with"; "yield"; ] -let ada_keyworkds = [ "abort"; "else"; "new"; "return"; "abs"; "elsif"; "not"; "reverse"; "abstract"; "end"; "null"; "accept"; "entry"; "select"; "access"; "exception"; "of"; "separate"; "aliased"; "exit"; "or"; "some"; "all"; "others"; "subtype"; "and"; "for"; "out"; "synchronized"; "array"; "function"; "overriding"; "at"; "tagged"; "generic"; "package"; "task"; "begin"; "goto"; "pragma"; "terminate"; "body"; "private"; "then"; "if"; "procedure"; "type"; "case"; "in"; "protected"; "constant"; "interface"; "until"; "is"; "raise"; "use"; "declare"; "range"; "delay"; "limited"; "record"; "when"; "delta"; "loop"; "rem"; "while"; "digits"; "renames"; "with"; "do"; "mod"; "requeue"; "xor" ] +let c_keywords = [ "auto"; "break"; "case"; "char"; "const"; "continue"; "default"; "do"; "double"; "else"; "enum"; "extern"; "float"; "for"; "goto"; "if"; "int"; "long"; "register"; "return"; "short"; "signed"; "sizeof"; "static"; "struct"; "switch"; "typedef"; "union"; "unsigned"; "void"; "volatile"; "while"; ] +let scala_keywords = [ "abstract"; "case"; "catch"; "class"; "def"; "do"; "else"; "enum"; "export"; "extends"; "false"; "final"; "finally"; "float"; "for"; "given"; "if"; "implicit"; "import"; "int"; "lazy"; "match"; "new"; "null"; "object"; "override"; "package"; "private"; "protected"; "return"; "sealed"; "super"; "then"; "throw"; "trait"; "true"; "try"; "type"; "val"; "var"; "while"; "with"; "yield"; ] +let ada_keywords = [ "abort"; "else"; "new"; "return"; "abs"; "elsif"; "not"; "reverse"; "abstract"; "end"; "null"; "accept"; "entry"; "select"; "access"; "exception"; "of"; "separate"; "aliased"; "exit"; "or"; "some"; "all"; "others"; "subtype"; "and"; "for"; "out"; "synchronized"; "array"; "function"; "overriding"; "at"; "tagged"; "generic"; "package"; "task"; "begin"; "goto"; "pragma"; "terminate"; "body"; "private"; "then"; "if"; "procedure"; "type"; "case"; "in"; "protected"; "constant"; "interface"; "until"; "is"; "raise"; "use"; "declare"; "range"; "delay"; "limited"; "record"; "when"; "delta"; "loop"; "rem"; "while"; "digits"; "renames"; "with"; "do"; "mod"; "requeue"; "xor" ] -type UserErrorSeverity = +type UserErrorSeverity = | ERROR | WARNING | INFO -type FuncParamType = - | VALUE of string - | POINTER of string - | FIXARRAY of string - with - member this.p = +type SelectionType = + | Value + | Pointer + | FixArray + +type Accessor = + | ValueAccess of string * SelectionType * bool // selection identifier and its type + | PointerAccess of string * SelectionType * bool // selection identifier and its type + | ArrayAccess of string * SelectionType // array index and the type of the array's element + member this.selectionType = + match this with + | ValueAccess (_, sel, _) -> sel + | PointerAccess (_, sel, _) -> sel + | ArrayAccess (_, sel) -> sel + member this.accessorType = match this with - | VALUE x -> x - | POINTER x -> x - | FIXARRAY x -> x + | ValueAccess _ -> Value + | PointerAccess _ -> Pointer + | ArrayAccess _ -> FixArray + +type Selection = { + receiverId: string + receiverType: SelectionType + path: Accessor list +} with + static member emptyPath (receiverId: string) (receiverType: SelectionType): Selection = + { Selection.receiverId = receiverId; receiverType = receiverType; path = []} + static member valueEmptyPath (receiverId: string): Selection = Selection.emptyPath receiverId Value + + member this.append (acc: Accessor): Selection = + assert (this.selectionType = acc.accessorType) + { this with path = this.path @ [acc] } + + member this.appendSelection (selectionId: string) (selTpe: SelectionType) (selOpt: bool): Selection = + let currTpe = this.selectionType + assert (currTpe = Value || currTpe = Pointer) + this.append (if currTpe = Value then ValueAccess (selectionId, selTpe, selOpt) else PointerAccess (selectionId, selTpe, selOpt)) + + member this.selectionType: SelectionType = + if this.path.IsEmpty then this.receiverType + else (List.last this.path).selectionType + + member this.isOptional: bool = + (not this.path.IsEmpty) && + match List.last this.path with + |ValueAccess (_exist, _, isOptional) -> isOptional + |PointerAccess (_, _, isOptional) -> isOptional + |ArrayAccess _ -> false + + member this.lastId: string = + if this.path.IsEmpty then this.receiverId + else + match List.last this.path with + |ValueAccess (id, _, _) -> id + |PointerAccess (id, _, _) -> id + |ArrayAccess _ -> raise (BugErrorException "lastId on ArrayAccess") + + member this.asLast: Selection = + assert (not this.path.IsEmpty) + match List.last this.path with + |ValueAccess (id, _, _) -> Selection.emptyPath id Value + |PointerAccess (id, _, _) -> Selection.emptyPath id Pointer + |ArrayAccess _ -> raise (BugErrorException "lastId on ArrayAccess") type UserError = { @@ -53,7 +106,7 @@ type TimeTypeClass = type Asn1DateValue = { years : BigInteger months : BigInteger - days : BigInteger + days : BigInteger } type Asn1TimeValue = { @@ -83,7 +136,7 @@ type Asn1DateTimeValue = type Asn1DateTimeValueLoc = PrimitiveWithLocation -let timeTypeToAsn1Str tmcl = +let timeTypeToAsn1Str tmcl = match tmcl with |Asn1LocalTime _ -> "TIME" |Asn1UtcTime _ -> "TIME" @@ -94,7 +147,7 @@ let timeTypeToAsn1Str tmcl = |Asn1Date_LocalTimeWithTimeZone _ -> "TIME" type DirInfo = { - rootDir : string + rootDir : string srcDir : string asn1rtlDir : string boardsDir : string @@ -103,7 +156,7 @@ type DirInfo = { let createTimeValueFromString timeClass (strL:StringLoc) = let pow b e = BigInteger.Pow (b,e) let str = strL.Value - let pr (s:string) size mn mx = + let pr (s:string) size mn mx = if s.Length <> size then raise(SemanticError(strL.Location, "Invalid TIME VALUE")) match BigInteger.TryParse s with @@ -115,14 +168,14 @@ let createTimeValueFromString timeClass (strL:StringLoc) = | [] -> () | c::_ -> raise(SemanticError(strL.Location, (sprintf "Invalid character '%c'" c))) (*16:53:49.0123+02:00*) - let parseTimeValue (str:string) = + let parseTimeValue (str:string) = let parseSeconds (secStr:string) = match secStr.Contains(".") with | false -> pr secStr 2 0I 59I, None | true -> let p = secStr.Split('.') let s = pr p.[0] 2 0I 59I - let fraction = + let fraction = match p.[1].Length with | 0 -> None | _ -> @@ -137,7 +190,7 @@ let createTimeValueFromString timeClass (strL:StringLoc) = raise(SemanticError(strL.Location, "Invalid TIME VALUE")) let scs, fraction = parseSeconds parts.[2] {Asn1TimeValue.hours = pr parts.[0] 2 0I 23I; mins = pr parts.[1] 2 0I 59I; secs = scs; secsFraction = fraction} - let parseUtcTimeValue (str:string) = + let parseUtcTimeValue (str:string) = match str.EndsWith("Z") with | false -> raise(SemanticError(strL.Location, "Invalid TIME VALUE. Expecting a 'Z' at the end")) | true -> parseTimeValue (str.Substring(0, str.Length-1)) @@ -149,7 +202,6 @@ let createTimeValueFromString timeClass (strL:StringLoc) = {Asn1DateValue.years = pr parts.[0] parts.[0].Length 0I 9999999999I; months = pr parts.[1] 2 1I 12I; days = pr parts.[2] 2 1I 31I} let parseTimeValueWithTimeZone (str:string) = - //let str = "2020-05-16T16:53:49+02:00" if str.Length <= 6 then raise(SemanticError(strL.Location, "Invalid TIME VALUE.")) let tm = str.Substring(0, str.Length-6) @@ -159,7 +211,7 @@ let createTimeValueFromString timeClass (strL:StringLoc) = let tz = str.Substring(str.Length-5) if (tz.Length <> 5) then raise(SemanticError(strL.Location, "Invalid TIME VALUE.")) - let time = parseTimeValue tm + let time = parseTimeValue tm let parts =tz.Split(':') let tz = {Asn1TimeZoneValue.sign = (if sign = '+' then 1I else (-1I)); hours = pr parts.[0] 2 0I 23I; mins = pr parts.[1] 2 0I 59I} (time, tz) @@ -168,7 +220,7 @@ let createTimeValueFromString timeClass (strL:StringLoc) = if parts.Length <> 2 then raise(SemanticError(strL.Location, "Invalid DATE TIME VALUE.")) (parseDateValue parts.[0], fnc parts.[1]) - let ret = + let ret = match timeClass with |Asn1LocalTime _ -> Asn1LocalTimeValue (parseTimeValue str) |Asn1UtcTime _ -> Asn1UtcTimeValue (parseUtcTimeValue str) @@ -176,7 +228,7 @@ let createTimeValueFromString timeClass (strL:StringLoc) = |Asn1Date -> Asn1DateValue (parseDateValue str) |Asn1Date_LocalTime _ -> Asn1Date_LocalTimeValue(splitDateTimeString str parseTimeValue) |Asn1Date_UtcTime _ -> Asn1Date_UtcTimeValue(splitDateTimeString str parseUtcTimeValue) - |Asn1Date_LocalTimeWithTimeZone _ -> + |Asn1Date_LocalTimeWithTimeZone _ -> let (a,(b,c)) = splitDateTimeString str parseTimeValueWithTimeZone Asn1Date_LocalTimeWithTimeZoneValue (a,b,c) {Asn1DateTimeValueLoc.Value = ret; Location = strL.Location} @@ -210,89 +262,52 @@ let asn1DateTimeValueToString (tv:Asn1DateTimeValue) = |Asn1Date_LocalTimeWithTimeZoneValue (dt,tv, tz)-> (asn1DateValueToString dt) + (asn1TimeValueToString tv) + (timeZoneToString tz) -let someTests () = -(* - |Asn1Date - |Asn1Date_LocalTime - |Asn1Date_UtcTime - |Asn1Date_LocalTimeWithTimeZone - -*) - let loc str = { StringLoc.Value = str; Location = {srcFilename = "a.asn1"; srcLine = 20; charPos = 5 }} - let a1 = createTimeValueFromString (Asn1LocalTime 3) (loc "23:53:49.234") - let a1 = createTimeValueFromString (Asn1UtcTime 0) (loc "23:53:49Z") - let a1 = createTimeValueFromString (Asn1LocalTimeWithTimeZone 3) (loc "23:53:49.234+02:00") - let a1 = createTimeValueFromString Asn1Date (loc "2020-05-16") - let a1 = createTimeValueFromString (Asn1Date_LocalTime 2) (loc "2020-05-16T16:53:49.21") - let a1 = createTimeValueFromString (Asn1Date_UtcTime 2) (loc "2020-05-16T16:53:59.21Z") - let a1 = createTimeValueFromString (Asn1Date_LocalTimeWithTimeZone 2) (loc "2020-05-16T16:53:59.21-11:30") - 0 - -(* -let getDateTimeFromAsn1TimeStringValue timeClass (str:StringLoc) = - try - let dt = - match timeClass with - |Asn1LocalTime _ -> DateTime.ParseExact(str.Value, "HH:mm:ss.FFF", CultureInfo.InvariantCulture) - |Asn1UtcTime _ -> DateTime.Parse(str.Value) (*.ToUniversalTime ()*) - |Asn1LocalTimeWithTimeZone _ -> DateTime.ParseExact(str.Value, "HH:mm:ss.FFFK", CultureInfo.InvariantCulture) - |Asn1Date -> DateTime.ParseExact(str.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture) - |Asn1Date_LocalTime _ -> DateTime.ParseExact(str.Value, "yyyy-MM-dd'T'HH:mm:ss.FFF", CultureInfo.InvariantCulture) - |Asn1Date_UtcTime _ -> DateTime.Parse(str.Value) (*.ToUniversalTime ()*) - |Asn1Date_LocalTimeWithTimeZone _ -> DateTime.ParseExact(str.Value, "yyyy-MM-dd'T'HH:mm:ss.FFFK", CultureInfo.InvariantCulture) - {DateTimeLoc.Value = dt; Location = str.Location} - with - | :? System.FormatException as e -> raise(SemanticError(str.Location, "Invalid TIME VALUE")) - - -*) - type ProgrammingLanguage = |C |Scala |Ada - with + with member l.cmp (s1:string) (s2:string) = match l with |C -> s1 = s2 |Scala -> s1 = s2 // TODO: Scala |Ada -> s1.icompare s2 - member l.keywords = + member l.keywords = match l with - |C -> c_keyworkds - |Scala -> scala_keyworkds - |Ada -> ada_keyworkds + |C -> c_keywords + |Scala -> scala_keywords + |Ada -> ada_keywords static member AllLanguages = [C; Scala; Ada] - + member l.OnTypeNameConflictTryAppendModName = match l with |C -> true |Scala -> true // TODO: SCala |Ada -> false - member l.declare_IntegerNoRTL = - match l with + member l.declare_IntegerNoRTL = + match l with | C -> "", "asn1SccSint", "INTEGER" - | Scala -> "", "Int", "INTEGER" // TODO: Scala + | Scala -> "", "Long", "INTEGER" // TODO: Scala | Ada -> "adaasn1rtl", "Asn1Int", "INTEGER" member l.declare_PosIntegerNoRTL = - match l with - | C -> "", "asn1SccUint" , "INTEGER" - | Scala -> "", " asn1SccUint" , "INTEGER" // TODO: Scala - | Ada -> "adaasn1rtl", "Asn1UInt" , "INTEGER" - member l.getRealRtlTypeName = - match l with - | C -> "", "asn1Real", "REAL" - | Scala -> "", "asn1Real", "REAL" // TODO: Scala - | Ada -> "adaasn1rtl", "Asn1Real", "REAL" - member l.getObjectIdentifierRtlTypeName relativeId = + match l with + | C -> "", "asn1SccUint" , "INTEGER" + | Scala -> "", " asn1SccUint" , "INTEGER" // TODO: Scala + | Ada -> "adaasn1rtl", "Asn1UInt" , "INTEGER" + member l.getRealRtlTypeName = + match l with + | C -> "", "asn1Real", "REAL" + | Scala -> "", "asn1Real", "REAL" // TODO: Scala + | Ada -> "adaasn1rtl", "Asn1Real", "REAL" + member l.getObjectIdentifierRtlTypeName relativeId = let asn1Name = if relativeId then "RELATIVE-OID" else "OBJECT IDENTIFIER" - match l with + match l with | C -> "", "Asn1ObjectIdentifier", asn1Name | Scala -> "", "Asn1ObjectIdentifier", asn1Name // TODO: Scala | Ada -> "adaasn1rtl", "Asn1ObjectIdentifier", asn1Name - member l.getTimeRtlTypeName timeClass = + member l.getTimeRtlTypeName timeClass = let asn1Name = "TIME" - match l, timeClass with + match l, timeClass with | C, Asn1LocalTime _ -> "", "Asn1LocalTime", asn1Name | C, Asn1UtcTime _ -> "", "Asn1UtcTime", asn1Name | C, Asn1LocalTimeWithTimeZone _ -> "", "Asn1TimeWithTimeZone", asn1Name @@ -315,15 +330,15 @@ type ProgrammingLanguage = | Ada, Asn1Date_LocalTime _ -> "adaasn1rtl", "Asn1DateLocalTime", asn1Name | Ada, Asn1Date_UtcTime _ -> "adaasn1rtl", "Asn1DateUtcTime", asn1Name | Ada, Asn1Date_LocalTimeWithTimeZone _ -> "adaasn1rtl", "Asn1DateTimeWithTimeZone", asn1Name - member l.getNullRtlTypeName = - match l with - | C -> "", "NullType", "NULL" - | Scala -> "", "NullType", "NULL" // TODO: Scala - | Ada -> "adaasn1rtl", "Asn1NullType", "NULL" + member l.getNullRtlTypeName = + match l with + | C -> "", "NullType", "NULL" + | Scala -> "", "NullType", "NULL" // TODO: Scala + | Ada -> "adaasn1rtl", "Asn1NullType", "NULL" member l.getBoolRtlTypeName = - match l with - | C -> "","flag","BOOLEAN" - | Scala -> "","Boolean","BOOLEAN" // TODO: Scala + match l with + | C -> "","flag","BOOLEAN" + | Scala -> "","Boolean","BOOLEAN" // TODO: Scala | Ada -> "adaasn1rtl", "Asn1Boolean", "BOOLEAN" @@ -337,14 +352,14 @@ type Codec = | Decode -> "_Decode" -type ObjectIdentifierValueCompoent = +type ObjectIdentifierValueComponent = | ObjInteger of IntLoc //integer form | ObjNamedDefValue of StringLoc*(StringLoc*StringLoc) //named form, points to an integer value | ObjNamedIntValue of StringLoc*IntLoc //name form | ObjRegisteredKeyword of StringLoc*BigInteger | ObjDefinedValue of StringLoc*StringLoc //value assignment to Integer value or ObjectIdentifier or RelativeObject -type ResolvedObjectIdentifierValueCompoent = +type ResolvedObjectIdentifierValueComponent = | ResObjInteger of IntLoc //integer form | ResObjNamedDefValue of StringLoc*(StringLoc*StringLoc)*BigInteger //named form, int VAS, int value | ResObjNamedIntValue of StringLoc*IntLoc //name form @@ -371,7 +386,7 @@ type SIZE = { acn : BigInteger } with - override x.ToString() = + override x.ToString() = x.uper.ToString() @@ -381,7 +396,7 @@ type Input = { } type FieldPrefix = - | FieldPrefixAuto + | FieldPrefixAuto | FieldPrefixUserValue of string type Targets = @@ -395,12 +410,12 @@ type ScopeNode = | MD of string //MODULE | TA of string //TYPE ASSIGNMENT | VA of string //VALUE ASSIGNMENT - | SEQ_CHILD of string //SEQUENCE child + | SEQ_CHILD of string*bool //SEQUENCE child, is optional | CH_CHILD of string*string*string //CHOICE child, choice child present when name | PRM of string //ACN parameter | SQF //SEQUENCE OF CHILD -type ReferenceToType = +type ReferenceToType = | ReferenceToType of ScopeNode list @@ -443,7 +458,7 @@ type ScopeNode with | TA strVal | VA strVal | PRM strVal - | SEQ_CHILD strVal + | SEQ_CHILD (strVal, _) | CH_CHILD (strVal,_, _) -> strVal | SQF -> "#" member this.StrValue = this.AsString @@ -464,8 +479,8 @@ type VarScopNode = | VA2 strVal -> strVal | DV -> "DV" | NI ni -> ni - | VL idx -> "v" + idx.ToString() - | IMG idx -> "img" + idx.ToString() + | VL idx -> "v" + idx.ToString() + | IMG idx -> "img" + idx.ToString() | CON idx -> "c" + idx.ToString() | SQOV i -> sprintf"[%d]" i | SQCHILD s-> s @@ -473,42 +488,42 @@ type VarScopNode = override this.ToString() = this.StrValue -type ReferenceToValue = +type ReferenceToValue = | ReferenceToValue of (ScopeNode list)*(VarScopNode list) with member this.ModName = match this with - | ReferenceToValue (path,_) -> + | ReferenceToValue (path,_) -> match path with | (MD modName)::_ -> modName - | _ -> raise(BugErrorException "Did not find module at the begining of the scope path") + | _ -> raise(BugErrorException "Did not find module at the beginning of the scope path") -type ReferenceToType with - member this.AsString = - match this with - | ReferenceToType sn -> sn |> Seq.map(fun x -> x.AsString) |> Seq.StrJoin "." - member this.ToScopeNodeList = +type ReferenceToType with + member this.AsString = + match this with + | ReferenceToType sn -> sn |> Seq.map(fun x -> x.AsString) |> Seq.StrJoin "." + member this.ToScopeNodeList = match this with - | ReferenceToType path -> path + | ReferenceToType path -> path member this.ModName = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path with | (MD modName)::_ -> modName - | _ -> raise(BugErrorException "Did not find module at the begining of the scope path") + | _ -> raise(BugErrorException "Did not find module at the beginning of the scope path") member this.tasInfo = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path with | (MD modName)::(TA tasName)::[] -> Some ({TypeAssignmentInfo.modName = modName; tasName=tasName}) | _ -> None member this.AcnAbsPath = match this with - | ReferenceToType path -> path |> List.map (fun i -> i.StrValue) - member this.getSeqChildId (childName:string) = + | ReferenceToType path -> path |> List.map (fun i -> i.StrValue) + member this.getSeqChildId (childName:string) (childIsOptional: bool) = match this with - | ReferenceToType path -> ReferenceToType (path@[SEQ_CHILD childName]) + | ReferenceToType path -> ReferenceToType (path@[SEQ_CHILD (childName, childIsOptional)]) member this.getSeqOfChildId = match this with | ReferenceToType path -> ReferenceToType (path@[SQF]) @@ -521,61 +536,50 @@ type ReferenceToType with | ReferenceToType ((MD mdName)::(TA tasName)::[]) -> ReferenceToType ((MD mdName)::(TA tasName)::[PRM paramName]) | _ -> raise(BugErrorException "Cannot add parameter here. Only within TAS scope") - member this.appendLongChildId (childRelativePath:string list) = - match this with - | ReferenceToType path -> - let newTail = - childRelativePath |> - List.map(fun s ->SEQ_CHILD s) - ReferenceToType (path@newTail) - member this.beginsWith (md:string) (ts:string)= + member this.beginsWith (md:string) (ts:string)= match this with | ReferenceToType((MD mdName)::(TA tasName)::[]) -> mdName = md && tasName = ts | _ -> false member this.lastItem = match this with - | ReferenceToType path -> + | ReferenceToType path -> match path |> List.rev |> List.head with - | SEQ_CHILD name -> name + | SEQ_CHILD (name, _) -> name | CH_CHILD (name,_,_) -> name | _ -> raise (BugErrorException "error in lastitem") + + member this.lastItemIsOptional = + match this with + | ReferenceToType path -> + match path |> List.rev |> List.head with + | SEQ_CHILD (_, opt) -> opt + | _ -> false + + member this.dropLast = + match this with + | ReferenceToType path -> + ReferenceToType (List.removeAt ((List.length path) - 1) path) + member this.parentTypeId = match this with - | ReferenceToType path -> + | ReferenceToType path -> let pathPar = path |> List.rev |> List.tail |> List.rev match pathPar with - | [] + | [] | _::[] -> None | _ -> Some (ReferenceToType pathPar) - member this.SeqeuenceOfLevel = + member this.SequenceOfLevel = match this with | ReferenceToType path -> path |> List.filter(fun n -> match n with SQF -> true | _ -> false) |> Seq.length static member createFromModAndTasName (modName : string) ((tasName : string))= ReferenceToType((MD modName)::(TA tasName)::[]) - - -(* -let rec foldMap func state lst = - match lst with - | [] -> [],state - | h::tail -> - let procItem, newState = func state h - let restList, finalState = tail |> foldMap func newState - procItem::restList, finalState - -let foldMap = RemoveParamterizedTypes.foldMap -*) - - -let foldMap func state lst = +let foldMap (func: 'a -> 'b -> 'c * 'a) (state: 'a) (lst: 'b list) : 'c list * 'a = let rec loop acc func state lst = match lst with | [] -> acc |> List.rev , state - | h::tail -> + | h::tail -> let procItem, newState = func state h - //let restList, finalState = tail |> loop func newState - //procItem::restList, finalState loop (procItem::acc) func newState tail loop [] func state lst @@ -584,7 +588,7 @@ type FE_TypeDefinitionKindInternal = | FEI_NewSubTypeDefinition of ReferenceToType //subtype | FEI_Reference2RTL | FEI_Reference2OtherType of ReferenceToType - override this.ToString() = + override this.ToString() = match this with | FEI_NewTypeDefinition -> "NewTypeDefinition" | FEI_NewSubTypeDefinition subId -> sprintf "NewSubTypeDefinition %s" subId.AsString @@ -594,9 +598,9 @@ type FE_TypeDefinitionKindInternal = type TypeDefinitionBaseKind = | NewTypeDefinition //type - | NewSubTypeDefinition + | NewSubTypeDefinition | Reference2RTL - | Reference2OtherType + | Reference2OtherType @@ -604,19 +608,19 @@ type FE_PrimitiveTypeDefinitionKind = | PrimitiveNewTypeDefinition //type | PrimitiveNewSubTypeDefinition of FE_PrimitiveTypeDefinition //subtype | PrimitiveReference2RTL - | PrimitiveReference2OtherType + | PrimitiveReference2OtherType member this.BaseKind = match this with | PrimitiveNewTypeDefinition -> NewTypeDefinition | PrimitiveNewSubTypeDefinition sub -> NewTypeDefinition | PrimitiveReference2RTL -> Reference2RTL | PrimitiveReference2OtherType -> Reference2OtherType - override this.ToString() = + override this.ToString() = match this with | PrimitiveNewTypeDefinition -> "NewTypeDefinition" | PrimitiveNewSubTypeDefinition sub -> sprintf "NewSubTypeDefinition %s.%s" sub.programUnit sub.typeName | PrimitiveReference2RTL -> "FE_Reference2RTL" - | PrimitiveReference2OtherType -> "FE_Reference2OtherType" + | PrimitiveReference2OtherType -> "FE_Reference2OtherType" and FE_PrimitiveTypeDefinition = { asn1Name : string @@ -629,13 +633,13 @@ and FE_PrimitiveTypeDefinition = { type FE_NonPrimitiveTypeDefinitionKind<'SUBTYPE> = | NonPrimitiveNewTypeDefinition //type | NonPrimitiveNewSubTypeDefinition of 'SUBTYPE //subtype - | NonPrimitiveReference2OtherType + | NonPrimitiveReference2OtherType member this.BaseKind = match this with | NonPrimitiveNewTypeDefinition -> NewTypeDefinition | NonPrimitiveNewSubTypeDefinition sub -> NewTypeDefinition | NonPrimitiveReference2OtherType -> Reference2OtherType - override this.ToString() = + override this.ToString() = match this with | NonPrimitiveNewTypeDefinition -> "NewTypeDefinition" | NonPrimitiveNewSubTypeDefinition subId -> sprintf "NewSubTypeDefinition %s" (subId.ToString()) @@ -657,7 +661,7 @@ type FE_StringTypeDefinition = { with member this.longTypedefName l callerProgramUnit = this.longTypedefName2 (l=Ada) callerProgramUnit - + member this.longTypedefName2 bHasUnits callerProgramUnit = let z n = this.programUnit + "." + n match bHasUnits with @@ -672,7 +676,7 @@ type FE_SizeableTypeDefinition = { typeName : string //e.g. MyInt, Asn1SccInt, Asn1SccUInt index : string array : string - length_index : string + length_index : string kind : FE_NonPrimitiveTypeDefinitionKind } with @@ -692,7 +696,7 @@ type FE_SequenceTypeDefinition = { programUnit : string //the program unit where this type is defined typeName : string //e.g. MyInt, Asn1SccInt, Asn1SccUInt exist : string - extention_function_potisions : string + extension_function_positions : string kind : FE_NonPrimitiveTypeDefinitionKind } with @@ -722,7 +726,7 @@ with | false -> this | true when this.programUnit = callerProgramUnit -> this | true -> {this with typeName = z this.typeName; index_range = z this.index_range; selection = z this.selection} - + member this.longTypedefName l callerProgramUnit = this.longTypedefName2 (l=Ada) callerProgramUnit @@ -746,7 +750,7 @@ with | true -> {this with typeName = z this.typeName; index_range = z this.index_range} -type FE_TypeDefinition = +type FE_TypeDefinition = | FE_PrimitiveTypeDefinition of FE_PrimitiveTypeDefinition | FE_SequenceTypeDefinition of FE_SequenceTypeDefinition | FE_StringTypeDefinition of FE_StringTypeDefinition @@ -754,8 +758,8 @@ type FE_TypeDefinition = | FE_ChoiceTypeDefinition of FE_ChoiceTypeDefinition | FE_EnumeratedTypeDefinition of FE_EnumeratedTypeDefinition - with - member this.typeName = + with + member this.typeName = match this with | FE_PrimitiveTypeDefinition a -> a.typeName | FE_SequenceTypeDefinition a -> a.typeName @@ -763,7 +767,7 @@ type FE_TypeDefinition = | FE_SizeableTypeDefinition a -> a.typeName | FE_ChoiceTypeDefinition a -> a.typeName | FE_EnumeratedTypeDefinition a -> a.typeName - member this.programUnit = + member this.programUnit = match this with | FE_PrimitiveTypeDefinition a -> a.programUnit | FE_SequenceTypeDefinition a -> a.programUnit @@ -771,7 +775,7 @@ type FE_TypeDefinition = | FE_SizeableTypeDefinition a -> a.programUnit | FE_ChoiceTypeDefinition a -> a.programUnit | FE_EnumeratedTypeDefinition a -> a.programUnit - member this.kind = + member this.kind = match this with | FE_PrimitiveTypeDefinition a -> a.kind.ToString() | FE_SequenceTypeDefinition a -> a.kind.ToString() @@ -789,7 +793,7 @@ type FE_TypeDefinition = | FE_EnumeratedTypeDefinition a -> a.kind.BaseKind - member this.asn1Name = + member this.asn1Name = match this with | FE_PrimitiveTypeDefinition a -> a.asn1Name | FE_SequenceTypeDefinition a -> a.asn1Name @@ -798,7 +802,7 @@ type FE_TypeDefinition = | FE_ChoiceTypeDefinition a -> a.asn1Name | FE_EnumeratedTypeDefinition a -> a.asn1Name - member this.asn1Module = + member this.asn1Module = match this with | FE_PrimitiveTypeDefinition a -> a.asn1Module | FE_SequenceTypeDefinition a -> a.asn1Module @@ -827,7 +831,7 @@ type IntegerOrDefinedValue = type Asn1SccOperationMode = | Asn1Compiler - | LanguagerServer + | LanguageServer type NamedBit0 = { Name:StringLoc @@ -868,8 +872,8 @@ let rec uperIntersection r1 r2 (l:SrcLoc) = | (PosInf(a), PosInf(b)) -> PosInf(max a b) | (PosInf(a), NegInf(b)) -> if a<=b then Concrete(a,b) else emptyTypeError l | (PosInf(a1), Concrete(a,b)) -> if a1>b then emptyTypeError l - elif a1<=a then r1 - else Concrete(a1,b) + elif a1<=a then r1 + else Concrete(a1,b) | (NegInf(a), NegInf(b)) -> NegInf(min a b) | (NegInf(a), PosInf(b)) -> if a>=b then Concrete(b,a) else emptyTypeError l | (NegInf(a1), Concrete(a,b)) -> if a1 string; - + type CommandLineSettings = { @@ -920,7 +924,7 @@ type CommandLineSettings = { handleEmptySequences : bool } -with +with member this.SIntMax = match this.integerSizeInBytes with | _ when this.integerSizeInBytes = 8I -> BigInteger(Int64.MaxValue) @@ -968,7 +972,7 @@ type SingleStringValue = | CStringValue of string | SpecialCharacter of SpecialCharacter with - override this.ToString() = + override this.ToString() = match this with | CStringValue v -> v | SpecialCharacter CarriageReturn -> "\r" @@ -990,7 +994,7 @@ let StringValue2String (vals: SingleStringValue list) = let char2SingleStringValue (c:char) = if c = CharCR then SpecialCharacter CarriageReturn - elif c = CharLF then SpecialCharacter LineFeed - elif c = CharHT then SpecialCharacter HorizontalTab - elif c = CharNul then SpecialCharacter NullCharacter + elif c = CharLF then SpecialCharacter LineFeed + elif c = CharHT then SpecialCharacter HorizontalTab + elif c = CharNul then SpecialCharacter NullCharacter else CStringValue (c.ToString()) \ No newline at end of file diff --git a/CommonTypes/FsUtils.fs b/CommonTypes/FsUtils.fs index 8fd97b492..29aa9e94b 100644 --- a/CommonTypes/FsUtils.fs +++ b/CommonTypes/FsUtils.fs @@ -53,26 +53,26 @@ let getChildrenByType (tree:ITree, childType) = getTreeChildren(tree) |> List.fi let getChildByType (tree:ITree, childType) = List.head(getChildrenByType(tree, childType)) -let getOptionChildByType (tree:ITree, childType) = +let getOptionChildByType (tree:ITree, childType) = getTreeChildren(tree) |> List.tryFind(fun x -> x.Type = childType) //let getTextLine (tree:ITree) = (tree.Text, tree.Line) -type SrcLoc = - { +type SrcLoc = + { srcFilename : string - srcLine : int + srcLine : int charPos : int } -let srcLocContaints (startLoc:SrcLoc) (endLoc:SrcLoc) (uiLoc:SrcLoc) = - startLoc.srcLine <= uiLoc.srcLine && - startLoc.charPos <= uiLoc.charPos && - uiLoc.srcLine <= endLoc.srcLine && - uiLoc.charPos <= endLoc.charPos - - +let srcLocContains (startLoc:SrcLoc) (endLoc:SrcLoc) (uiLoc:SrcLoc) = + startLoc.srcLine <= uiLoc.srcLine && + startLoc.charPos <= uiLoc.charPos && + uiLoc.srcLine <= endLoc.srcLine && + uiLoc.charPos <= endLoc.charPos + + let emptyLocation = {srcFilename=""; srcLine=0; charPos = 0} @@ -80,18 +80,18 @@ let emptyLocation = {srcFilename=""; srcLine=0; charPos = 0} module Seq = let StrJoin str listItems = - if Seq.isEmpty listItems then + if Seq.isEmpty listItems then "" else listItems |> Seq.map(fun x -> x.ToString()) |> Seq.reduce(fun agr el -> agr + str + el.ToString()) [] -type PrimitiveWithLocation<'T when 'T :equality> = +type PrimitiveWithLocation<'T when 'T :equality> = { Value:'T Location:SrcLoc } - override x.ToString() = + override x.ToString() = x.Value.ToString() member x.AsTupple = (x.Value, x.Location) member x.IsEqual(other:PrimitiveWithLocation<'T>) = x.Value.Equals(other.Value) @@ -144,7 +144,7 @@ type ITree with member t.Children = getTreeChildren(t) member t.GetChildByType (childType) = getChildByType(t, childType) member t.GetChildrenByType(childType) = getChildrenByType(t, childType) - member t.GetOptChild(childTyep) = + member t.GetOptChild(childTyep) = match getChildrenByType(t, childTyep) with | [] -> None | first::_ -> Some(first) @@ -164,9 +164,9 @@ type ITree with | :? CommonErrorNode as errToken -> t.Text | _ -> tokens.[t.TokenStartIndex .. t.TokenStopIndex] |> Seq.map(fun (z:IToken) -> z.Text) |> Seq.StrJoin "" - - + + static member RegisterFiles(files:seq) = for (i,f) in files do if dict.ContainsKey i then @@ -177,7 +177,7 @@ type ITree with member t.FileName = dict.[t.Root] member t.Location = { srcFilename = t.FileName; srcLine = t.Line; charPos = t.CharPositionInLine} - member t.Parents = + member t.Parents = seq { if t.Parent <> null then yield t.Parent @@ -187,7 +187,7 @@ type ITree with member t.AllChildren = seq { yield t - for ch in t.Children do + for ch in t.Children do yield! ch.AllChildren } |> Seq.toList @@ -196,14 +196,14 @@ type ITree with // member t.GetValueFL v = (v, t.Location) member t.GetValueL<'T when 'T :equality> (v:'T) = { StringLoc.Value = v; Location = t.Location} - + member t.TextL = { StringLoc.Value = t.Text; Location = t.Location} - - member t.BigIntL integerSizeInBytes = { IntLoc.Value = t.BigInt integerSizeInBytes; Location = t.Location} - - member t.BigInt integerSizeInBytes = + + member t.BigIntL integerSizeInBytes = { IntLoc.Value = t.BigInt integerSizeInBytes; Location = t.Location} + + member t.BigInt integerSizeInBytes = let ret = BigInteger.Parse(t.Text) let mn = if integerSizeInBytes = 8I then (BigInteger System.Int64.MinValue) else (BigInteger System.Int32.MinValue) let mx = if integerSizeInBytes = 8I then (BigInteger System.Int64.MaxValue) else (BigInteger System.Int32.MaxValue) @@ -214,8 +214,8 @@ type ITree with | false -> ret member t.Double = System.Double.Parse(t.Text, System.Globalization.NumberFormatInfo.InvariantInfo) - member t.DoubleL = { StringLoc.Value = t.Double; Location = t.Location} - + member t.DoubleL = { StringLoc.Value = t.Double; Location = t.Location} + type PositionWithinFile = { @@ -243,7 +243,7 @@ let rec getAsTupples<'T> (list:array<'T>) (empty:'T) = } |> Seq.toList -let rec combinations arr = +let rec combinations arr = seq { let nLength = Array.length arr for i=0 to nLength - 1 do @@ -253,11 +253,11 @@ let rec combinations arr = | [] -> yield [arr.[i]] | _ -> for rightPart in rightPartComb do - yield (arr.[i]) :: rightPart + yield (arr.[i]) :: rightPart } |> Seq.toList |> List.filter(fun l -> List.length l = Array.length arr) -let getOptionalChildByType (tree:ITree, childType) = +let getOptionalChildByType (tree:ITree, childType) = match getChildrenByType(tree, childType) with | head::tail -> Some(head) | _ -> None @@ -273,20 +273,20 @@ let MakeLowerFirst(s:string) = let tryGetEnvVar (varName:string) = - let envVars = - System.Environment.GetEnvironmentVariables() |> Seq.cast |> Seq.map (fun d -> d.Key :?> string, d.Value :?> string) - envVars |> Seq.tryFind(fun (nm, vl) -> nm = varName) + let envVars = + System.Environment.GetEnvironmentVariables() |> Seq.cast |> Seq.map (fun d -> d.Key :?> string, d.Value :?> string) + envVars |> Seq.tryFind(fun (nm, vl) -> nm = varName) let checkForAdaKeywords () = match tryGetEnvVar "ASN1SCC_DISABLE_KEYW_CHECKS" with | Some (_,vl) -> vl <> "1" | None -> true - + type System.String with member s.WithLoc (lc:SrcLoc) = {StringLoc.Value = s; Location=lc} member this.L1 = MakeLowerFirst this - member this.U1 = + member this.U1 = if this.IsEmptyOrNull then "" else this.Substring(0,1).ToUpper() + this.Substring(1) member this.RDA = @@ -320,15 +320,15 @@ type Option<'T> with | Some v -> v | None -> other //member this.map fnc = Option.map fnc this - + type System.Int32 with member x.AsBigInt = BigInteger x type System.Collections.Generic.IEnumerable<'T> with - member t.StrJoin str = - if Seq.isEmpty(t) then + member t.StrJoin str = + if Seq.isEmpty(t) then "" else t |> Seq.map(fun x -> x.ToString()) |> Seq.reduce(fun agr el -> agr + str + el.ToString()) @@ -344,18 +344,18 @@ module List = | x::xs -> match x = item with | true -> true | false -> contains item xs - + let rec StartsWith subList biglist= match biglist,subList with |[],a::rest -> false |_,[] -> true - |h1::big, h2::smal -> h1=h2 && StartsWith smal big + |h1::big, h2::smal -> h1=h2 && StartsWith smal big let split func list = let l1 = list |> List.filter func let l2 = list |> List.filter (fun x -> not (func x)) (l1,l2) - + let Replace listToSearch listToReplace mainList = let rec GetSubList smallList bigList = match smallList, bigList with @@ -372,7 +372,7 @@ module List = let rec keepDuplicates_private lst fnc = match lst with | [] -> [] - | x::xs -> + | x::xs -> let dups = xs |> List.filter (fnc x) match dups with | [] -> keepDuplicates_private xs fnc @@ -380,7 +380,7 @@ module List = let keepDuplicatesCaseSensitive lst = keepDuplicates_private lst (=) - + let keepDuplicatesCaseInsensitive lst = keepDuplicates_private lst (fun (x:string) y -> x.icompare y) @@ -392,7 +392,7 @@ module List = let rec keepDuplicatesI (lst:string list) = match lst with | [] -> [] - | x::xs -> + | x::xs -> let dups = xs |> List.filter (fun l -> l.icompare x) match dups with | [] -> keepDuplicatesI xs @@ -417,14 +417,14 @@ let MinInt() = if WordSize()=64I then BigInteger(System.Int64.MinValue) else Big let powersof2 = [1..100] |> List.map(fun i -> (i, BigInteger.Pow(2I,i) - 1I )) -(* -let GetNumberOfBitsForNonNegativeInteger(a:BigInteger) = +(* +let GetNumberOfBitsForNonNegativeInteger(a:BigInteger) = let vl = a + 1I let lg = BigInteger.Log(vl, 2.0) BigInteger( System.Math.Ceiling(lg) ) *) -let GetNumberOfBitsForNonNegativeInteger(a:BigInteger) = +let GetNumberOfBitsForNonNegativeInteger(a:BigInteger) = if a > 0I then let aaa = powersof2 |> List.skipWhile(fun (i,pow2) -> a > pow2 ) match aaa with @@ -435,19 +435,19 @@ let GetNumberOfBitsForNonNegativeInteger(a:BigInteger) = (* -let GetNumberOfBitsForNonNegativeInteger2(a:BigInteger) = +let GetNumberOfBitsForNonNegativeInteger2(a:BigInteger) = let a = System.Decimal.Parse( a.ToString()) let lg = Math.Log(a+1m, 2.0) - System.Math.Ceiling() + System.Math.Ceiling() *) -let GetChoiceUperDeterminantLengthInBits(nChoiceAlternatives:BigInteger) = +let GetChoiceUperDeterminantLengthInBits(nChoiceAlternatives:BigInteger) = match nChoiceAlternatives with | _ when nChoiceAlternatives > 1I -> GetNumberOfBitsForNonNegativeInteger (nChoiceAlternatives - 1I) //BigInteger( System.Math.Ceiling(BigInteger.Log(nChoiceAlternatives,2.0)) ) | _ -> 0I -//let GetNumberOfBitsForNonNegativeInt(a:int) = +//let GetNumberOfBitsForNonNegativeInt(a:int) = // int (System.Math.Ceiling(BigInteger.Log(BigInteger(a)+1I,2.0)) ) let toString x = (sprintf "%A" x).Split(' ').[0].Trim() @@ -465,7 +465,7 @@ let BI (i:int) = BigInteger i // | i1::[] -> [i1*8uy] // | i1::i2::[] -> [i1*8uy+i2*4uy] // | i1::i2::i3::[] -> [i1*8uy+i2*4uy+i3*2uy] -// | i1::i2::i3::i4::tail -> (i1*8uy+i2*4uy+i3*2uy+i4)::(BitsToNibbles tail) +// | i1::i2::i3::i4::tail -> (i1*8uy+i2*4uy+i3*2uy+i4)::(BitsToNibbles tail) // let rec NibblesToBytes l:list = // match l with // | [] -> [] @@ -482,7 +482,7 @@ let bitStringValueToByteArray (s:StringLoc) = | i1::[] -> BitsToNibblesAux [] (i1*8uy::acc) | i1::i2::[] -> BitsToNibblesAux [] ((i1*8uy+i2*4uy)::acc) | i1::i2::i3::[] -> BitsToNibblesAux [] ((i1*8uy+i2*4uy+i3*2uy)::acc) - | i1::i2::i3::i4::tail -> + | i1::i2::i3::i4::tail -> let newAcc = (i1*8uy+i2*4uy+i3*2uy+i4)::acc BitsToNibblesAux tail newAcc BitsToNibblesAux l [] @@ -522,92 +522,92 @@ let byteArrayToBitStringValue (bytes: byte seq) = let octetStringLiteralToByteArray (octLiteral:string) = - let chars = octLiteral.ToCharArray() - let bytes = getAsTupples chars '0' |> List.map (fun (x1,x2)-> System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier)) + let chars = octLiteral.ToCharArray() + let bytes = getAsTupples chars '0' |> List.map (fun (x1,x2)-> System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier)) bytes //let rec DoTopologicalSort2 independentNodes dependentNodes comparer excToThrow = -//let rec DoTopologicalSort2 -// (independentNodes: PrimitiveWithLocation list) -// (dependentNodes: (PrimitiveWithLocation * PrimitiveWithLocation list) list) +//let rec DoTopologicalSort2 +// (independentNodes: PrimitiveWithLocation list) +// (dependentNodes: (PrimitiveWithLocation * PrimitiveWithLocation list) list) // comparer excToThrow = -let rec DoTopologicalSort2b - (independentNodes: 'a list) - (dependentNodes: ('a * 'b list) list) +let rec DoTopologicalSort2b + (independentNodes: 'a list) + (dependentNodes: ('a * 'b list) list) comparer excToThrow = match independentNodes with | [] -> if List.isEmpty dependentNodes then [] - else - raise(excToThrow dependentNodes) + else + raise(excToThrow dependentNodes) | head::tail -> - let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) + let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) let newDependentNodes = dependentNodes2 |> List.filter(fun (_,list) -> not(List.isEmpty list)) let independentNodes2 = dependentNodes2 |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map fst let newIndependentNodes = independentNodes2 @ tail - head::(DoTopologicalSort2b newIndependentNodes newDependentNodes comparer excToThrow) + head::(DoTopologicalSort2b newIndependentNodes newDependentNodes comparer excToThrow) -let DoTopologicalSort2_noexc - (independentNodes: 'a list) - (dependentNodes: ('a * 'b list) list) +let DoTopologicalSort2_noexc + (independentNodes: 'a list) + (dependentNodes: ('a * 'b list) list) comparer = - let rec DoTopologicalSort3_aux - (independentNodes: 'a list) - (dependentNodes: ('a * 'b list) list) + let rec DoTopologicalSort3_aux + (independentNodes: 'a list) + (dependentNodes: ('a * 'b list) list) comparer ret= match independentNodes with | [] -> ret |> List.rev, dependentNodes | head::tail -> - let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) + let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) let newDependentNodes = dependentNodes2 |> List.filter(fun (_,list) -> not(List.isEmpty list)) let independentNodes2 = dependentNodes2 |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map fst let newIndependentNodes = independentNodes2 @ tail let newRet = head::ret DoTopologicalSort3_aux newIndependentNodes newDependentNodes comparer newRet - let sorted, unsorted = DoTopologicalSort3_aux independentNodes dependentNodes comparer [] + let sorted, unsorted = DoTopologicalSort3_aux independentNodes dependentNodes comparer [] match unsorted with | [] -> Ok sorted - | _ -> Error(unsorted) + | _ -> Error(unsorted) let rec DoTopologicalSort_noexc independentNodes dependentNodes = - DoTopologicalSort2_noexc independentNodes dependentNodes (=) + DoTopologicalSort2_noexc independentNodes dependentNodes (=) -let DoTopologicalSort2 - (independentNodes: 'a list) - (dependentNodes: ('a * 'b list) list) +let DoTopologicalSort2 + (independentNodes: 'a list) + (dependentNodes: ('a * 'b list) list) comparer excToThrow = - let rec DoTopologicalSort3_aux - (independentNodes: 'a list) - (dependentNodes: ('a * 'b list) list) + let rec DoTopologicalSort3_aux + (independentNodes: 'a list) + (dependentNodes: ('a * 'b list) list) comparer excToThrow ret= match independentNodes with | [] -> ret |> List.rev, dependentNodes | head::tail -> - let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) + let dependentNodes2 = dependentNodes |> List.map(fun (n,list) -> (n, list |>List.filter(fun x -> (not (comparer x head))) ) ) let newDependentNodes = dependentNodes2 |> List.filter(fun (_,list) -> not(List.isEmpty list)) let independentNodes2 = dependentNodes2 |> List.filter(fun (_,list) -> List.isEmpty list) |> List.map fst let newIndependentNodes = independentNodes2 @ tail let newRet = head::ret DoTopologicalSort3_aux newIndependentNodes newDependentNodes comparer excToThrow newRet - let sorted, unsorted = DoTopologicalSort3_aux independentNodes dependentNodes comparer excToThrow [] + let sorted, unsorted = DoTopologicalSort3_aux independentNodes dependentNodes comparer excToThrow [] match unsorted with | [] -> sorted - | _ -> raise(excToThrow unsorted) + | _ -> raise(excToThrow unsorted) let ind = ["A";"B";"C"] let dep = [("E",["D";"C"]); ("D",["A";"B"])] //DoTopologicalSort ind dep (fun x -> System.Exception "sdfds") let rec DoTopologicalSort independentNodes dependentNodes excToThrow = - DoTopologicalSort2 independentNodes dependentNodes (=) excToThrow - + DoTopologicalSort2 independentNodes dependentNodes (=) excToThrow + //let rec DoTopologicalSort independentNodes dependentNodes excToThrow = -// DoTopologicalSort2 independentNodes dependentNodes (=) excToThrow +// DoTopologicalSort2 independentNodes dependentNodes (=) excToThrow //let a1 = ["a";"d";"e"] //let a2 = [("b",["c"]); ("c",["b"])] @@ -634,29 +634,29 @@ let PrintLocation loc = sprintf "File:%s, line:%d" loc.srcFilename loc.srcLine /// Generic function which checks an input sequence of strings*location and if there -/// are duplicate values it raises a user exception +/// are duplicate values it raises a user exception -let CheckForDuplicatesCaseCaseInsensitive (sequence:seq) = - let duplicates = sequence - |> Seq.map(fun x -> x.AsTupple) +let CheckForDuplicatesCaseCaseInsensitive (sequence:seq) = + let duplicates = sequence + |> Seq.map(fun x -> x.AsTupple) |> Seq.groupBy(fun (name,loc) -> name.ToLower()) |> Seq.filter(fun (n,dups) -> Seq.length dups > 1) if not(Seq.isEmpty duplicates) then - let duplicateNames = + let duplicateNames = match Seq.toList duplicates with - | (_,dups)::_ -> + | (_,dups)::_ -> let aaa = dups |> Seq.map fst //|> Seq.map(fun n -> n.AsTupple) |> Seq.map fst - aaa |> Seq.StrJoin ", " - | [] -> + aaa |> Seq.StrJoin ", " + | [] -> let inputSeq = sequence |> Seq.map(fun n -> n.AsTupple) |> Seq.map fst |> Seq.StrJoin ", " raise(BugErrorException (sprintf "CheckForDuplicatesCaseCaseInsensitive. Input was %s" inputSeq)) let loc = snd ((snd (duplicates |> Seq.head)) |> Seq.head) let errMsg = sprintf "Duplicate case insensitive definitions within the same scope: %s" duplicateNames raise (SemanticError (loc, errMsg)) -let CheckForDuplicates<'T when 'T :equality> (sequence:seq>) = - let duplicates = sequence - |> Seq.map(fun x -> x.AsTupple) +let CheckForDuplicates<'T when 'T :equality> (sequence:seq>) = + let duplicates = sequence + |> Seq.map(fun x -> x.AsTupple) |> Seq.groupBy(fun (name,loc) -> name) |> Seq.filter(fun (n,dups) -> Seq.length dups > 1) if not(Seq.isEmpty duplicates) then let name = fst ( duplicates |> Seq.head) @@ -665,31 +665,31 @@ let CheckForDuplicates<'T when 'T :equality> (sequence:seq (sequence:seq>) : Result= - let duplicates = sequence - |> Seq.map(fun x -> x.AsTupple) +let CheckForDuplicates2<'T when 'T :equality> (sequence:seq>) : Result= + let duplicates = sequence + |> Seq.map(fun x -> x.AsTupple) |> Seq.groupBy(fun (name,loc) -> name) |> Seq.filter(fun (n,dups) -> Seq.length dups > 1) if not(Seq.isEmpty duplicates) then let name = fst ( duplicates |> Seq.head) let loc = snd ((snd (duplicates |> Seq.head)) |> Seq.head) let errMsg = sprintf "Duplicate definition: %s" (name.ToString()) Error (Semantic_Error (loc, errMsg)) - else + else Ok () let CheckForDuplicatesCI asn1ConstructCheck (lst: StringLoc seq) = - lst |> - Seq.groupBy(fun s -> s.Value.ToLower()) |> - Seq.filter(fun (n,dups) -> Seq.length dups > 1) |> - Seq.iter(fun (_,dups) -> + lst |> + Seq.groupBy(fun s -> s.Value.ToLower()) |> + Seq.filter(fun (n,dups) -> Seq.length dups > 1) |> + Seq.iter(fun (_,dups) -> let head = dups |> Seq.head let dupStr = dups |> Seq.map(fun z -> "'" + z.Value + "'") |> Seq.StrJoin ", " let errMsg = sprintf "Duplicate %s. Values: %s have the same spelling but different case. Use different names to avoid conflicts in case insentive target languages" asn1ConstructCheck dupStr match checkForAdaKeywords () with | false -> () - | true -> raise (SemanticError (head.Location, errMsg)) ) + | true -> raise (SemanticError (head.Location, errMsg)) ) //it throws excToThrow if list2 contains an element that does not exist in list1 @@ -697,7 +697,7 @@ let CompareLists (list1:List) (list2:List) excToThrow = list2 |> Seq.iter(fun s2 ->match list1 |> Seq.exists(fun s1 -> s1.Value = s2.Value) with | false -> raise (excToThrow s2) | true -> ()) - + @@ -706,22 +706,22 @@ let CompareLists (list1:List) (list2:List) excToThrow = //let thanos = // let str = "a-b-c-d" // let parts = str.Split('-') |> Seq.toList |> List.rev -// let res = +// let res = // (parts,[]) |> Seq.unfold (fun (list1,list2) -> match list1 with // | [] -> None -// | x::xs -> +// | x::xs -> // let lst2 = x::list2 // let str = lst2 |> Seq.StrJoin "-" // Some(str,(xs,lst2)) ) |> Seq.toList -// let parts = "a-b-c-d".Split('-') |> Seq.toList +// let parts = "a-b-c-d".Split('-') |> Seq.toList // let rec aux lst = // match lst with // | [] -> [] // | x::xs -> lst::(aux xs) // let res2 = "a-b-c-d".Split('-') |> Seq.toList |> aux |> List.rev |> List.map (Seq.StrJoin "-") -// +// // res -// +// let replaceErrorCodes (initialString:string) (patternToSearch:string) generalErrCode fileIdx initialCount = @@ -734,16 +734,16 @@ let replaceErrorCodes (initialString:string) (patternToSearch:string) generalErr let str1 = stringToProcess.Substring(0,pos1) let str2 = stringToProcess.Substring(pos1 + patternToSearch.Length) let strRep = (generalErrCode<<<28) ||| (fileIdx<<<18) ||| initialCount - sw.Write(str1) - sw.Write(strRep.ToString()) + sw.Write(str1) + sw.Write(strRep.ToString()) replaceErrorCodes_aux str2 (initialCount+1) replaceErrorCodes_aux initialString initialCount let ret = sw.ToString(); sw.Dispose() ret - -let inline getX (x: ^TX) : ^X = + +let inline getX (x: ^TX) : ^X = (^TX : (member get_X : unit -> ^X) (x)) type T1 = { @@ -761,7 +761,7 @@ type T3 = { Z : int } -let inline someFunc (x: ^REC) : int = +let inline someFunc (x: ^REC) : int = let xF = (^REC : (member get_X : unit -> int) (x)) let yF = (^REC : (member get_Y : unit -> int) (x)) xF+yF @@ -783,19 +783,19 @@ let loadXmlFile (validationType:ValidationType) (xmlFileName:string) = settings.ValidationFlags <- settings.ValidationFlags ||| XmlSchemaValidationFlags.ProcessSchemaLocation settings.ValidationFlags <- settings.ValidationFlags ||| XmlSchemaValidationFlags.ReportValidationWarnings let nErrors = ref 0 - settings.ValidationEventHandler.AddHandler((fun s e -> + settings.ValidationEventHandler.AddHandler((fun s e -> let ex = e.Exception :?> System.Xml.Schema.XmlSchemaValidationException Console.WriteLine("{0} '{1}':line {2}, {3}", e.Severity.ToString(), xmlFileName, ex.LineNumber, e.Message) - nErrors := !nErrors + 1 + nErrors := !nErrors + 1 )) let xmlRdr = XmlReader.Create(xmlFileName, settings) - try + try let doc = XDocument.Load(xmlRdr, LoadOptions.SetLineInfo); if !nErrors > 0 then raise(BugErrorException "One or more errors detected in the xml parsing") doc with - | exc -> + | exc -> Console.Error.WriteLine("Error in file: {0}", xmlFileName) raise exc @@ -810,12 +810,12 @@ let getResourceAsString0 (resourcePrefix:string) (assembly:Reflection.Assembly) let msg = sprintf "Resource '%s' not found!\nAvailable resources are\n%A" compositeResourceName names raise (UserException msg) | Some _ -> - let resource = assembly.GetManifestResourceStream compositeResourceName + let resource = assembly.GetManifestResourceStream compositeResourceName use memStrm = new MemoryStream () resource.CopyTo(memStrm) System.Text.Encoding.UTF8.GetString(memStrm.ToArray()) - - + + let getResourceAsByteArray0 (resourcePrefix:string) (assembly:Reflection.Assembly) (rsName:string) = //let projName = "asn1scc" //let assembly = System.Reflection.Assembly.GetExecutingAssembly() @@ -826,7 +826,7 @@ let getResourceAsByteArray0 (resourcePrefix:string) (assembly:Reflection.Assembl let msg = sprintf "Resource '%s' not found!\nAvailable resources are\n%A" compositeResourceName names raise (UserException msg) | Some _ -> - let resource = assembly.GetManifestResourceStream compositeResourceName + let resource = assembly.GetManifestResourceStream compositeResourceName use memStrm = new MemoryStream () resource.CopyTo(memStrm) memStrm.ToArray() @@ -843,7 +843,7 @@ let TL subSystem func = let totalElapsed = stopwatch.Elapsed match subsystems.ContainsKey subSystem with - | true -> + | true -> let (oc, ts) = subsystems.[subSystem] subsystems.[subSystem] <- (oc+1, ts+totalElapsed) | false -> @@ -853,18 +853,18 @@ let TL subSystem func = let TL_report () = let StrJoin_priv str listItems = - if Seq.isEmpty listItems then + if Seq.isEmpty listItems then "" else listItems |> Seq.map(fun x -> x.ToString()) |> Seq.reduce(fun agr el -> agr + str + el.ToString()) let aaa = subsystems.Keys |> Seq.toList - let bbb = - aaa |> - List.map(fun z -> + let bbb = + aaa |> + List.map(fun z -> let (a,b) = subsystems.[z] sprintf "%s nCall %d = took %A" z a b) |> StrJoin_priv "\n" printfn "%s" bbb - + diff --git a/CommonTypes/SimpleSets.fs b/CommonTypes/SimpleSets.fs index a5ab048c6..6193aade4 100644 --- a/CommonTypes/SimpleSets.fs +++ b/CommonTypes/SimpleSets.fs @@ -18,51 +18,51 @@ type SsRangeSetDefinition<'v> = { type SsRangeSet<'v when 'v : comparison> = { ranges : SsRange<'v> list setDef : SsRangeSetDefinition<'v> -} +} with member this.isEmpty = this.ranges.IsEmpty //let fullIntegerSet = {Range<'v>.a = bigint Int64.MinValue; b = bigint Int64.MaxValue} -let range_within (r:SsRange<'v>) v = +let range_within (r:SsRange<'v>) v = r.a <= v && v <= r.b - + let range_intersect (r1:SsRange<'v>) (r2:SsRange<'v>) = -(* +(* --- r2 ---- --- r1 --- -*) - match r2.b < r1.a with +*) + match r2.b < r1.a with | true -> None - | false -> -(* + | false -> +(* --- r2 ---- --- r1 --- -*) +*) match r2.a <= r1.a && r1.a <= r2.b && r2.b <= r1.b with - | true -> Some({SsRange.a = r1.a; b = r2.b}) - | false -> -(* + | true -> Some({SsRange.a = r1.a; b = r2.b}) + | false -> +(* ---------- r2 -------- --- r1 --- -*) +*) match r2.a <= r1.a && r2.b > r1.b with | true -> Some r1 - | false -> -(* + | false -> +(* --- r2 ---- ----- r1 ------ -*) +*) match r1.a <= r2.a && r2.b <= r1.b with | true -> Some r2 | false -> -(* +(* --- r2 ---- --- r1 --- -*) +*) match r1.a <= r2.a && r2.a <= r1.b && r1.b <= r2.b with | true -> Some {SsRange.a = r2.a; b = r1.b} | false -> None @@ -70,13 +70,13 @@ let range_intersect (r1:SsRange<'v>) (r2:SsRange<'v>) = let range_union (r1:SsRange<'v>) (r2:SsRange<'v>) = match r2.b < r1.a with | true -> Some r2, Some r1 - | false -> + | false -> match r2.a <= r1.a && r1.a <= r2.b && r2.b <= r1.b with | true -> Some {SsRange.a = r2.a; b = r1.b}, None - | false -> + | false -> match r2.a <= r1.a && r2.b > r1.b with | true -> Some r2, None - | false -> + | false -> match r1.a <= r2.a && r2.b <= r1.b with | true -> Some r1, None | false -> @@ -89,7 +89,7 @@ let range_union2 (r1:SsRange<'v>) (r2:SsRange<'v>) = | None, None -> [] | Some x, None -> [x] | None, Some x -> [x] - | Some x, Some y -> [x;y] + | Some x, Some y -> [x;y] let range_complement (d:SsRangeSetDefinition<'v>) (r2:SsRange<'v>) = let u = d.universe @@ -108,14 +108,14 @@ let range_complement2 (d:SsRangeSetDefinition<'v>) (r2:SsRange<'v>) = | None, None -> [] | Some x, None -> [x] | None, Some x -> [x] - | Some x, Some y -> [x;y] + | Some x, Some y -> [x;y] let range_difference (d:SsRangeSetDefinition<'v>) (r1:SsRange<'v>) (r2:SsRange<'v>) = // A - B = A intersection (Complement B) let r2Complement = range_complement d r2 match r2Complement with | None, None -> None, None - | Some r2c, None + | Some r2c, None | None, Some r2c -> range_intersect r1 r2c, None | Some r2c, Some r2d -> let r1a = range_intersect r1 r2c @@ -124,14 +124,14 @@ let range_difference (d:SsRangeSetDefinition<'v>) (r1:SsRange<'v>) (r2:SsRange<' | None, None -> None, None | Some x, None -> Some x, None | None, Some x -> Some x, None - | Some a, Some b ->range_union a b - + | Some a, Some b ->range_union a b + let set_add_range (s1:SsRangeSet<'v> ) (r2: SsRange<'v>) = let before = s1.ranges |> List.filter(fun r1 -> r1.b < r2.a) let after = s1.ranges |> List.filter(fun r1 -> r2.b < r1.a) let middleRanges = s1.ranges |> List.filter(fun r1 -> not (r1.b < r2.a)) |> List.filter(fun r1 -> not (r2.b < r1.a)) let midleRange = - middleRanges |> + middleRanges |> List.fold(fun st r -> (range_union2 st r).Head ) r2 {s1 with ranges = (before@[midleRange]@after)} @@ -143,22 +143,22 @@ let range_set_intersect (s1:SsRangeSet<'v>) (s2:SsRangeSet<'v>) = yield range_intersect r1 r2 } |> Seq.toList ranges |> List.choose id |> List.fold(fun set r -> set_add_range set r ) ({s1 with ranges = []}) - + let range_set_union (s1:SsRangeSet<'v>) (s2:SsRangeSet<'v>) = s1.ranges |> List.fold(fun set r -> set_add_range set r) s2 let range_set_complement (s:SsRangeSet<'v>) = - s.ranges |> - List.fold(fun set r -> + s.ranges |> + List.fold(fun set r -> let comp = {s with ranges = range_complement2 set.setDef r} range_set_intersect set comp) ({s with ranges = [s.setDef.universe]}) -let range_set_difference s1 s2= +let range_set_difference s1 s2= // A - B = A intersection (Complement B) - range_set_intersect s1 (range_set_complement s2) + range_set_intersect s1 (range_set_complement s2) -type SsRangeSet<'v when 'v : equality> with +type SsRangeSet<'v when 'v : comparison> with member this.Complement = range_set_complement this member this.union other = range_set_union this other member this.intersect other = range_set_intersect this other @@ -173,7 +173,7 @@ type SsValueSet<'v when 'v : comparison> = | SsEmpty | SsValues of Set<'v> | SsExceptValues of (Set<'v>) -with +with member this.isEmpty = this = SsEmpty member this.isUniverse = this = SsUniverse @@ -196,8 +196,8 @@ let value_set_complement (s:SsValueSet<'v>) = | SsExceptValues s1 -> SsValues s1 - - + + let keepCommonElemnts s1 (s2:Set<'v>) = @@ -207,60 +207,60 @@ let unionSet s1 (s2:Set<'v>) = s1 |> Set.fold(fun (ns:Set<'v>) v -> ns.Add v) s2 -let value_set_difference s1 s2= +let value_set_difference s1 s2= match (fixSet s1), (fixSet s2) with | SsEmpty , _ -> SsEmpty | _ , SsEmpty -> s1 | _ , SsUniverse -> SsEmpty | SsUniverse , SsValues s2 -> SsExceptValues s2 | SsUniverse , SsExceptValues s2 -> SsValues s2 - + | SsValues a1 , SsValues a2 -> fixSet (SsValues (a1 |> Set.filter(fun v -> not (a2.Contains v)))) - | SsValues b , SsExceptValues a -> + | SsValues b , SsExceptValues a -> //B-A = Intesect(Complement(A), B) fixSet (SsValues (a |> Set.filter(fun v -> b.Contains v))) | SsExceptValues a1 , SsValues a2 -> fixSet (SsExceptValues (a1 |> Set.fold(fun ns v -> ns.Add v) a2)) - | SsExceptValues a1 , SsExceptValues a2 -> + | SsExceptValues a1 , SsExceptValues a2 -> //B-A = Intesect(Complement(A), B) fixSet(SsValues (a2 |> Set.filter(fun v -> not (a1.Contains v)))) -let value_set_intersection s1 s2= +let value_set_intersection s1 s2= match (fixSet s1), (fixSet s2) with | SsEmpty , _ -> SsEmpty | _ , SsEmpty -> SsEmpty | SsUniverse , _ -> s2 | _ , SsUniverse -> s1 | SsValues a1 , SsValues a2 -> fixSet (SsValues (keepCommonElemnts a1 a2)) - | SsExceptValues a1 , SsExceptValues a2 -> fixSet (SsExceptValues (unionSet a1 a2)) - | SsValues b , SsExceptValues a -> - //Intesect(B, Complement(A)) = B - A + | SsExceptValues a1 , SsExceptValues a2 -> fixSet (SsExceptValues (unionSet a1 a2)) + | SsValues b , SsExceptValues a -> + //Intersect(B, Complement(A)) = B - A value_set_difference s1 (SsValues a) - | SsExceptValues a1 , SsValues a2 -> - //Intesect(Complement(A), B) = B - A + | SsExceptValues a1 , SsValues a2 -> + //Intersect(Complement(A), B) = B - A value_set_difference s2 (SsValues a1) -let value_set_union s1 s2= +let value_set_union s1 s2= match (fixSet s1), (fixSet s2) with | SsEmpty , _ -> s2 | _ , SsEmpty -> s1 | SsUniverse , _ -> SsUniverse | _ , SsUniverse -> SsUniverse | SsValues a1 , SsValues a2 -> fixSet (SsValues (unionSet a1 a2)) - | SsExceptValues a1 , SsExceptValues a2 -> fixSet (SsExceptValues (keepCommonElemnts a1 a2)) - | SsValues a , SsExceptValues b -> + | SsExceptValues a1 , SsExceptValues a2 -> fixSet (SsExceptValues (keepCommonElemnts a1 a2)) + | SsValues a , SsExceptValues b -> //Union (A, Complement(B)) = Complement (B -A) value_set_complement (value_set_difference (SsValues b) s1) - | SsExceptValues B , SsValues A -> + | SsExceptValues B , SsValues A -> //Union (Complement(B), A ) = Complement (B -A) value_set_complement (value_set_difference (SsValues B) s2) -type SsValueSet<'v when 'v : comparison> with +type SsValueSet<'v when 'v : comparison> with member this.Complement = value_set_complement this member this.union other = value_set_union this other member this.intersect other = value_set_intersection this other member this.difference other = value_set_difference this other - + (* let s1 = SsValues(set [1;2;3;4] ) @@ -276,7 +276,7 @@ let s_i = value_set_intersection s1 s2 type SsInfSet<'v when 'v : comparison> = | SsValues of Set<'v> | SsAll - + let SsInfSet_union (s1:SsInfSet<'v>) (s2:SsInfSet<'v>) = match s1,s2 with @@ -291,7 +291,7 @@ let SsInfSet_intersect (s1:SsInfSet<'v>) (s2:SsInfSet<'v>) = | SsAll, SsValues _ -> s2 | SsValues _, SsAll -> s1 | SsValues ss1, SsValues ss2 -> SsValues (ss1 |> Set.filter(fun v -> ss2.Contains v) ) - + type SsValueSet<'v when 'v : comparison> = { @@ -311,7 +311,7 @@ let value_set_intersect (s1:SsValueSet<'v>) (s2:SsValueSet<'v>) = | SsAll -> Set.empty | SsValues exc -> ss1 |> Set.filter(fun v -> not (exc.Contains v)) {SsValueSet.values = SsValues newSs1; ecxeptValues = newEcxeptValues} - + let value_set_union (s1:SsValueSet<'v>) (s2:SsValueSet<'v>) = let newEcxeptValues = SsInfSet_union s1.ecxeptValues s2.ecxeptValues @@ -332,9 +332,9 @@ let value_set_complement (s:SsValueSet<'v>) = {SsValueSet.values = s.ecxeptValues; ecxeptValues = s.values} -let value_set_difference s1 s2= +let value_set_difference s1 s2= // A - B = A intersection (Complement B) - value_set_intersect s1 (value_set_complement s2) + value_set_intersect s1 (value_set_complement s2) *) @@ -352,7 +352,7 @@ let nextChar (c:System.Char) = let prevChar (c:System.Char) = System.Convert.ToChar(System.Convert.ToInt32(c)-1) -let charRangeSetDef = +let charRangeSetDef = { universe = {SsRange.a= System.Convert.ToChar(0) ;b= System.Convert.ToChar(127)}; prefFunc = prevChar; nextFunc = nextChar} @@ -382,7 +382,7 @@ let createDefaultCharSet () = {CharSet.ranges = [charRangeSetDef.universe]; setD type SizeSet = SsRangeSet let createDefaultSizeSet () = {SizeSet.ranges = [posInt32RangeSetDef.universe]; setDef = posInt32RangeSetDef} -let createSizeDet minSize maxSize = +let createSizeDet minSize maxSize = let newUniverse = {SsRange.a=minSize; b=maxSize} {SizeSet.ranges = [newUniverse]; setDef = {posInt32RangeSetDef with universe = newUniverse} } @@ -391,8 +391,8 @@ type SingleStringSet = { charSet : CharSet option values : SsValueSet option } -with - member this.isEmpty = +with + member this.isEmpty = match this.sizeRange, this.charSet, this.values with | Some s, Some c, Some v -> s.isEmpty && c.isEmpty && v.isEmpty | _ -> false @@ -400,14 +400,14 @@ with type MultiStringSet = SingleStringSet list // union -let SingleStringSet_set_complement (ss:SingleStringSet) = +let SingleStringSet_set_complement (ss:SingleStringSet) = { SingleStringSet.sizeRange = ss.sizeRange |> Option.map (fun sr -> sr.Complement) charSet = ss.charSet |> Option.map (fun sr -> sr.Complement) values = ss.values |> Option.map (fun sr -> sr.Complement) } -let SingleStringSet_set_intersection (s1:SingleStringSet) (s2:SingleStringSet) = +let SingleStringSet_set_intersection (s1:SingleStringSet) (s2:SingleStringSet) = let newSizeRange = match s1.sizeRange, s2.sizeRange with @@ -433,7 +433,7 @@ let SingleStringSet_set_intersection (s1:SingleStringSet) (s2:SingleStringSet) = {SingleStringSet.sizeRange = newSizeRange; charSet = newCharSet; values = newValues} -let SingleStringSet_set_union (s1:SingleStringSet) (s2:SingleStringSet) : MultiStringSet= +let SingleStringSet_set_union (s1:SingleStringSet) (s2:SingleStringSet) : MultiStringSet= match s1.sizeRange, s1.charSet, s1.values, s2.sizeRange, s2.charSet, s2.values with | None, None, None, _,_,_ -> [s2] | _, _,_, None, None, None -> [s1] @@ -445,11 +445,11 @@ let SingleStringSet_set_union (s1:SingleStringSet) (s2:SingleStringSet) : MultiS let MultiStringSet_set_add_SingleStringSet (ms:MultiStringSet) (ss:SingleStringSet) = match ms |> List.tryFindIndex(fun s0 -> List.length (SingleStringSet_set_union s0 ss) = 1) with | None -> ss::ms - | Some idx -> + | Some idx -> let arr = ms |> List.toArray let p1 = (arr.[0..idx-1]) |> Seq.toList let p2 = SingleStringSet_set_union (arr.[idx-1]) ss - let p3 = + let p3 = match idx+1 <= arr.Length with | true -> arr.[idx+1 .. arr.Length] |> Seq.toList | false -> [] @@ -458,10 +458,10 @@ let MultiStringSet_set_add_SingleStringSet (ms:MultiStringSet) (ss:SingleStringS let MultiStringSet_set_intersect_SingleStringSet (ms:MultiStringSet) (ss:SingleStringSet) : MultiStringSet= ms |> List.map(fun mss0 -> SingleStringSet_set_intersection mss0 ss) |> List.filter (fun z -> not z.isEmpty) -let MultiStringSet_set_union (s1:MultiStringSet) (s2:MultiStringSet) : MultiStringSet= +let MultiStringSet_set_union (s1:MultiStringSet) (s2:MultiStringSet) : MultiStringSet= s1 |> List.fold(fun newSet sss -> MultiStringSet_set_add_SingleStringSet newSet sss) s2 - -let MultiStringSet_set_intersect (s1:MultiStringSet) (s2:MultiStringSet) : MultiStringSet= + +let MultiStringSet_set_intersect (s1:MultiStringSet) (s2:MultiStringSet) : MultiStringSet= s1 |> List.fold(fun newSet sss -> MultiStringSet_set_intersect_SingleStringSet newSet sss) s2 diff --git a/CommonTypes/SizeableSet.fs b/CommonTypes/SizeableSet.fs index bd232a16a..718b7459f 100644 --- a/CommonTypes/SizeableSet.fs +++ b/CommonTypes/SizeableSet.fs @@ -8,7 +8,7 @@ type OneOrTwo<'T> = | One of 'T | Two of 'T*'T | Three of 'T*'T*'T -with +with member this.toList = match this with | One a -> [a] @@ -19,7 +19,7 @@ type Range2d<'v when 'v : equality> = { sizeSet : Range valueSet : ValueSet<'v> } -with +with member this.intersect (other:Range2d<'v>) = {this with sizeSet = this.sizeSet.intersect other.sizeSet; valueSet = this.valueSet.intersect other.valueSet} member this.isEmpty = @@ -34,19 +34,19 @@ with member this.complement = match this.sizeSet = Range_Universe, this.valueSet.isUniverse with | true, true -> One (Range2d<'v>.createEmptySet()) - | false, true -> + | false, true -> match this.sizeSet.complement with | RangeSets.One sizeComplement -> One ({this with sizeSet = sizeComplement; valueSet = SsUniverse}) | RangeSets.Two (s1Comp, s2Comp) -> Two ({this with sizeSet = s1Comp; valueSet = SsUniverse}, {this with sizeSet = s2Comp; valueSet = SsUniverse}) | true, false -> One ({this with sizeSet = (Range_Universe); valueSet = this.valueSet.complement}) - | false, false -> + | false, false -> match this.sizeSet.complement with | RangeSets.One sizeComplement -> Two ({this with sizeSet = sizeComplement; valueSet = SsUniverse}, {this with sizeSet = (Range_Universe); valueSet = this.valueSet.complement}) | RangeSets.Two (s1Comp, s2Comp) -> Three ( - {this with sizeSet = s1Comp; valueSet = SsUniverse}, - {this with sizeSet = s2Comp; valueSet = SsUniverse}, + {this with sizeSet = s1Comp; valueSet = SsUniverse}, + {this with sizeSet = s2Comp; valueSet = SsUniverse}, {this with sizeSet = Range_Universe; valueSet = this.valueSet.complement}) @@ -62,15 +62,15 @@ with | [] -> (Range2D (Range2d<'v>.createEmptySet ())) | r1::[] -> Range2D r1 | r1::r2::rest -> Range2DCollection (r1,r2,rest) - static member createUniverse = + static member createUniverse = Range2D ({sizeSet = Range_Universe; valueSet = SsUniverse}) - static member createFromSingleValue v = + static member createFromSingleValue v = Range2D ({sizeSet = Range_Universe; valueSet = ValueSet<'v>.createFromSingleValue v}) - static member createFromSizeRange rangeSet = + static member createFromSizeRange rangeSet = match rangeSet with | Range r -> Range2D ({sizeSet = r; valueSet = SsUniverse}) | RangeCollection(r1,r2,rs) -> Range2DCollection( ({sizeSet = r1; valueSet = SsUniverse}, {sizeSet = r2; valueSet = SsUniverse}, rs |> List.map(fun r -> {sizeSet = r; valueSet = SsUniverse}))) - + member this.intersect (other:SizeableSet<'v>) = @@ -86,23 +86,21 @@ with member this.complement = match this with - | Range2D r -> + | Range2D r -> match r.complement with | One rc -> Range2D rc | Two (rc1,rc2) -> Range2DCollection(rc1,rc2, []) | Three (rc1,rc2, rc3) -> Range2DCollection(rc1,rc2, [rc3]) - | Range2DCollection (r1,r2,rest) -> - r1::r2::rest |> - List.map(fun r -> (Range2D r).complement) |> - List.fold(fun newRange curR -> + | Range2DCollection (r1,r2,rest) -> + r1::r2::rest |> + List.map(fun r -> (Range2D r).complement) |> + List.fold(fun newRange curR -> newRange.intersect curR ) (Range2D (Range2d<'v>.createUniverse ())) member this.difference (other:SizeableSet<'v>) = other.complement.intersect this member this.union (other:SizeableSet<'v>) = - let b = true - match b with true -> () //not implemented yet this - + diff --git a/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.adb b/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.adb index fc34f6ae7..96e53c471 100644 --- a/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.adb +++ b/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.adb @@ -7,7 +7,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin BitStream_Encode_Non_Negative_Integer (bs, IntVal, sizeInBits); end Acn_Enc_Int_PositiveInteger_ConstSize; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_8(bs : in out BitStream; IntVal : in Asn1UInt) is begin @@ -31,13 +31,13 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin Enc_UInt (bs, IntVal, 8); end Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N (bs : in out BitStream; IntVal : in Asn1UInt; total_bytes : in Integer) with Depends => (bs => (bs, IntVal, total_bytes)), - Pre => total_bytes >= 0 and then - total_bytes <= Asn1UInt'Size/8 and then - bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then + Pre => total_bytes >= 0 and then + total_bytes <= Asn1UInt'Size/8 and then + bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - total_bytes*8, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 @@ -52,38 +52,38 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is tmp := tmp / 256; end loop; end Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N; - - + + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16 (bs : in out BitStream; IntVal : in Asn1UInt) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, 2); end Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32 (bs : in out BitStream; IntVal : in Asn1UInt) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, 4); end Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64 (bs : in out BitStream; IntVal : in Asn1UInt) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, 8); end Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64; - + procedure Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1UInt) is begin Enc_SemiConstraintPosWholeNumber (bs, IntVal, 0); end Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded; - + procedure Acn_Enc_Int_TwosComplement_ConstSize (bs : in out BitStream; IntVal : in Asn1Int; sizeInBits : in Natural) is begin BitStream_Encode_Non_Negative_Integer (bs, To_UInt (IntVal), sizeInBits); end Acn_Enc_Int_TwosComplement_ConstSize; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_8(bs : in out BitStream; IntVal : in Asn1Int) is @@ -91,8 +91,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is --Acn_Enc_Int_TwosComplement_ConstSize (bs, IntVal, 8); BitStream_AppendByte(bs, Asn1Byte(To_UInt(IntVal) and 16#FF#) , false); end Acn_Enc_Int_TwosComplement_ConstSize_8; - - + + procedure Acn_Enc_Int_TwosComplement_ConstSize_big_endian_16 (bs : in out BitStream; IntVal : in Asn1Int) is begin @@ -110,37 +110,37 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin Enc_UInt (bs, To_UInt(IntVal), 8); end Acn_Enc_Int_TwosComplement_ConstSize_big_endian_64; - - + + procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16 (bs : in out BitStream; IntVal : in Asn1Int) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, To_UInt(IntVal), 2); end Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32 (bs : in out BitStream; IntVal : in Asn1Int) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, To_UInt(IntVal), 4); end Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64 (bs : in out BitStream; IntVal : in Asn1Int) is begin Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_N(bs, To_UInt(IntVal), 8); end Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64; - + procedure Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1Int) is begin Enc_UnConstraintWholeNumber (bs, IntVal); end Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded; - + -- subtype OctetArray100 is OctetBuffer (1..100); - - procedure Acn_Enc_Int_BCD_ConstSize (bs : in out BitStream; IntVal : in Asn1UInt; nNibbles : in Integer) - + + procedure Acn_Enc_Int_BCD_ConstSize (bs : in out BitStream; IntVal : in Asn1UInt; nNibbles : in Integer) + is intValCopy : Asn1UInt := IntVal; powOf10 : Asn1UInt; @@ -154,8 +154,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is BitStream_AppendPartialByte (bs, curNibble, 4, False); end loop; end Acn_Enc_Int_BCD_ConstSize; - - + + procedure Acn_Enc_Int_BCD_VarSize_NullTerminated (bs : in out BitStream; IntVal : in Asn1UInt) is totalNibbles : Integer; @@ -164,8 +164,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Acn_Enc_Int_BCD_ConstSize(bs, IntVal, totalNibbles); BitStream_AppendPartialByte (bs, 16#F#, 4, False); end Acn_Enc_Int_BCD_VarSize_NullTerminated; - - + + procedure Get_integer_digits(IntVal :in Asn1Uint; digits_array: out Digits_Buffer; totalDigits : out Asn1Byte) with Post => totalDigits >=1 and totalDigits<=20 and totalDigits = Asn1Byte(Get_number_of_digits(IntVal)) is @@ -182,7 +182,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is digits_array(i) := Asn1Byte(Character'Pos ('0') + curNibble); end loop; end Get_integer_digits; - + procedure Acn_Enc_Int_ASCII_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1Int) is digits_array: Digits_Buffer; @@ -191,7 +191,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is absIntVal : Asn1Uint; begin - + absIntVal := Asn1Uint(abs IntVal); sing := (if intVal >= 0 then Character'Pos('+') else Character'Pos('-')); Get_integer_digits(absIntVal,digits_array, nChars); @@ -210,7 +210,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end Acn_Enc_Int_ASCII_VarSize_LengthEmbedded; - + procedure Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1UInt) is digits_array: Digits_Buffer; @@ -225,9 +225,9 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8); BitStream_AppendByte(bs, digits_array(i), False); end loop; - + end Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded; - + procedure Acn_Enc_Int_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal : in Asn1Int; nullChars : in OctetBuffer) is digits_array: Digits_Buffer; @@ -250,7 +250,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is -- encode nullChar for i in nullChars'Range loop - pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-nullChars'First)*8); + pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-nullChars'First)*8); BitStream_AppendByte(bs, nullChars(i), False); end loop; @@ -272,15 +272,15 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is -- encode nullChar for i in nullChars'Range loop - pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-nullChars'First)*8); + pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-nullChars'First)*8); BitStream_AppendByte(bs, nullChars(i), False); end loop; end Acn_Enc_UInt_ASCII_VarSize_NullTerminated; - - + + ---------------------- Decoding functions ------------------------------------------ - + procedure Acn_Dec_Int_PositiveInteger_ConstSize (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nSizeInBits : in Integer; Result: out ASN1_RESULT) is encVal : Asn1UInt; @@ -296,15 +296,15 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.ErrorCode := ERR_INCORRECT_STREAM; end if; end Acn_Dec_Int_PositiveInteger_ConstSize; - - - + + + procedure Acn_Dec_Int_PositiveInteger_ConstSize_8 (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is begin Acn_Dec_Int_PositiveInteger_ConstSize(bs, IntVal, minVal, maxVal, 8, Result); end Acn_Dec_Int_PositiveInteger_ConstSize_8; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16 (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is @@ -317,7 +317,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin Acn_Dec_Int_PositiveInteger_ConstSize(bs, IntVal, minVal, maxVal, 32, Result); end Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64 (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is begin @@ -329,15 +329,15 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.ErrorCode := ERR_INCORRECT_STREAM; end if; end Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N0 (bs : in out BitStream; IntVal : out Asn1UInt; total_bytes : in Integer) with - Pre => total_bytes >= 0 and then - total_bytes <= Asn1UInt'Size/8 and then - bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then + Pre => total_bytes >= 0 and then + total_bytes <= Asn1UInt'Size/8 and then + bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - total_bytes*8, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 is byteValue : Asn1Byte; result : Asn1Boolean; @@ -353,14 +353,14 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N0; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT; total_bytes : in Integer) with - Pre => total_bytes >= 0 and then - total_bytes <= Asn1UInt'Size/8 and then - bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then + Pre => total_bytes >= 0 and then + total_bytes <= Asn1UInt'Size/8 and then + bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - total_bytes*8, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) is @@ -374,28 +374,28 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.ErrorCode := ERR_INCORRECT_STREAM; end if; end Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N; - - procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) + + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is begin Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 2); end Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16; - - procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) + + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is begin Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 4); end Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32; - procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is begin Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 8); end Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64; - - - + + + procedure Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; Result : out ASN1_RESULT) is NBytes : Asn1Byte; @@ -405,7 +405,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is IntVal := minVal; Result.ErrorCode := 0; BitStream_DecodeByte(bs, NBytes, Result.Success); - + if Result.Success and NBytes >= 1 and NBytes <= 8 then Dec_UInt (bs, Integer (NBytes), Ret, Result.Success); pragma Assert(Result.Success); @@ -420,7 +420,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.Success := False; end if; end Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded; - + procedure Acn_Dec_Int_TwosComplement_ConstSize (bs : in out BitStream; IntVal : out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; nSizeInBits : in Integer; Result : out ASN1_RESULT) is encVal : Asn1UInt; @@ -439,8 +439,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.ErrorCode := ERR_INCORRECT_STREAM; end if; end Acn_Dec_Int_TwosComplement_ConstSize; - - + + procedure Acn_Dec_Int_TwosComplement_ConstSize_8 (bs : in out BitStream; IntVal : out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) is begin @@ -472,21 +472,21 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is IntVal := minVal; Result.ErrorCode := ERR_INCORRECT_STREAM; end if; - end Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64; - - + end Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64; + + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_N (bs : in out BitStream; IntVal : out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT; total_bytes : in Integer) with - Pre => total_bytes > 0 and then - total_bytes <= Asn1Int'Size/8 and then - bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then + Pre => total_bytes > 0 and then + total_bytes <= Asn1Int'Size/8 and then + bs.Current_Bit_Pos < Natural'Last - total_bytes*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - total_bytes*8, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + total_bytes*8 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) is encValue :Asn1UInt; - + begin Result.ErrorCode := 0; Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_N0(bs, encValue, total_bytes); @@ -497,41 +497,41 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.ErrorCode := ERR_INCORRECT_STREAM; end if; end Acn_Dec_Int_TwosComplement_ConstSize_little_endian_N; - - procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) + + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) is begin Acn_Dec_Int_TwosComplement_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 2); end Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16; - - procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) + + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) is begin Acn_Dec_Int_TwosComplement_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 4); end Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32; - procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) is begin Acn_Dec_Int_TwosComplement_ConstSize_little_endian_N(bs, IntVal, minVal, maxVal, Result, 8); end Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64; - + procedure Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded (bs : in out BitStream; IntVal :out Asn1Int; Result : out ASN1_RESULT) is begin Result.ErrorCode := ERR_INCORRECT_STREAM; Dec_UnConstraintWholeNumber (bs, IntVal, Result.Success); end Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded; - - + + procedure Acn_Dec_Int_BCD_ConstSize (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nNibbles : in Integer; Result : out ASN1_RESULT) is digit : Asn1Byte; begin IntVal := 0; Result := ASN1_RESULT'(Success => True, ErrorCode => 0); - + for i in 1..nNibbles loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*4); BitStream_ReadNibble (bs, digit, Result.Success); @@ -543,14 +543,14 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; exit when not Result.Success; end loop; - + Result.Success := Result.Success and then ((IntVal >= minVal) and (IntVal <= maxVal)); if not Result.Success then result.ErrorCode := ERR_INCORRECT_STREAM; IntVal := minVal; end if; end Acn_Dec_Int_BCD_ConstSize; - + procedure Acn_Dec_Int_BCD_VarSize_NullTerminated (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) is @@ -558,7 +558,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin IntVal := 0; Result := ASN1_RESULT'(Success => True, ErrorCode => 0); - + for i in 1..19 loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*4); BitStream_ReadNibble (bs, digit, Result.Success); @@ -570,22 +570,22 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; exit when digit = 16#F# or not Result.Success; end loop; - + if Result.Success and (not (digit = 16#F#)) then BitStream_ReadNibble (bs, digit, Result.Success); Result.Success := digit = 16#F# and then ((IntVal >= minVal) and (IntVal <= maxVal)); else Result.Success := Result.Success and then ((IntVal >= minVal) and (IntVal <= maxVal)); end if; - - + + if not Result.Success then result.ErrorCode := ERR_INCORRECT_STREAM; IntVal := minVal; end if; end Acn_Dec_Int_BCD_VarSize_NullTerminated; - - + + procedure Acn_Enc_Int_ASCII_ConstSize (bs : in out BitStream; IntVal : in Asn1Int; nChars : in Integer) is digits_array: Digits_Buffer; @@ -596,9 +596,9 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is --pragma assert (intVal > -Asn1Int(Powers_of_10(nChars))); --pragma assert (intVal < Asn1Int(Powers_of_10(nChars))); --pragma assert (abs IntVal < Asn1Int(Powers_of_10(nChars))); - + absIntVal := abs_value(IntVal); - --pragma assert (absIntVal < Powers_of_10(nChars)); + --pragma assert (absIntVal < Powers_of_10(nChars)); sing := (if intVal >= 0 then Character'Pos('+') else Character'Pos('-')); Get_integer_digits(absIntVal,digits_array, nDigits); --pragma assert(absIntVal < Powers_of_10(nChars)); @@ -612,14 +612,14 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8); BitStream_AppendByte(bs, Character'Pos ('0'), False); end loop; - + -- encode digits for i in 1..Integer(nDigits) loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8); BitStream_AppendByte(bs, digits_array(i), False); end loop; end Acn_Enc_Int_ASCII_ConstSize; - + procedure Acn_Dec_Int_ASCII_ConstSize (bs : in out BitStream; IntVal: out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; nChars : in Integer; Result : out ASN1_RESULT) is @@ -634,7 +634,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result := ASN1_RESULT'(Success => digit = Character'Pos ('+') or digit = Character'Pos ('-'), ErrorCode => ERR_INCORRECT_STREAM); if result.Success then - + negative := digit = Character'Pos ('-'); for i in 1..nChars-1 loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8 ); @@ -642,7 +642,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma Assert (Result.Success); Ch := Character'Val (digit); intDigit := Character'Pos (Ch) - Character'Pos ('0'); - + Result.Success := intDigit >=0 and intDigit <= 9; if Result.Success then uval := uval * 10; @@ -653,7 +653,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; if Result.Success then IntVal := (if negative and uval > 0 then (-Asn1Int(uval-1) - 1) else Asn1Int(uval)); - + Result.Success := Result.Success and then ((IntVal >= minVal) and (IntVal <= maxVal)); if not Result.Success then result.ErrorCode := ERR_INCORRECT_STREAM; @@ -667,11 +667,11 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is result.ErrorCode := ERR_INCORRECT_STREAM; IntVal := minVal; end if; - - + + end Acn_Dec_Int_ASCII_ConstSize; - - + + procedure Acn_Enc_UInt_ASCII_ConstSize (bs : in out BitStream; IntVal : in Asn1Uint; nChars : in Integer) is digits_array: Digits_Buffer; @@ -687,15 +687,15 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8); BitStream_AppendByte(bs, Character'Pos ('0'), False); end loop; - + -- encode digits for i in 1..Integer(nDigits) loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8); BitStream_AppendByte(bs, digits_array(i), False); end loop; end Acn_Enc_UInt_ASCII_ConstSize; - - + + procedure Acn_Dec_UInt_ASCII_ConstSize (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nChars : in Integer; Result : out ASN1_RESULT) is digit : Asn1Byte; @@ -719,19 +719,19 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; exit when not Result.Success; end loop; - - + + Result.Success := Result.Success and then ((IntVal >= minVal) and (IntVal <= maxVal)); - - + + if not Result.Success then result.ErrorCode := ERR_INCORRECT_STREAM; IntVal := minVal; end if; - - + + end Acn_Dec_UInt_ASCII_ConstSize; - + procedure Acn_Dec_UInt_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal: out Asn1UInt; nullChars: in OctetBuffer; Result : out ASN1_RESULT) is @@ -749,24 +749,24 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma Assert (Result.Success); tmp(i + tmp'First - nullChars'First) := digit; end loop; - + pragma Assert (tmp'First = 1); pragma Assert (tmp'Last = 10); - + for i in 1..20 loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-1)*8 and nullChars'First=1 and tmp'First = 1); digit := tmp(tmp'First); - + for j in nullChars'First .. nullChars'Last - 1 loop pragma Loop_Invariant (j>= nullChars'First); tmp(j + tmp'First - nullChars'First) := tmp(j + 1 + tmp'First - nullChars'First); end loop; - + --BitStream_DecodeByte (bs, digit, Result.Success); BitStream_DecodeByte (bs, tmp(tmp'First + (nullChars'Last - nullChars'First)), Result.Success); pragma Assert (Result.Success); - - + + Ch := Character'Val (digit); intDigit := Character'Pos (Ch) - Character'Pos ('0'); @@ -778,8 +778,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is exit when not Result.Success; exit when nullChars(nullChars'First .. nullChars'Last) = tmp(tmp'First .. tmp'First + (nullChars'Last - nullChars'First) ); end loop; - - + + if not Result.Success then result.ErrorCode := ERR_INCORRECT_STREAM; end if; @@ -795,7 +795,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result := ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); --decode sign BitStream_DecodeByte (bs, digitAscii, Result.Success); - + Ch := Character'Val (digitAscii); Result.Success := Result.Success and (Ch = '+' or Ch = '-'); @@ -809,30 +809,30 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is IntVal := Asn1Int(absIntVal); elsif Ch = '-' and absIntVal <= Asn1UInt(Asn1Int'Last)+1 then IntVal := -Asn1Int(absIntVal-1)-1; - else + else Result := ASN1_RESULT'(Success => False, ErrorCode => ERR_INCORRECT_STREAM); end if; end if; end if; - - + + end Acn_Dec_Int_ASCII_VarSize_NullTerminated; - - - + + + function Float_to_OctetArray4 (x : Float) return OctetArray4 is function do_it is new Ada.Unchecked_Conversion (Float, OctetArray4); begin return do_it (x); end Float_to_OctetArray4; - + function OctetArray4_to_Float (x : OctetArray4) return Float is function do_it is new Ada.Unchecked_Conversion (OctetArray4, Float); begin return do_it (x); end OctetArray4_to_Float; - - + + function Long_Float_to_OctetArray8 (x : Asn1Real) return OctetArray8 is function do_it is new Ada.Unchecked_Conversion (Asn1Real, OctetArray8); begin @@ -845,7 +845,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is return do_it (x); end OctetArray8_to_Long_Float; - + procedure Acn_Enc_Real_IEEE754_32_big_endian (bs : in out BitStream; RealVal : in Asn1Real) is tmp : OctetArray4; @@ -863,7 +863,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end if; end Acn_Enc_Real_IEEE754_32_big_endian; - + procedure Acn_Dec_Real_IEEE754_32_big_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) is tmp : OctetArray4 := OctetArray4'(others => 0); @@ -885,7 +885,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; RealVal := Asn1Real (OctetArray4_to_Float (tmp)); end Acn_Dec_Real_IEEE754_32_big_endian; - + procedure Acn_Enc_Real_IEEE754_64_big_endian (bs : in out BitStream; RealVal : in Asn1Real) is tmp : OctetArray8; @@ -924,8 +924,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is pragma assert(Result.Success); RealVal := OctetArray8_to_Long_Float (tmp); end Acn_Dec_Real_IEEE754_64_big_endian; - - + + procedure Acn_Enc_Real_IEEE754_32_little_endian (bs : in out BitStream; RealVal : in Asn1Real) is tmp : OctetArray4; @@ -943,7 +943,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end if; end Acn_Enc_Real_IEEE754_32_little_endian; - + procedure Acn_Dec_Real_IEEE754_32_little_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) is tmp : OctetArray4 := OctetArray4'(others => 0); @@ -965,7 +965,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; RealVal := Asn1Real (OctetArray4_to_Float (tmp)); end Acn_Dec_Real_IEEE754_32_little_endian; - + procedure Acn_Enc_Real_IEEE754_64_little_endian (bs : in out BitStream; RealVal : in Asn1Real) is tmp : OctetArray8; @@ -1003,10 +1003,10 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end if; pragma assert(Result.Success); RealVal := OctetArray8_to_Long_Float (tmp); - end Acn_Dec_Real_IEEE754_64_little_endian; - - - + end Acn_Dec_Real_IEEE754_64_little_endian; + + + procedure Acn_Enc_Boolean_true_pattern (bs : in out BitStream; BoolVal : in Asn1Boolean; pattern : in BitArray) is begin @@ -1029,7 +1029,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result := ASN1_RESULT'(Success => true, ErrorCode => 0); end Acn_Dec_Boolean_true_pattern; - + procedure Acn_Enc_Boolean_false_pattern (bs : in out BitStream; BoolVal : in Asn1Boolean; pattern : in BitArray) is begin @@ -1039,8 +1039,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end Acn_Enc_Boolean_false_pattern; - - + + procedure Acn_Dec_Boolean_false_pattern (bs : in out BitStream; BoolVal : out Asn1Boolean; pattern : in BitArray; Result : out ASN1_RESULT) is begin @@ -1048,7 +1048,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is BoolVal := not BoolVal; end Acn_Dec_Boolean_false_pattern; - + procedure Acn_Enc_NullType_pattern (bs : in out BitStream; encVal : in Asn1NullType; pattern : in BitArray) is pragma Unreferenced (encVal); @@ -1064,7 +1064,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result.Success := BoolVal; decValue := (if BoolVal then 0 else 1); end Acn_Dec_NullType_pattern; - + procedure Acn_Enc_NullType_pattern2 (bs : in out BitStream; pattern : in BitArray) is @@ -1079,8 +1079,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Acn_Dec_Boolean_true_pattern(bs, BoolVal, pattern, Result); Result.Success := BoolVal; end Acn_Dec_NullType_pattern2; - - + + procedure Acn_Enc_NullType(bs : in out BitStream; encVal : in Asn1NullType) is pragma Unreferenced (bs); @@ -1096,10 +1096,10 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is decValue := 0; Result := ASN1_RESULT'(Success => True, ErrorCode => 0); end Acn_Dec_NullType; - - - + + + procedure Acn_Enc_String_Ascii_FixSize (bs : in out BitStream; strVal : in String) is begin @@ -1122,13 +1122,13 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is strVal (I) := Character'Val (Integer(charIndex)); end loop; strVal (strVal'Last) := Standard.ASCII.NUL; - end Acn_Dec_String_Ascii_FixSize; - - - + end Acn_Dec_String_Ascii_FixSize; + + - procedure Acn_Enc_String_Ascii_Null_Teminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in String) + + procedure Acn_Enc_String_Ascii_Null_Terminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in String) is i : Integer := strVal'First; begin @@ -1139,65 +1139,65 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; -- encode nullChar for i in null_characters'Range loop - pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-null_characters'First)*8); + pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-null_characters'First)*8); BitStream_AppendByte(bs, null_characters(i), False); end loop; - end Acn_Enc_String_Ascii_Null_Teminated; - - - procedure Acn_Dec_String_Ascii_Null_Teminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) + end Acn_Enc_String_Ascii_Null_Terminated; + + + procedure Acn_Dec_String_Ascii_Null_Terminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) is I : Integer := strVal'First; charIndex : Asn1Byte := 65; -- ascii code of 'A'. Let's hope that 'A' will never be null Character tmp : OctetBuffer := OctetBuffer'(1=> 0, 2=> 0, 3=> 0, 4=> 0, 5=> 0, 6=> 0, 7=> 0, 8=> 0, 9=> 0, 10=> 0); begin Result := ASN1_RESULT'(Success => True, ErrorCode => 0); - - + + --read null_character_size characters into the tmp buffer pragma Assert (tmp'First = 1); pragma Assert (tmp'Last = 10); pragma Assert (null_characters'First = 1); pragma Assert(null_characters'Last <= 10); - - + + for i in null_characters'Range loop pragma Loop_Invariant (bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-null_characters'First)*8 and i>=1 and i<=10); BitStream_DecodeByte (bs, charIndex, Result.Success); pragma Assert (Result.Success); tmp(i + tmp'First - null_characters'First) := charIndex; end loop; - - + + while i <= strVal'Last and then null_characters(null_characters'First .. null_characters'Last) /= tmp(tmp'First .. tmp'First + (null_characters'Last - null_characters'First) ) loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last and bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-strVal'First)*8); - + charIndex := tmp(tmp'First); for j in null_characters'First .. null_characters'Last - 1 loop pragma Loop_Invariant (j>= null_characters'First); tmp(j + tmp'First - null_characters'First) := tmp(j + 1 + tmp'First - null_characters'First); end loop; - + --BitStream_DecodeByte (bs, digit, Result.Success); pragma Assert(null_characters'Last - null_characters'First <= 9); BitStream_DecodeByte (bs, tmp(tmp'First + (null_characters'Last - null_characters'First)), Result.Success); pragma Assert (Result.Success); - + --exit when null_characters(null_characters'First .. null_characters'Last) = tmp(tmp'First .. tmp'First + (null_characters'Last - null_characters'First) ); - + strVal (i) := Character'Val (Integer(charIndex)); i := i + 1; end loop; - + while i <= strVal'Last loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last); strVal (i) := Standard.ASCII.NUL; i := i + 1; end loop; - end Acn_Dec_String_Ascii_Null_Teminated; - + end Acn_Dec_String_Ascii_Null_Terminated; + procedure Acn_Enc_String_Ascii_Internal_Field_Determinant (bs : in out BitStream; asn1Min : Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal : in String) is @@ -1222,7 +1222,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result := ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); Dec_ConstraintWholeNumberInt (bs, nSize, Integer (asn1Min), Integer (asn1Max), nLengthDeterminantSizeInBits, Result.Success); - + while Result.Success and then I <= strVal'Last and then I <= nSize loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last and bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-strVal'First)*8); BitStream_DecodeByte (bs, charIndex, Result.Success); @@ -1236,10 +1236,10 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is I := I + 1; end loop; - end Acn_Dec_String_Ascii_Internal_Field_Determinant; + end Acn_Dec_String_Ascii_Internal_Field_Determinant; + + - - procedure Acn_Enc_String_Ascii_External_Field_Determinant(bs : in out BitStream; strVal : in String) is I : Integer := strVal'First; @@ -1253,14 +1253,14 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end Acn_Enc_String_Ascii_External_Field_Determinant; - procedure Acn_Dec_String_Ascii_External_Field_Determinant (bs : in out BitStream; extSizeDeterminatFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) + procedure Acn_Dec_String_Ascii_External_Field_Determinant (bs : in out BitStream; extSizeDeterminantFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) is I : Integer := strVal'First; charIndex : Asn1Byte; begin Result := ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); - while Result.Success and then I <= strVal'Last and then I <= Integer(extSizeDeterminatFld) loop + while Result.Success and then I <= strVal'Last and then I <= Integer(extSizeDeterminantFld) loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last and bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-strVal'First)*8); BitStream_DecodeByte (bs, charIndex, Result.Success); strVal (I) := Character'Val (Integer(charIndex)); @@ -1274,8 +1274,8 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end Acn_Dec_String_Ascii_External_Field_Determinant; - - + + procedure Acn_Enc_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize : Integer; strVal : in String) is @@ -1293,7 +1293,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end Acn_Enc_String_CharIndex_External_Field_Determinant; - procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize :Integer; extSizeDeterminatFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) + procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize :Integer; extSizeDeterminantFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) is I : Integer := strVal'First; charIndex : Integer; @@ -1301,7 +1301,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is begin Result := ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); - while Result.Success and then I <= strVal'Last - 1 and then I <= Integer (extSizeDeterminatFld) loop + while Result.Success and then I <= strVal'Last - 1 and then I <= Integer (extSizeDeterminantFld) loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last and bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-strVal'First)*nCharSize); Dec_ConstraintWholeNumberInt (bs, charIndex, 0, asn1Max, nCharSize, Result.Success); @@ -1317,9 +1317,9 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end Acn_Dec_String_CharIndex_External_Field_Determinant; - - - + + + procedure Acn_Enc_String_CharIndex_Internal_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize : Integer; asn1Min : Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal: in String) is I : Integer := strVal'First; @@ -1348,7 +1348,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is Result := ASN1_RESULT'(Success => True, ErrorCode => ERR_INCORRECT_STREAM); Dec_ConstraintWholeNumberInt (bs, nSize, Integer (asn1Min), Integer (asn1Max), nLengthDeterminantSizeInBits, Result.Success); - + while Result.Success and then I <= strVal'Last - 1 and then I <= nSize loop pragma Loop_Invariant (i >= strVal'First and i <= strVal'Last and bs.Current_Bit_Pos = bs.Current_Bit_Pos'Loop_Entry + (i-strVal'First)*nCharSize); @@ -1359,7 +1359,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is result.Success := false; strVal (I) := Standard.ASCII.NUL; end if; - + I := I + 1; end loop; @@ -1370,7 +1370,7 @@ package body adaasn1rtl.encoding.acn with Spark_Mode is end loop; end Acn_Dec_String_CharIndex_Internal_Field_Determinant; - - + + end adaasn1rtl.encoding.acn; diff --git a/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.ads b/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.ads index 15b96b9d4..683f4e7e5 100644 --- a/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.ads +++ b/Docs/examples/calculate_crc/a_out/adaasn1rtl-encoding-acn.ads @@ -2,18 +2,18 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_PositiveInteger_ConstSize(bs : in out BitStream; IntVal : in Asn1UInt; sizeInBits : in Integer) with Depends => (bs => (bs, IntVal, sizeInBits)), - Pre => sizeInBits >= 0 and then - sizeInBits < Asn1UInt'Size and then + Pre => sizeInBits >= 0 and then + sizeInBits < Asn1UInt'Size and then IntVal <= 2**sizeInBits - 1 and then - bs.Current_Bit_Pos < Natural'Last - sizeInBits and then + bs.Current_Bit_Pos < Natural'Last - sizeInBits and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - sizeInBits, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + sizeInBits ; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_8(bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then IntVal <= Asn1UInt(Asn1Byte'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8, @@ -21,7 +21,7 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_16 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then IntVal <= Asn1UInt(Interfaces.Unsigned_16'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, @@ -29,7 +29,7 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_32 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then IntVal <= Asn1UInt(Interfaces.Unsigned_32'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, @@ -37,22 +37,22 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_PositiveInteger_ConstSize_big_endian_64 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_16 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then IntVal <= Asn1UInt(Interfaces.Unsigned_16'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16; - + procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_32 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then IntVal <= Asn1UInt(Interfaces.Unsigned_32'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, @@ -60,49 +60,49 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_PositiveInteger_ConstSize_little_endian_64 (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64; - + procedure Acn_Enc_Int_PositiveInteger_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1UInt'Size + 8) and then + Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1UInt'Size + 8) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (Asn1UInt'Size + 8), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1UInt'Size + 8); - - + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1UInt'Size + 8); + + type Asn1Int_ARRAY_2_64 is array (2 .. 64) of Asn1Int; - + PV : constant Asn1Int_ARRAY_2_64 := Asn1Int_ARRAY_2_64'(2 => Asn1Int(1), 3 => Asn1Int(3), 4 => Asn1Int(7), 5 => Asn1Int(15), 6 => Asn1Int(31), 7 => Asn1Int(63), 8 => Asn1Int(127), 9 => Asn1Int(255), 10 => Asn1Int(511), 11 => Asn1Int(1023), 12 => Asn1Int(2047), 13 => Asn1Int(4095), 14 => Asn1Int(8191), 15 => Asn1Int(16383), 16 => Asn1Int(32767), 17 => Asn1Int(65535), 18 => Asn1Int(131071), 19 => Asn1Int(262143), 20 => Asn1Int(524287), 21 => Asn1Int(1048575), 22 => Asn1Int(2097151), 23 => Asn1Int(4194303), 24 => Asn1Int(8388607), 25 => Asn1Int(16777215), 26 => Asn1Int(33554431), 27 => Asn1Int(67108863), 28 => Asn1Int(134217727), 29 => Asn1Int(268435455), 30 => Asn1Int(536870911), 31 => Asn1Int(1073741823), 32 => Asn1Int(2147483647), 33 => Asn1Int(4294967295), 34 => Asn1Int(8589934591), 35 => Asn1Int(17179869183), 36 => Asn1Int(34359738367), 37 => Asn1Int(68719476735), 38 => Asn1Int(137438953471), 39 => Asn1Int(274877906943), 40 => Asn1Int(549755813887), 41 => Asn1Int(1099511627775), 42 => Asn1Int(2199023255551), 43 => Asn1Int(4398046511103), 44 => Asn1Int(8796093022207), 45 => Asn1Int(17592186044415), 46 => Asn1Int(35184372088831), 47 => Asn1Int(70368744177663), 48 => Asn1Int(140737488355327), 49 => Asn1Int(281474976710655), 50 => Asn1Int(562949953421311), 51 => Asn1Int(1125899906842623), 52 => Asn1Int(2251799813685247), 53 => Asn1Int(4503599627370495), 54 => Asn1Int(9007199254740991), 55 => Asn1Int(18014398509481983), 56 => Asn1Int(36028797018963967), 57 => Asn1Int(72057594037927935), 58 => Asn1Int(144115188075855871), 59 => Asn1Int(288230376151711743), 60 => Asn1Int(576460752303423487), 61 => Asn1Int(1152921504606846975), 62 => Asn1Int(2305843009213693951), 63 => Asn1Int(4611686018427387903), 64 => Asn1Int(9223372036854775807)); NV : constant Asn1Int_ARRAY_2_64 := Asn1Int_ARRAY_2_64'(2 => Asn1Int(-2), 3 => Asn1Int(-4), 4 => Asn1Int(-8), 5 => Asn1Int(-16), 6 => Asn1Int(-32), 7 => Asn1Int(-64), 8 => Asn1Int(-128), 9 => Asn1Int(-256), 10 => Asn1Int(-512), 11 => Asn1Int(-1024), 12 => Asn1Int(-2048), 13 => Asn1Int(-4096), 14 => Asn1Int(-8192), 15 => Asn1Int(-16384), 16 => Asn1Int(-32768), 17 => Asn1Int(-65536), 18 => Asn1Int(-131072), 19 => Asn1Int(-262144), 20 => Asn1Int(-524288), 21 => Asn1Int(-1048576), 22 => Asn1Int(-2097152), 23 => Asn1Int(-4194304), 24 => Asn1Int(-8388608), 25 => Asn1Int(-16777216), 26 => Asn1Int(-33554432), 27 => Asn1Int(-67108864), 28 => Asn1Int(-134217728), 29 => Asn1Int(-268435456), 30 => Asn1Int(-536870912), 31 => Asn1Int(-1073741824), 32 => Asn1Int(-2147483648), 33 => Asn1Int(-4294967296), 34 => Asn1Int(-8589934592), 35 => Asn1Int(-17179869184), 36 => Asn1Int(-34359738368), 37 => Asn1Int(-68719476736), 38 => Asn1Int(-137438953472), 39 => Asn1Int(-274877906944), 40 => Asn1Int(-549755813888), 41 => Asn1Int(-1099511627776), 42 => Asn1Int(-2199023255552), 43 => Asn1Int(-4398046511104), 44 => Asn1Int(-8796093022208), 45 => Asn1Int(-17592186044416), 46 => Asn1Int(-35184372088832), 47 => Asn1Int(-70368744177664), 48 => Asn1Int(-140737488355328), 49 => Asn1Int(-281474976710656), 50 => Asn1Int(-562949953421312), 51 => Asn1Int(-1125899906842624), 52 => Asn1Int(-2251799813685248), 53 => Asn1Int(-4503599627370496), 54 => Asn1Int(-9007199254740992), 55 => Asn1Int(-18014398509481984), 56 => Asn1Int(-36028797018963968), 57 => Asn1Int(-72057594037927936), 58 => Asn1Int(-144115188075855872), 59 => Asn1Int(-288230376151711744), 60 => Asn1Int(-576460752303423488), 61 => Asn1Int(-1152921504606846976), 62 => Asn1Int(-2305843009213693952), 63 => Asn1Int(-4611686018427387904), 64 => Asn1Int(-9223372036854775808)); - + procedure Acn_Enc_Int_TwosComplement_ConstSize(bs : in out BitStream; IntVal : in Asn1Int; sizeInBits : in Natural) with Depends => (bs => (bs, IntVal, sizeInBits)), - Pre => sizeInBits >= 2 and then - sizeInBits < Asn1UInt'Size and then + Pre => sizeInBits >= 2 and then + sizeInBits < Asn1UInt'Size and then IntVal >= NV(sizeInBits) and then IntVal <= PV(sizeInBits) and then - bs.Current_Bit_Pos < Natural'Last - sizeInBits and then + bs.Current_Bit_Pos < Natural'Last - sizeInBits and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - sizeInBits, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + sizeInBits ; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_8(bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), Pre => IntVal >= NV(8) and then IntVal <= PV(8) and then - bs.Current_Bit_Pos < Natural'Last - 8 and then + bs.Current_Bit_Pos < Natural'Last - 8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 8 ; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_big_endian_16(bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), Pre => IntVal >= NV(16) and then IntVal <= PV(16) and then - bs.Current_Bit_Pos < Natural'Last - 8 and then + bs.Current_Bit_Pos < Natural'Last - 8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 ; @@ -112,29 +112,29 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => (bs => (bs, IntVal)), Pre => IntVal >= NV(32) and then IntVal <= PV(32) and then - bs.Current_Bit_Pos < Natural'Last - 32 and then + bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 ; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_big_endian_64(bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 ; procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_16 (bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then IntVal <= Asn1Int(Interfaces.Unsigned_16'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16; - + procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_32 (bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then IntVal <= Asn1Int(Interfaces.Unsigned_32'Last) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, @@ -142,27 +142,27 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_TwosComplement_ConstSize_little_endian_64 (bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64; - + procedure Acn_Enc_Int_TwosComplement_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1Int) with Depends => (bs => (bs, IntVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1Int'Size + 8) and then + Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1Int'Size + 8) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (Asn1Int'Size + 8), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1Int'Size + 8); + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1Int'Size + 8); + - procedure Acn_Enc_Int_BCD_ConstSize (bs : in out BitStream; IntVal : in Asn1UInt; nNibbles : in Integer) with Depends => (bs => (bs, IntVal, nNibbles)), Pre => nNibbles >= 1 and then nNibbles <= 19 and then IntVal < Powers_of_10(nNibbles) and then - bs.Current_Bit_Pos < Natural'Last - 4*nNibbles and then + bs.Current_Bit_Pos < Natural'Last - 4*nNibbles and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 4*nNibbles, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 4*nNibbles ; @@ -171,7 +171,7 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_BCD_VarSize_NullTerminated (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), Pre => IntVal < Powers_of_10(19) and then - bs.Current_Bit_Pos < Natural'Last - 4*(19+1) and then + bs.Current_Bit_Pos < Natural'Last - 4*(19+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 4*(19+1), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 4*(19+1) ; @@ -184,7 +184,7 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => (bs => (bs, IntVal)), Pre => IntVal > -Asn1Int(Powers_of_10(18)) and then Asn1Uint(abs IntVal) < Powers_of_10(18) and then - bs.Current_Bit_Pos < Natural'Last - 8*(18+1+1) and then + bs.Current_Bit_Pos < Natural'Last - 8*(18+1+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(18+1+1), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(18+1+1) ; @@ -194,7 +194,7 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_UInt_ASCII_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : in Asn1UInt) with Depends => (bs => (bs, IntVal)), Pre => IntVal < Powers_of_10(19) and then - bs.Current_Bit_Pos < Natural'Last - 8*(19+1) and then + bs.Current_Bit_Pos < Natural'Last - 8*(19+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(19+1), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(19+1) ; @@ -202,9 +202,9 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_Int_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal : in Asn1Int; nullChars : in OctetBuffer) with Depends => (bs => (bs, IntVal, nullChars)), - Pre => + Pre => nullChars'Length <= 100 and then - bs.Current_Bit_Pos < Natural'Last - 8*(Get_number_of_digits(abs_value(IntVal))+nullChars'Length+1) and then + bs.Current_Bit_Pos < Natural'Last - 8*(Get_number_of_digits(abs_value(IntVal))+nullChars'Length+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(Get_number_of_digits(abs_value(IntVal))+nullChars'Length+1), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(Get_number_of_digits(abs_value(IntVal))+nullChars'Length+1) ; @@ -212,312 +212,312 @@ package adaasn1rtl.encoding.acn with Spark_Mode is procedure Acn_Enc_UInt_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal : in Asn1UInt; nullChars : in OctetBuffer) with Depends => (bs => (bs, IntVal, nullChars)), Pre => nullChars'Length <= 100 and then - bs.Current_Bit_Pos < Natural'Last - 8*(Get_number_of_digits(IntVal) + nullChars'Length ) and then + bs.Current_Bit_Pos < Natural'Last - 8*(Get_number_of_digits(IntVal) + nullChars'Length ) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(Get_number_of_digits(IntVal) + nullChars'Length), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(Get_number_of_digits(IntVal) + nullChars'Length) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nSizeInBits : in Integer; Result: out ASN1_RESULT) with - Pre => nSizeInBits >= 0 and then - nSizeInBits < Asn1UInt'Size and then - bs.Current_Bit_Pos < Natural'Last - nSizeInBits and then + Pre => nSizeInBits >= 0 and then + nSizeInBits < Asn1UInt'Size and then + bs.Current_Bit_Pos < Natural'Last - nSizeInBits and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - nSizeInBits, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + nSizeInBits and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + nSizeInBits and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize_8 (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 8 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 8 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_16 (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_32 (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize_big_endian_64 (bs : in out BitStream; IntVal :out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; - + procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1UInt; minVal:in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_PositiveInteger_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : out Asn1UInt; minVal : in Asn1UInt; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - (8*8+8) and then + Pre => bs.Current_Bit_Pos < Natural'Last - (8*8+8) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (8*8+8), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (8*8+8) and + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (8*8+8) and ( (Result.Success and IntVal >= minVal ) or (not Result.Success and IntVal = minVal)); - + procedure Acn_Dec_Int_TwosComplement_ConstSize (bs : in out BitStream; IntVal : out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; nSizeInBits : in Integer; Result : out ASN1_RESULT) with - Pre => nSizeInBits >= 0 and then - nSizeInBits < Asn1UInt'Size and then - bs.Current_Bit_Pos < Natural'Last - nSizeInBits and then + Pre => nSizeInBits >= 0 and then + nSizeInBits < Asn1UInt'Size and then + bs.Current_Bit_Pos < Natural'Last - nSizeInBits and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - nSizeInBits, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + nSizeInBits and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + nSizeInBits and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; - + procedure Acn_Dec_Int_TwosComplement_ConstSize_8 (bs : in out BitStream; IntVal :out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 8 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 8 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_TwosComplement_ConstSize_big_endian_16 (bs : in out BitStream; IntVal :out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_TwosComplement_ConstSize_big_endian_32 (bs : in out BitStream; IntVal :out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_TwosComplement_ConstSize_big_endian_64 (bs : in out BitStream; IntVal :out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; Result: out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; - + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_16 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 16 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 16, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 16 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; - + procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_32 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_TwosComplement_ConstSize_little_endian_64 (bs : in out BitStream; IntVal: out Asn1Int; minVal:in Asn1Int; maxVal : in Asn1Int; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, - Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and + Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)) ; procedure Acn_Dec_Int_TwosComplement_VarSize_LengthEmbedded (bs : in out BitStream; IntVal : out Asn1Int; Result : out ASN1_RESULT) with - Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1Int'Size + 8) and then + Pre => bs.Current_Bit_Pos < Natural'Last - (Asn1Int'Size + 8) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (Asn1Int'Size + 8), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1Int'Size + 8); + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (Asn1Int'Size + 8); procedure Acn_Dec_Int_BCD_ConstSize (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nNibbles : in Integer; Result : out ASN1_RESULT) with Pre => nNibbles >= 1 and then nNibbles <= 19 and then minVal <= maxVal and then maxVal <= Powers_of_10(nNibbles) - 1 and then - bs.Current_Bit_Pos < Natural'Last - 4*nNibbles and then + bs.Current_Bit_Pos < Natural'Last - 4*nNibbles and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 4*nNibbles, - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 4*nNibbles and + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 4*nNibbles and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); - + procedure Acn_Dec_Int_BCD_VarSize_NullTerminated (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; Result : out ASN1_RESULT) with Pre => minVal <= maxVal and then maxVal <= Powers_of_10(19) - 1 and then - bs.Current_Bit_Pos < Natural'Last - 4*(19+1) and then + bs.Current_Bit_Pos < Natural'Last - 4*(19+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 4*(19+1), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 4*(19+1) and + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 4*(19+1) and ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); - - + + procedure Acn_Enc_Int_ASCII_ConstSize (bs : in out BitStream; IntVal : in Asn1Int; nChars : in Integer) with Depends => (bs => (bs, IntVal, nChars)), Pre => nChars >= Get_number_of_digits(abs_value(IntVal)) + 1 and then nChars <= 50 and then - bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then + bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(nChars), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars) ; - + procedure Acn_Dec_Int_ASCII_ConstSize (bs : in out BitStream; IntVal: out Asn1Int; minVal : in Asn1Int; maxVal : in Asn1Int; nChars : in Integer; Result : out ASN1_RESULT) with - Pre => nChars >= 2 and then nChars <=50 and then + Pre => nChars >= 2 and then nChars <=50 and then minVal <= maxVal and then - bs.Current_Bit_Pos < Natural'Last - 8*(nChars+1) and then + bs.Current_Bit_Pos < Natural'Last - 8*(nChars+1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(nChars), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars+1) and - ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); - + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars+1) and + ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); + procedure Acn_Enc_UInt_ASCII_ConstSize (bs : in out BitStream; IntVal : in Asn1UInt; nChars : in Integer) with Depends => (bs => (bs, IntVal, nChars)), - Pre => nChars >= 1 and then nChars <=19 and then + Pre => nChars >= 1 and then nChars <=19 and then IntVal < Powers_of_10(nChars) and then - bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then + bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(nChars), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars) ; - + procedure Acn_Dec_UInt_ASCII_ConstSize (bs : in out BitStream; IntVal: out Asn1UInt; minVal : in Asn1UInt; maxVal : in Asn1UInt; nChars : in Integer; Result : out ASN1_RESULT) with - Pre => nChars >= 2 and then nChars <=19 and then + Pre => nChars >= 2 and then nChars <=19 and then minVal <= maxVal and then - maxVal < Powers_of_10(19) and then - bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then + maxVal < Powers_of_10(19) and then + bs.Current_Bit_Pos < Natural'Last - 8*(nChars) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(nChars), - Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars) and - ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); - + Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(nChars) and + ( (Result.Success and IntVal >= minVal and IntVal <= maxVal) or (not Result.Success and IntVal = minVal)); + procedure Acn_Dec_UInt_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal: out Asn1UInt; nullChars: in OctetBuffer; Result : out ASN1_RESULT) with Pre => nullChars'Length >= 1 and then nullChars'Length <= 10 and then nullChars'First = 1 and then - bs.Current_Bit_Pos < Natural'Last - 8*(20+nullChars'Length) and then + bs.Current_Bit_Pos < Natural'Last - 8*(20+nullChars'Length) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(20+nullChars'Length), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(20+nullChars'Length) ; - + procedure Acn_Dec_Int_ASCII_VarSize_NullTerminated (bs : in out BitStream; IntVal: out Asn1Int; nullChars: in OctetBuffer; Result : out ASN1_RESULT) with - Pre => nullChars'Length >= 1 and then + Pre => nullChars'Length >= 1 and then nullChars'Length < 10 and then nullChars'First = 1 and then - bs.Current_Bit_Pos < Natural'Last - 8*(20+1+nullChars'Length) and then + bs.Current_Bit_Pos < Natural'Last - 8*(20+1+nullChars'Length) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 8*(20+1+nullChars'Length), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + 8*(20+1+nullChars'Length) ; - + procedure Acn_Enc_Real_IEEE754_32_big_endian (bs : in out BitStream; RealVal : in Asn1Real) with Depends => (bs => (bs, RealVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32; - + procedure Acn_Dec_Real_IEEE754_32_big_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) with Depends => ((Result,bs, RealVal) => bs), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 ; - + procedure Acn_Enc_Real_IEEE754_64_big_endian (bs : in out BitStream; RealVal : in Asn1Real) with Depends => (bs => (bs, RealVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64; - + procedure Acn_Dec_Real_IEEE754_64_big_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) with Depends => ((Result,bs, RealVal) => bs), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 ; procedure Acn_Enc_Real_IEEE754_32_little_endian (bs : in out BitStream; RealVal : in Asn1Real) with Depends => (bs => (bs, RealVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32; - + procedure Acn_Dec_Real_IEEE754_32_little_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) with Depends => ((Result,bs, RealVal) => bs), - Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 32 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 32, Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 32 ; - + procedure Acn_Enc_Real_IEEE754_64_little_endian (bs : in out BitStream; RealVal : in Asn1Real) with Depends => (bs => (bs, RealVal)), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64; - + procedure Acn_Dec_Real_IEEE754_64_little_endian (bs : in out BitStream; RealVal : out Asn1Real; Result : out ASN1_RESULT) with Depends => ((Result,bs, RealVal) => bs), - Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then + Pre => bs.Current_Bit_Pos < Natural'Last - 64 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - 64, Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + 64 ; - + procedure Acn_Enc_Boolean_true_pattern (bs : in out BitStream; BoolVal : in Asn1Boolean; pattern : in BitArray) with Depends => (bs => (bs, BoolVal, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); @@ -526,16 +526,16 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => ( (bs, BoolVal, Result) => (bs, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); - + procedure Acn_Enc_Boolean_false_pattern (bs : in out BitStream; BoolVal : in Asn1Boolean; pattern : in BitArray) with Depends => (bs => (bs, BoolVal, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); @@ -544,17 +544,17 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => ( (bs, BoolVal, Result) => (bs, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); - + procedure Acn_Enc_NullType_pattern (bs : in out BitStream; encVal : in Asn1NullType; pattern : in BitArray) with Depends => (bs => (bs, encVal, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); @@ -564,17 +564,17 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => ( (bs, decValue, Result) => (bs, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); - + procedure Acn_Enc_NullType_pattern2 (bs : in out BitStream; pattern : in BitArray) with Depends => (bs => (bs, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); @@ -584,22 +584,22 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => ( (bs, Result) => (bs, pattern)), Pre => pattern'Last >= pattern'First and then pattern'Last - pattern'First < Natural'Last and then - bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then + bs.Current_Bit_Pos < Natural'Last - (pattern'Last - pattern'First + 1) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (pattern'Last - pattern'First + 1), Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (pattern'Last - pattern'First + 1); - + procedure Acn_Enc_NullType(bs : in out BitStream; encVal : in Asn1NullType) with Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos; - + procedure Acn_Dec_NullType (bs : in out BitStream; decValue : out Asn1NullType; Result : out ASN1_RESULT) with Post => Result.Success and decValue = 0 and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos; - + procedure Acn_Enc_String_Ascii_FixSize (bs : in out BitStream; strVal : in String) with Depends => (bs => (bs, strVal)), Pre => strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then - bs.Current_Bit_Pos < Natural'Last - (strVal'Last - strVal'First)*8 and then + bs.Current_Bit_Pos < Natural'Last - (strVal'Last - strVal'First)*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (strVal'Last - strVal'First)*8, Post => bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (strVal'Last - strVal'First)*8; @@ -609,143 +609,143 @@ package adaasn1rtl.encoding.acn with Spark_Mode is Depends => ( (bs, strVal, Result) => (bs)), Pre => strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then - bs.Current_Bit_Pos < Natural'Last - (strVal'Last - strVal'First)*8 and then + bs.Current_Bit_Pos < Natural'Last - (strVal'Last - strVal'First)*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (strVal'Last - strVal'First)*8, Post => Result.Success and bs.Current_Bit_Pos = bs'Old.Current_Bit_Pos + (strVal'Last - strVal'First)*8; - - procedure Acn_Enc_String_Ascii_Null_Teminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in String) with + + procedure Acn_Enc_String_Ascii_Null_Terminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in String) with Depends => (bs => (bs, strVal, null_characters)), Pre => null_characters'Length >= 1 and then - null_characters'Length <= 10 and then + null_characters'Length <= 10 and then null_characters'First = 1 and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - null_characters'Length and then - bs.Current_Bit_Pos < Natural'Last - (strVal'Length + null_characters'Length)*8 and then + bs.Current_Bit_Pos < Natural'Last - (strVal'Length + null_characters'Length)*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (strVal'Length + null_characters'Length)*8, Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (strVal'Length + null_characters'Length)*8; - - - procedure Acn_Dec_String_Ascii_Null_Teminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) with + + + procedure Acn_Dec_String_Ascii_Null_Terminated (bs : in out BitStream; null_characters : in OctetBuffer; strVal : in out String; Result : out ASN1_RESULT) with Depends => ( (bs, strVal, Result) => (bs, null_characters)), Pre => null_characters'Length >= 1 and then - null_characters'Length <= 10 and then + null_characters'Length <= 10 and then null_characters'First = 1 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Length < Natural'Last/8 - null_characters'Length and then - bs.Current_Bit_Pos < Natural'Last - (strVal'Length + null_characters'Length)*8 and then + bs.Current_Bit_Pos < Natural'Last - (strVal'Length + null_characters'Length)*8 and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - (strVal'Length + null_characters'Length)*8, Post => Result.Success and bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + (strVal'Length + null_characters'Length)*8; - + procedure Acn_Enc_String_Ascii_Internal_Field_Determinant (bs : in out BitStream; asn1Min : Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal : in String) with Depends => (bs => (bs, asn1Min, strVal, nLengthDeterminantSizeInBits)), - Pre => nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then - asn1Min >= 0 and then + Pre => nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then + asn1Min >= 0 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then asn1Min <= Asn1Int(getStringSize (strVal)) and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits); - + procedure Acn_Dec_String_Ascii_Internal_Field_Determinant (bs : in out BitStream; asn1Min : Asn1Int; asn1Max : Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal : in out String; Result : out ASN1_RESULT) with Depends => ( (bs, strVal, Result) => (bs, asn1Min, asn1Max, nLengthDeterminantSizeInBits)), - Pre => asn1Min >= 0 and then + Pre => asn1Min >= 0 and then asn1Max <= Asn1Int(Integer'Last) and then asn1Min <= asn1Max and then - nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then + nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*8 + nLengthDeterminantSizeInBits); - - - + + + procedure Acn_Enc_String_Ascii_External_Field_Determinant(bs : in out BitStream; strVal : in String) with Depends => (bs => (bs, strVal)), Pre => strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 ) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8 ) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*8 ), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*8); - procedure Acn_Dec_String_Ascii_External_Field_Determinant (bs : in out BitStream; extSizeDeterminatFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) with - Depends => ( (bs, strVal, Result) => (bs, extSizeDeterminatFld)), - Pre => extSizeDeterminatFld >= 0 and then - extSizeDeterminatFld <= Asn1Int(Integer'Last) and then + procedure Acn_Dec_String_Ascii_External_Field_Determinant (bs : in out BitStream; extSizeDeterminantFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) with + Depends => ( (bs, strVal, Result) => (bs, extSizeDeterminantFld)), + Pre => extSizeDeterminantFld >= 0 and then + extSizeDeterminantFld <= Asn1Int(Integer'Last) and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then strVal'Last - strVal'First < Natural'Last/8 - 8 and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*8) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*8), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*8); - - + + procedure Acn_Enc_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize : Integer; strVal : in String) with Depends => (bs => (bs, strVal, nCharSize, charSet)), - Pre => nCharSize >=1 and then nCharSize <= 8 and then + Pre => nCharSize >=1 and then nCharSize <= 8 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then charSet'Last < Natural'Last and then charSet'Last >= charSet'First and then charSet'Last-charSet'First <= 255 and then strVal'Last - strVal'First < Natural'Last/8 - nCharSize and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize ) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize ) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*nCharSize ), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*nCharSize); - procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize :Integer; extSizeDeterminatFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) with - Depends => ( (bs, strVal, Result) => (bs, extSizeDeterminatFld, charSet, nCharSize)), - Pre => extSizeDeterminatFld >= 0 and then extSizeDeterminatFld <= Asn1Int(Integer'Last) and then - nCharSize >=1 and then nCharSize <= 8 and then + procedure Acn_Dec_String_CharIndex_External_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize :Integer; extSizeDeterminantFld : in Asn1Int; strVal : in out String; Result : out ASN1_RESULT) with + Depends => ( (bs, strVal, Result) => (bs, extSizeDeterminantFld, charSet, nCharSize)), + Pre => extSizeDeterminantFld >= 0 and then extSizeDeterminantFld <= Asn1Int(Integer'Last) and then + nCharSize >=1 and then nCharSize <= 8 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then charSet'Last < Natural'Last and then charSet'Last >= charSet'First and then charSet'Last-charSet'First <= 255 and then strVal'Last - strVal'First < Natural'Last/8 - nCharSize and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*nCharSize), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*nCharSize); - - + + procedure Acn_Enc_String_CharIndex_Internal_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize : Integer; asn1Min : Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal: in String) with - Pre => nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then - asn1Min >= 0 and then - nCharSize >=1 and then nCharSize <= 8 and then + Pre => nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then + asn1Min >= 0 and then + nCharSize >=1 and then nCharSize <= 8 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then charSet'Last < Natural'Last and then charSet'Last >= charSet'First and then charSet'Last-charSet'First <= 255 and then strVal'Last - strVal'First < Natural'Last/8 - nCharSize and then asn1Min <= Asn1Int(getStringSize (strVal)) and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits ), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits); procedure Acn_Dec_String_CharIndex_Internal_Field_Determinant (bs : in out BitStream; charSet : String; nCharSize : Integer; asn1Min : Asn1Int; asn1Max: Asn1Int; nLengthDeterminantSizeInBits : in Integer; strVal : in out String; Result : out ASN1_RESULT) with - Pre => asn1Min >= 0 and then + Pre => asn1Min >= 0 and then asn1Max <= Asn1Int(Integer'Last) and then asn1Min <= asn1Max and then - nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then - nCharSize >=1 and then nCharSize <= 8 and then + nLengthDeterminantSizeInBits >= 0 and then nLengthDeterminantSizeInBits < Asn1UInt'Size and then + nCharSize >=1 and then nCharSize <= 8 and then strVal'Last < Natural'Last and then strVal'Last >= strVal'First and then charSet'Last < Natural'Last and then charSet'Last >= charSet'First and then charSet'Last-charSet'First <= 255 and then Asn1Int(charSet'First) + asn1Max < Asn1Int(Integer'Last) and then strVal'Last - strVal'First < Natural'Last/8 - nCharSize and then - bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits) and then + bs.Current_Bit_Pos < Natural'Last - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits) and then bs.Size_In_Bytes < Positive'Last/8 and then bs.Current_Bit_Pos <= bs.Size_In_Bytes * 8 - ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits), Post => bs.Current_Bit_Pos >= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos <= bs'Old.Current_Bit_Pos + ((strVal'Last - strVal'First + 1)*nCharSize + nLengthDeterminantSizeInBits); - + end adaasn1rtl.encoding.acn; diff --git a/FrontEndAst/AcnCreateFromAntlr.fs b/FrontEndAst/AcnCreateFromAntlr.fs index e6e6a693c..eb6f57329 100644 --- a/FrontEndAst/AcnCreateFromAntlr.fs +++ b/FrontEndAst/AcnCreateFromAntlr.fs @@ -27,22 +27,22 @@ open AcnGenericTypes open Asn1AcnAst open Asn1AcnAstUtilFunctions -let private tryGetProp (props:GenericAcnProperty list) fnPropKind = +let private tryGetProp (props:GenericAcnProperty list) fnPropKind = match props |> List.choose fnPropKind with | e::_ -> Some e | _ -> None -let private getEndianessProperty (props:GenericAcnProperty list) = - tryGetProp props (fun x -> match x with ENDIANNES e -> Some e | _ -> None) +let private getEndiannessProperty (props:GenericAcnProperty list) = + tryGetProp props (fun x -> match x with ENDIANNESS e -> Some e | _ -> None) -let private getIntSizeProperty errLoc (props:GenericAcnProperty list) = +let private getIntSizeProperty errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with SIZE e -> Some e | _ -> None) with | None -> None | Some (GP_Fixed v) -> Some(AcnGenericTypes.Fixed (v.Value)) - | Some (GP_NullTerminated ) -> + | Some (GP_NullTerminated ) -> match tryGetProp props (fun x -> match x with TERMINATION_PATTERN e -> Some e | _ -> None) with - | Some bitPattern -> + | Some bitPattern -> match bitPattern.Value.Length % 8 <> 0 with | true -> raise(SemanticError(bitPattern.Location, sprintf "termination-pattern value must be a sequence of bytes" )) | false -> @@ -51,10 +51,10 @@ let private getIntSizeProperty errLoc (props:GenericAcnProperty list) = | None -> Some(AcnGenericTypes.IntNullTerminated ([byte 0])) | Some (GP_SizeDeterminant _) -> raise(SemanticError(errLoc ,"Expecting an Integer value or an ACN constant as value for the size property")) -let private getStringSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errLoc (props:GenericAcnProperty list) = +let private getStringSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with SIZE e -> Some e | _ -> None) with | None -> None - | Some (GP_Fixed v) -> + | Some (GP_Fixed v) -> match minSize = maxSize with | false -> let errMessage = sprintf "The size constraints of the ASN.1 allows variable items (%A .. %A). Therefore, you should either remove the size property (in which case the size determinant will be encoded automatically exactly like uPER), or use a an Integer field as size determinant" minSize maxSize @@ -63,9 +63,9 @@ let private getStringSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errL match minSize = v.Value with | true -> None | false -> raise(SemanticError(errLoc , (sprintf "The size property must either be ommited or have the fixed value %A" minSize))) - | Some (GP_NullTerminated ) -> + | Some (GP_NullTerminated ) -> match tryGetProp props (fun x -> match x with TERMINATION_PATTERN e -> Some e | _ -> None) with - | Some bitPattern -> + | Some bitPattern -> match bitPattern.Value.Length % 8 <> 0 with | true -> raise(SemanticError(bitPattern.Location, sprintf "termination-pattern value must be a sequence of bytes" )) | false -> @@ -74,7 +74,7 @@ let private getStringSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errL | None -> Some(AcnGenericTypes.StrNullTerminated ([byte 0])) | Some (GP_SizeDeterminant fld) -> (Some (AcnGenericTypes.StrExternalField fld)) -let private getSizeableSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errLoc (props:GenericAcnProperty list) = +let private getSizeableSizeProperty (minSize:BigInteger) (maxSize:BigInteger) errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with SIZE e -> Some e | _ -> None) with | None -> None | Some (GP_Fixed v) -> @@ -87,57 +87,57 @@ let private getSizeableSizeProperty (minSize:BigInteger) (maxSize:BigInteger) er | true -> None | false -> raise(SemanticError(errLoc , (sprintf "The size property must either be ommited or have the fixed value %A" minSize))) | Some (GP_SizeDeterminant fld) -> (Some (SzExternalField fld)) - | Some (GP_NullTerminated ) -> + | Some (GP_NullTerminated ) -> match tryGetProp props (fun x -> match x with TERMINATION_PATTERN e -> Some e | _ -> None) with | Some b -> Some(AcnGenericTypes.SzNullTerminated b) | None -> raise(SemanticError(errLoc , (sprintf "No 'termination-pattern' was provided"))) -let private getIntEncodingProperty errLoc (props:GenericAcnProperty list) = +let private getIntEncodingProperty errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with ENCODING e -> Some e | _ -> None) with | None -> None | Some (GP_PosInt ) -> Some (AcnGenericTypes.PosInt) | Some (GP_TwosComplement ) -> Some (AcnGenericTypes.TwosComplement) | Some (GP_Ascii ) -> Some (AcnGenericTypes.IntAscii) - | Some (GP_BCD ) -> Some (AcnGenericTypes.BCD) - | Some (GP_IEEE754_32 ) + | Some (GP_BCD ) -> Some (AcnGenericTypes.BCD) + | Some (GP_IEEE754_32 ) | Some (GP_IEEE754_64 ) -> raise(SemanticError(errLoc ,"The encoding property was expected to be one of 'pos-int','twos-complement','BCD' or 'ASCII' ")) -let private getMappingFunctionProperty acnErrLoc (props:GenericAcnProperty list) = +let private getMappingFunctionProperty acnErrLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with MAPPING_FUNCTION (md,fn) -> Some (md,fn) | _ -> None) with | None -> None - | Some (md,fn) -> + | Some (md,fn) -> let newMd = md |> Option.map(fun m -> {StringLoc.Value = ToC m.Value; Location=m.Location}) let newFn = {StringLoc.Value = ToC fn.Value; Location=fn.Location} Some (AcnGenericTypes.MappingFunction (newMd,newFn)) -let private getPostEncodingFunction (props:GenericAcnProperty list) = +let private getPostEncodingFunction (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with POST_ENCODING_FUNCTION (md,fn)-> Some (md,fn) | _ -> None) with | None -> None | Some (md,fn) -> Some (AcnGenericTypes.POST_ENCODING_FUNCTION (md,fn)) -let private getPreDecodingFunction (props:GenericAcnProperty list) = +let private getPreDecodingFunction (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with PRE_DECODING_FUNCTION (md,fn) -> Some (md,fn) | _ -> None) with | None -> None | Some (md,fn) -> Some (AcnGenericTypes.PRE_DECODING_FUNCTION (md,fn)) -let private getRealEncodingProperty errLoc (props:GenericAcnProperty list) = +let private getRealEncodingProperty errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with ENCODING e -> Some e | _ -> None) with | None -> None - | Some (GP_PosInt ) - | Some (GP_TwosComplement ) - | Some (GP_Ascii ) + | Some (GP_PosInt ) + | Some (GP_TwosComplement ) + | Some (GP_Ascii ) | Some (GP_BCD ) -> raise(SemanticError(errLoc ,"Invalid encoding property value. Expecting 'IEEE754-1985-32' or 'IEEE754-1985-64'")) | Some (GP_IEEE754_32 ) -> Some (AcnGenericTypes.IEEE754_32) - | Some (GP_IEEE754_64 ) -> Some (AcnGenericTypes.IEEE754_64) + | Some (GP_IEEE754_64 ) -> Some (AcnGenericTypes.IEEE754_64) -let private getStringEncodingProperty errLoc (props:GenericAcnProperty list) = +let private getStringEncodingProperty errLoc (props:GenericAcnProperty list) = match tryGetProp props (fun x -> match x with ENCODING e -> Some e | _ -> None) with | None -> None - | Some (GP_PosInt ) - | Some (GP_TwosComplement ) - | Some (GP_IEEE754_32 ) - | Some (GP_IEEE754_64 ) + | Some (GP_PosInt ) + | Some (GP_TwosComplement ) + | Some (GP_IEEE754_32 ) + | Some (GP_IEEE754_64 ) | Some (GP_BCD ) -> raise(SemanticError(errLoc ,"The encoding property was expected to be 'ASCII' or empty")) | Some (GP_Ascii ) -> Some (AcnGenericTypes.StrAscii) @@ -151,28 +151,28 @@ let checkIntHasEnoughSpace acnEncodingClass (hasMappingFunction:bool) acnErrLoc0 let check_ (minEnc : BigInteger) (maxEnc:BigInteger) = match minEnc <= asn1Min && asn1Max <= maxEnc with | true -> () - | false when not (asn1Max <= maxEnc) -> + | false when not (asn1Max <= maxEnc) -> let errMessage = sprintf "The applied ACN encoding does not allow values larger than %A to be encoded, while the corresponding ASN.1 type allows values up to %A" maxEnc asn1Max raise(SemanticError(acnErrLoc0, errMessage)) - | false -> + | false -> let errMessage = sprintf "The applied ACN encoding does not allow values smaller than %A to be encoded, while the corresponding ASN.1 type allows values up to %A" minEnc asn1Min raise(SemanticError(acnErrLoc0, errMessage)) let checkBinary isUnsigned (lengthInBiths:BigInteger) = match isUnsigned with - | true -> check_ 0I (BigInteger.Pow(2I, int lengthInBiths) - 1I) + | true -> check_ 0I (BigInteger.Pow(2I, int lengthInBiths) - 1I) | false -> check_ (-BigInteger.Pow(2I, int (lengthInBiths - 1I))) ((BigInteger.Pow(2I, int (lengthInBiths - 1I))) - 1I) let checkAscii isUnsigned (lengthInBiths:BigInteger) = let digits = int (lengthInBiths / 8I) match isUnsigned with - | true -> check_ 0I (BigInteger.Pow(10I, digits) - 1I) + | true -> check_ 0I (BigInteger.Pow(10I, digits) - 1I) | false -> check_ (-BigInteger.Pow(10I, digits - 1)) ((BigInteger.Pow(10I, digits - 1)) - 1I) let checkBCD (lengthInBiths:BigInteger) = let digits = int (lengthInBiths / 4I) - check_ 0I (BigInteger.Pow(10I, digits) - 1I) + check_ 0I (BigInteger.Pow(10I, digits) - 1I) match hasMappingFunction with | true -> () //when there is a mapping function we are performing no size check - | false -> + | false -> match acnEncodingClass with |Integer_uPER -> () |PositiveInteger_ConstSize_8 -> checkBinary true 8I @@ -209,18 +209,18 @@ let checkIntHasEnoughSpace acnEncodingClass (hasMappingFunction:bool) acnErrLoc0 let private removeTypePrefix (typePrefix : String) (typeName : string)= match typePrefix.Length > 0 with - | false -> typeName + | false -> typeName | true -> match typeName.StartsWith(typePrefix) with - | false -> typeName + | false -> typeName | true -> (typeName.Substring(typePrefix.Length)) - -let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo : AssignmentInfo option) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons thisTypeCons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = + +let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo : AssignmentInfo option) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons thisTypeCons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let declare_IntegerNoRTL (l:ProgrammingLanguage) = l.declare_IntegerNoRTL let declare_PosIntegerNoRTL (l:ProgrammingLanguage) = l.declare_PosIntegerNoRTL @@ -230,20 +230,20 @@ let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo let thisTypeUperRange = uPER.getIntTypeConstraintUperRange thisTypeCons loc let intClass = getIntEncodingClassByUperRange asn1.args thisTypeUperRange uPER.getIntTypeConstraintUperRange (cons@withcons) loc |> ignore - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { IntegerAcnProperties.encodingProp = getIntEncodingProperty acnErrLoc props sizeProp = getIntSizeProperty acnErrLoc props - endiannessProp = getEndianessProperty props + endiannessProp = getEndiannessProperty props mappingFunction = getMappingFunctionProperty acnErrLoc props } | None -> {IntegerAcnProperties.encodingProp = None; sizeProp = None; endiannessProp = None; mappingFunction = None } - let uperMinSizeInBits, uperMaxSizeInBits = + let uperMinSizeInBits, uperMaxSizeInBits = match rootCons with | [] -> uPER.getRequiredBitsForIntUperEncoding asn1.args.integerSizeInBytes uperRange - | _ -> + | _ -> let mn,mx = uPER.getRequiredBitsForIntUperEncoding asn1.args.integerSizeInBytes uperRange 1I + mn, 1I + mx @@ -258,8 +258,8 @@ let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo | Full _ -> false // (-inf, +inf) *) - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes aligment acnErrLoc0 acnProperties uperMinSizeInBits uperMaxSizeInBits isUnsigned + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes alignment acnErrLoc0 acnProperties uperMinSizeInBits uperMaxSizeInBits isUnsigned let asn1Min, asn1Max = match uperRange with @@ -267,16 +267,16 @@ let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo | NegInf b -> (asn1.args.SIntMin, b) //(-inf, b] | PosInf a when a >= 0I -> (a, asn1.args.UIntMax) //[a, +inf) | PosInf a -> (a, asn1.args.SIntMax) - | Full _ -> (asn1.args.SIntMin, asn1.args.SIntMax) + | Full -> (asn1.args.SIntMin, asn1.args.SIntMax) - let rtlFnc = + let rtlFnc = match uperRange with | Full -> Some declare_IntegerNoRTL | PosInf (a) when a=0I -> Some declare_PosIntegerNoRTL - | _ -> + | _ -> match typeAssignmentInfo with - | Some (ValueAssignmentInfo _) -> + | Some (ValueAssignmentInfo _) -> //this is a case where a new type should have been defined. However, the type is under a value assignment e.g. max-Instr INTEGER (12 .. 504) ::= 12 //and currently, we do not declare a new type match asn1Min >= 0I with @@ -285,49 +285,49 @@ let private mergeInteger (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (typeAssignmentInfo | _ -> None checkIntHasEnoughSpace acnEncodingClass acnProperties.mappingFunction.IsSome acnErrLoc0 asn1Min asn1Max - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = rtlFnc} us - {Integer.acnProperties = acnProperties; cons = cons; withcons = withcons; uperRange = uperRange;uperMinSizeInBits=uperMinSizeInBits; - uperMaxSizeInBits=uperMaxSizeInBits; acnEncodingClass = acnEncodingClass; intClass=intClass; acnMinSizeInBits=acnMinSizeInBits; + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = rtlFnc} us + {Integer.acnProperties = acnProperties; cons = cons; withcons = withcons; uperRange = uperRange;uperMinSizeInBits=uperMinSizeInBits; + uperMaxSizeInBits=uperMaxSizeInBits; acnEncodingClass = acnEncodingClass; intClass=intClass; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; isUnsigned= isUnsigned; typeDef=typeDef; defaultInitVal="0"}, us1 -let private mergeReal (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeReal (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let acnErrLoc0 = match acnErrLoc with Some a -> a | None -> loc let getRtlTypeName (l:ProgrammingLanguage) = l.getRealRtlTypeName - + //check for invalid properties - props |> - Seq.iter(fun pr -> + props |> + Seq.iter(fun pr -> match pr with | SIZE _ -> raise(SemanticError(acnErrLoc0, "Acn property 'size' cannot be applied to REAL types")) | _ -> ()) - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { RealAcnProperties.encodingProp = getRealEncodingProperty acnErrLoc props - endiannessProp = getEndianessProperty props + endiannessProp = getEndiannessProperty props } | None -> {RealAcnProperties.encodingProp = None; endiannessProp = None } let uperRange = uPER.getRealTypeConstraintUperRange cons loc let uperMaxSizeInBits=(5I+asn1.args.integerSizeInBytes)*8I let uperMinSizeInBits=8I - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetRealEncodingClass aligment loc acnProperties uperMinSizeInBits uperMaxSizeInBits + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetRealEncodingClass alignment loc acnProperties uperMinSizeInBits uperMaxSizeInBits match acnEncodingClass with | Real_IEEE754_64_big_endian when asn1.args.floatingPointSizeInBytes = 4I -> raise(SemanticError(acnErrLoc0, "Acn property 'IEEE754-1985-64' cannot be applied when -fpWordSize 4")) | Real_IEEE754_64_little_endian when asn1.args.floatingPointSizeInBytes = 4I -> raise(SemanticError(acnErrLoc0, "Acn property 'IEEE754-1985-64' cannot be applied when -fpWordSize 4")) | _ -> () - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = Some getRtlTypeName} us - {Real.acnProperties = acnProperties; cons = cons; withcons = withcons; uperRange=uperRange; uperMaxSizeInBits=uperMaxSizeInBits; - uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = Some getRtlTypeName} us + {Real.acnProperties = acnProperties; cons = cons; withcons = withcons; uperRange=uperRange; uperMaxSizeInBits=uperMaxSizeInBits; + uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; defaultInitVal="0"}, us1 -let private mergeObjectIdentifier (asn1:Asn1Ast.AstRoot) (relativeId:bool) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeObjectIdentifier (asn1:Asn1Ast.AstRoot) (relativeId:bool) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let acnErrLoc0 = match acnErrLoc with Some a -> a | None -> loc let getRtlTypeName (l:ProgrammingLanguage) = l.getObjectIdentifierRtlTypeName relativeId - + //check for invalid properties props |> Seq.iter(fun pr -> raise(SemanticError(acnErrLoc0, "Acn property cannot be applied to OBJECT IDENTIFIER types"))) @@ -337,12 +337,12 @@ let private mergeObjectIdentifier (asn1:Asn1Ast.AstRoot) (relativeId:bool) (loc: let compUperMinSizeInBits, compUperMaxSizeInBits = 8I, 16I*8I//uPER.getRequiredBitsForIntUperEncoding asn1.args.integerSizeInBytes Full let uperMaxSizeInBits= compUperMaxSizeInBits*asn1.args.objectIdentifierMaxLength + lengthSize let uperMinSizeInBits= lengthSize - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) let acnMinSizeInBits, acnMaxSizeInBits= uperMinSizeInBits, uperMaxSizeInBits - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = Some getRtlTypeName} us + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = Some getRtlTypeName} us {ObjectIdentifier.acnProperties = acnProperties; cons = cons; withcons = withcons; relativeObjectId=relativeId; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef}, us1 -let private mergeTimeType (asn1:Asn1Ast.AstRoot) (timeClass:TimeTypeClass) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeTimeType (asn1:Asn1Ast.AstRoot) (timeClass:TimeTypeClass) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let acnErrLoc0 = match acnErrLoc with Some a -> a | None -> loc let getRtlTypeName (l:ProgrammingLanguage) = l.getTimeRtlTypeName timeClass @@ -353,45 +353,30 @@ let private mergeTimeType (asn1:Asn1Ast.AstRoot) (timeClass:TimeTypeClass) (loc: let uperMaxSizeInBits= 1I let uperMinSizeInBits= 400I //+++ let acnMinSizeInBits, acnMaxSizeInBits= uperMinSizeInBits, uperMaxSizeInBits - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = Some getRtlTypeName} us + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = Some getRtlTypeName} us {TimeType.timeClass = timeClass; uperMaxSizeInBits=uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; cons = cons; withcons = withcons }, us1 - - - - - - - - - - - - - - - -type EnmStrGetTypeDifition_arg = - | EnmStrGetTypeDifition_arg of GetTypeDifition_arg +type EnmStrGetTypeDefinition_arg = + | EnmStrGetTypeDefinition_arg of GetTypeDefinition_arg | AcnPrmGetTypeDefinition of ((ScopeNode list)* string*string) -let isCharachterAllowedByAplhabetConstrains (cons:IA5StringConstraint list) (b:byte) = +let isCharacterAllowedByAlphabetConstrains (cons:IA5StringConstraint list) (b:byte) = let ch = System.Convert.ToChar b - let isCharachterAllowedByAplhabetConstrain (c:IA5StringConstraint) = + let isCharacterAllowedByAlphabetConstrain (c:IA5StringConstraint) = let con_or _ e1 e2 _ s = e1 || e2, s let con_and _ e1 e2 s = e1 && e2, s let con_not _ e s = not e, s - let con_ecxept _ e1 e2 s = e1 && (not e2), s + let con_except _ e1 e2 s = e1 && (not e2), s let con_root _ e s = e,s let con_root2 _ e1 e2 s = e1 || e2, s let foldRangeCharCon (c:CharTypeConstraint) = - Asn1Fold.foldRangeTypeConstraint - con_or con_and con_not con_ecxept con_root con_root2 + Asn1Fold.foldRangeTypeConstraint + con_or con_and con_not con_except con_root con_root2 (fun _ (v:string) s -> v.Contains ch ,s) - (fun _ v1 v2 minIsIn maxIsIn s -> - let ret = + (fun _ v1 v2 minIsIn maxIsIn s -> + let ret = match minIsIn, maxIsIn with | true, true -> v1 <= ch && ch <= v2 | true, false -> v1 <= ch && ch < v2 @@ -404,15 +389,15 @@ let isCharachterAllowedByAplhabetConstrains (cons:IA5StringConstraint list) (b:b 0 |> fst Asn1Fold.foldStringTypeConstraint2 - con_or con_and con_not con_ecxept con_root con_root2 + con_or con_and con_not con_except con_root con_root2 (fun _ _ s -> true ,s) (fun _ _ s -> true, s) - (fun _ alphcon s -> foldRangeCharCon alphcon,s) + (fun _ alphcon s -> foldRangeCharCon alphcon,s) c 0 |> fst - cons |> Seq.forall isCharachterAllowedByAplhabetConstrain + cons |> Seq.forall isCharacterAllowedByAlphabetConstrain -let private mergeStringType (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type option) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons defaultCharSet isNumeric (tdarg:EnmStrGetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeStringType (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type option) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons defaultCharSet isNumeric (tdarg:EnmStrGetTypeDefinition_arg) (us:Asn1AcnMergeState) = let acnErrLoc0 = match acnErrLoc with Some a -> a | None -> loc let sizeUperRange = uPER.getSrtingSizeUperRange cons loc let sizeUperAcnRange = uPER.getSrtingSizeUperRange (cons@withcons) loc @@ -421,7 +406,7 @@ let private mergeStringType (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type option) ( let aminSize, amaxSize = uPER.getSizeMinAndMaxValue loc sizeUperAcnRange let minSize = {SIZE.uper = uminSize; acn = aminSize } let maxSize = {SIZE.uper = umaxSize; acn = amaxSize } - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { @@ -429,20 +414,20 @@ let private mergeStringType (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type option) ( sizeProp = getStringSizeProperty minSize.acn maxSize.acn acnErrLoc props } | None -> {StringAcnProperties.encodingProp = None; sizeProp = None } - + let charSize = GetNumberOfBitsForNonNegativeInteger (BigInteger (uperCharSet.Length-1)) let uperMinSizeInBits, uperMaxSizeInBits = uPER.getSizeableTypeSize minSize.uper maxSize.uper charSize let acnUperMinSizeInBits, acnUperMaxSizeInBits = uPER.getSizeableTypeSize minSize.acn maxSize.acn charSize - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetStringEncodingClass aligment loc acnProperties acnUperMinSizeInBits acnUperMaxSizeInBits minSize.acn maxSize.acn uperCharSet + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetStringEncodingClass alignment loc acnProperties acnUperMinSizeInBits acnUperMaxSizeInBits minSize.acn maxSize.acn uperCharSet - match acnEncodingClass with + match acnEncodingClass with | Acn_Enc_String_uPER _ -> () | Acn_Enc_String_uPER_Ascii _ -> () - | Acn_Enc_String_Ascii_Null_Teminated (_, nullChars) -> + | Acn_Enc_String_Ascii_Null_Terminated (_, nullChars) -> let errMsg = "The termination-pattern defines a character which belongs to the allowed values of the ASN.1 type. Use another value in the termination-pattern or apply different constraints in the ASN.1 type." - match nullChars |> Seq.filter(fun c -> c <> 0uy) |> Seq.tryFind (isCharachterAllowedByAplhabetConstrains cons) with + match nullChars |> Seq.filter(fun c -> c <> 0uy) |> Seq.tryFind (isCharacterAllowedByAlphabetConstrains cons) with | Some _ -> raise(SemanticError(acnErrLoc0, errMsg)) | None -> () | Acn_Enc_String_Ascii_External_Field_Determinant (_,relativePath) -> () @@ -451,23 +436,23 @@ let private mergeStringType (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type option) ( - let typeDef, us1 = + let typeDef, us1 = match tdarg with - | EnmStrGetTypeDifition_arg tdarg -> getStringTypeDifition tdarg us - | AcnPrmGetTypeDefinition (curPath, md, ts) -> + | EnmStrGetTypeDefinition_arg tdarg -> getStringTypeDefinition tdarg us + | AcnPrmGetTypeDefinition (curPath, md, ts) -> let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerStringTypeDefinition us l (ReferenceToType curPath) (FEI_Reference2OtherType (ReferenceToType [MD md; TA ts])) + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerStringTypeDefinition us l (ReferenceToType curPath) (FEI_Reference2OtherType (ReferenceToType [MD md; TA ts])) (l,itm), ns) us lanDefs |> Map.ofList, us1 - {StringType.acnProperties = acnProperties; cons = cons; withcons = withcons; minSize=minSize; maxSize =maxSize; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; uperCharSet=uperCharSet; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits;isNumeric=isNumeric; typeDef=typeDef; defaultInitVal="null"}, us1 + {StringType.acnProperties = acnProperties; cons = cons; withcons = withcons; minSize=minSize; maxSize =maxSize; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; uperCharSet=uperCharSet; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits;isNumeric=isNumeric; typeDef=typeDef}, us1 -let private mergeOctetStringType (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeOctetStringType (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let sizeUperRange = uPER.getOctetStringUperRange cons loc let sizeUperAcnRange = uPER.getOctetStringUperRange (cons@withcons) loc @@ -482,22 +467,22 @@ let private mergeOctetStringType (asn1:Asn1Ast.AstRoot) (loc:SrcLoc) (acnErrLoc: let acnUperMinSizeInBits, acnUperMaxSizeInBits = uPER.getSizeableTypeSize minSize.acn maxSize.acn 8I //let fixAsn1Size = match minSize = maxSize with true -> Some minSize | false -> None - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> {SizeableAcnProperties.sizeProp = getSizeableSizeProperty minSize.acn maxSize.acn acnErrLoc props} | None -> {SizeableAcnProperties.sizeProp = None} - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetOctetStringEncodingClass aligment loc acnProperties acnUperMinSizeInBits acnUperMaxSizeInBits minSize.acn maxSize.acn hasNCount + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetOctetStringEncodingClass alignment loc acnProperties acnUperMinSizeInBits acnUperMaxSizeInBits minSize.acn maxSize.acn hasNCount - let typeDef, us1 = getSizeableTypeDifition tdarg us + let typeDef, us1 = getSizeableTypeDefinition tdarg us {OctetString.acnProperties = acnProperties; cons = cons; withcons = withcons; minSize=minSize; maxSize =maxSize; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef}, us1 -let private mergeBitStringType (asn1:Asn1Ast.AstRoot) (namedBitList: NamedBit0 list) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeBitStringType (asn1:Asn1Ast.AstRoot) (namedBitList: NamedBit0 list) (loc:SrcLoc) (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let newNamedBitList = - namedBitList |> List.map(fun nb -> - let resolvedValue = + namedBitList |> List.map(fun nb -> + let resolvedValue = match nb._value with | IDV_IntegerValue intVal -> intVal.Value | IDV_DefinedValue (mdVal, refVal) -> Asn1Ast.GetValueAsInt (Asn1Ast.GetBaseValue mdVal refVal asn1) asn1 @@ -516,39 +501,39 @@ let private mergeBitStringType (asn1:Asn1Ast.AstRoot) (namedBitList: NamedBit0 l let acnUperMinSizeInBits, uperMaxSizeInBits = uPER.getSizeableTypeSize minSize.acn maxSize.acn 1I //let fixAsn1Size = match minSize = maxSize with true -> Some minSize | false -> None - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { SizeableAcnProperties.sizeProp = getSizeableSizeProperty minSize.acn maxSize.acn acnErrLoc props} | None -> {SizeableAcnProperties.sizeProp = None } - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBitStringEncodingClass aligment loc acnProperties acnUperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBitStringEncodingClass alignment loc acnProperties acnUperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount - let typeDef, us1 = getSizeableTypeDifition tdarg us - {BitString.acnProperties = acnProperties; cons = cons; withcons = withcons; minSize=minSize; maxSize =maxSize; - uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; - acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; namedBitList = newNamedBitList; defaultInitVal="null"}, us1 + let typeDef, us1 = getSizeableTypeDefinition tdarg us + {BitString.acnProperties = acnProperties; cons = cons; withcons = withcons; minSize=minSize; maxSize =maxSize; + uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; + acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; namedBitList = newNamedBitList}, us1 -let private mergeNullType (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeNullType (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = let getRtlTypeName (l:ProgrammingLanguage) = l.getNullRtlTypeName - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { NullTypeAcnProperties.encodingPattern = tryGetProp props (fun x -> match x with PATTERN e -> Some e | _ -> None); savePosition = props |> Seq.exists(fun z -> match z with SAVE_POSITION -> true | _ -> false )} | None -> {NullTypeAcnProperties.encodingPattern = None; savePosition = false } - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetNullEncodingClass aligment loc acnProperties - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = Some getRtlTypeName} us - {NullType.acnProperties = acnProperties; uperMaxSizeInBits = 0I; uperMinSizeInBits=0I; - acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetNullEncodingClass alignment loc acnProperties + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = Some getRtlTypeName} us + {NullType.acnProperties = acnProperties; uperMaxSizeInBits = 0I; uperMinSizeInBits=0I; + acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; defaultInitVal="0"}, us1 -let private mergeBooleanType (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= +let private mergeBooleanType (acnErrLoc: SrcLoc option) (props:GenericAcnProperty list) cons withcons (tdarg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= let getRtlTypeName (l:ProgrammingLanguage) = l.getBoolRtlTypeName - let size = + let size = match acnErrLoc with - | Some acnErrLoc -> + | Some acnErrLoc -> match tryGetProp props (fun x -> match x with SIZE e -> Some e | _ -> None) with | None -> None | Some (GP_Fixed v) -> Some(v.Value) @@ -561,65 +546,65 @@ let private mergeBooleanType (acnErrLoc: SrcLoc option) (props:GenericAcnPropert | Some sz when sz >= bitVal.Value.Length.AsBigInt -> let zeros = new String('0', ((int sz) - bitVal.Value.Length) ) {StringLoc.Value = zeros + bitVal.Value; Location = bitVal.Location} - | Some sz -> + | Some sz -> let errMsg = sprintf "The size of the pattern '%s' is greater than the encoding size (%d)" bitVal.Value (int sz) raise(SemanticError(bitVal.Location ,errMsg)) - - let acnProperties = + + let acnProperties = match acnErrLoc with - | Some acnErrLoc -> + | Some acnErrLoc -> match tryGetProp props (fun x -> match x with TRUE_VALUE e -> Some e | _ -> None) with - | Some tv -> + | Some tv -> {BooleanAcnProperties.encodingPattern = Some (TrueValue (alignWithZeros tv))} | None -> match tryGetProp props (fun x -> match x with FALSE_VALUE e -> Some e | _ -> None) with | Some tv -> {BooleanAcnProperties.encodingPattern = Some (FalseValue (alignWithZeros tv))} | None -> {BooleanAcnProperties.encodingPattern = None} | None -> {BooleanAcnProperties.encodingPattern = None } - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBooleanEncodingClass aligment loc acnProperties - let typeDef, us1 = getPrimitiveTypeDifition {tdarg with rtlFnc = Some getRtlTypeName} us - {Boolean.acnProperties = acnProperties; cons = cons; withcons = withcons;uperMaxSizeInBits = 1I; uperMinSizeInBits=1I; + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBooleanEncodingClass alignment loc acnProperties + let typeDef, us1 = getPrimitiveTypeDefinition {tdarg with rtlFnc = Some getRtlTypeName} us + {Boolean.acnProperties = acnProperties; cons = cons; withcons = withcons;uperMaxSizeInBits = 1I; uperMinSizeInBits=1I; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; typeDef=typeDef; defaultInitVal="false"}, us1 -let private mergeEnumerated (asn1:Asn1Ast.AstRoot) (items: Asn1Ast.NamedItem list) (originalLocation : SrcLoc option, loc:SrcLoc) (acnErrLoc: SrcLoc option) (acnType:AcnTypeEncodingSpec option) (props:GenericAcnProperty list) cons withcons (tdarg:EnmStrGetTypeDifition_arg) (us:Asn1AcnMergeState) = +let private mergeEnumerated (asn1:Asn1Ast.AstRoot) (items: Asn1Ast.NamedItem list) (originalLocation : SrcLoc option, loc:SrcLoc) (acnErrLoc: SrcLoc option) (acnType:AcnTypeEncodingSpec option) (props:GenericAcnProperty list) cons withcons (tdarg:EnmStrGetTypeDefinition_arg) (us:Asn1AcnMergeState) = let loc = match originalLocation with | None -> loc | Some l -> l - let endodeValues = + let encodeValues = match tryGetProp props (fun x -> match x with ENCODE_VALUES -> Some true | _ -> None) with | Some true -> true | _ -> false - let typeDef, proposedEnmName, us1 = + let typeDef, proposedEnmName, us1 = match tdarg with - | EnmStrGetTypeDifition_arg tdarg -> - let proposedEnmName = - ProgrammingLanguage.AllLanguages |> List.map(fun l -> + | EnmStrGetTypeDefinition_arg tdarg -> + let proposedEnmName = + ProgrammingLanguage.AllLanguages |> List.map(fun l -> l, FE_TypeDefinition.getProposedTypeDefName us l (ReferenceToType tdarg.enmItemTypeDefPath) |> fst) |> Map.ofList - let typeDef, us1 = getEnumeratedTypeDifition tdarg us + let typeDef, us1 = getEnumeratedTypeDefinition tdarg us typeDef, proposedEnmName, us1 - | AcnPrmGetTypeDefinition (curPath, md, ts) -> - let proposedEnmName = - ProgrammingLanguage.AllLanguages |> List.map(fun l -> + | AcnPrmGetTypeDefinition (curPath, md, ts) -> + let proposedEnmName = + ProgrammingLanguage.AllLanguages |> List.map(fun l -> l, FE_TypeDefinition.getProposedTypeDefName us l (ReferenceToType [MD md; TA ts]) |> fst) |> Map.ofList let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerEnumeratedTypeDefinition us l (ReferenceToType curPath) (FEI_Reference2OtherType (ReferenceToType [MD md; TA ts])) + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerEnumeratedTypeDefinition us l (ReferenceToType curPath) (FEI_Reference2OtherType (ReferenceToType [MD md; TA ts])) (l,itm), ns) us lanDefs |> Map.ofList, proposedEnmName, us1 - let allocatedValuesToAllEnumItems (namedItems:Asn1Ast.NamedItem list) = + let allocatedValuesToAllEnumItems (namedItems:Asn1Ast.NamedItem list) = let createAsn1ValueByBigInt biVal = {Asn1Ast.Asn1Value.Kind = Asn1Ast.IntegerValue (IntLoc.ByValue biVal); Asn1Ast.Asn1Value.moduleName=""; Asn1Ast.Location = emptyLocation; Asn1Ast.id = ReferenceToValue([],[])} let allocated = namedItems |> List.filter(fun x -> x._value.IsSome) let unallocated = namedItems |> List.filter(fun x -> x._value.IsNone) let rec allocateItems (unallocated:Asn1Ast.NamedItem list) (allocated:Asn1Ast.NamedItem list) potentialValue: Asn1Ast.NamedItem list = match unallocated with | [] -> allocated - |x::xs -> + |x::xs -> let rec getValue (allocated:Asn1Ast.NamedItem list) (vl:BigInteger) = match allocated |> Seq.exists(fun ni -> match ni._value with Some value -> vl = (Asn1Ast.GetValueAsInt value asn1) | None -> false) with | false -> vl @@ -633,12 +618,12 @@ let private mergeEnumerated (asn1:Asn1Ast.AstRoot) (items: Asn1Ast.NamedItem li let definitionValue = Asn1Ast.GetValueAsInt itm._value.Value asn1 let c_name, s_name, a_name = match asn1.args.renamePolicy with - | AlwaysPrefixTypeName -> + | AlwaysPrefixTypeName -> let typeName0 lang = proposedEnmName[lang] (* let langTypeDef = typeDef.[lang] - let rec aux (langTypeDef:FE_EnumeratedTypeDefinition) = + let rec aux (langTypeDef:FE_EnumeratedTypeDefinition) = match langTypeDef.kind with | NonPrimitiveNewTypeDefinition -> langTypeDef.typeName | NonPrimitiveNewSubTypeDefinition sub -> aux sub @@ -656,52 +641,52 @@ let private mergeEnumerated (asn1:Asn1Ast.AstRoot) (items: Asn1Ast.NamedItem li match acnType with | None -> let acnEncodeValue = (BigInteger i) - {NamedItem.Name = itm.Name; Comments = itm.Comments; c_name = c_name; scala_name = s_name; ada_name = a_name; definitionValue = definitionValue; acnEncodeValue = acnEncodeValue} + {NamedItem.Name = itm.Name; Comments = itm.Comments; c_name = c_name; scala_name = s_name; ada_name = a_name; definitionValue = definitionValue; acnEncodeValue = acnEncodeValue} | Some acnType -> - let acnEncodeValue = + let acnEncodeValue = match tryGetProp props (fun x -> match x with ENCODE_VALUES -> Some true | _ -> None) with - | Some _ -> + | Some _ -> match acnType.children |> Seq.tryFind(fun z -> z.name.Value = itm.Name.Value) with - | Some acnNameItem -> + | Some acnNameItem -> match tryGetProp acnNameItem.childEncodingSpec.acnProperties (fun x -> match x with ENUM_SET_VALUE newIntVal -> Some newIntVal | _ -> None) with | Some intVal -> intVal.Value | None -> definitionValue | None -> definitionValue | None -> (BigInteger i) - {NamedItem.Name = itm.Name; Comments = itm.Comments; c_name = c_name; scala_name = s_name; ada_name = a_name; definitionValue = definitionValue; acnEncodeValue = acnEncodeValue} + {NamedItem.Name = itm.Name; Comments = itm.Comments; c_name = c_name; scala_name = s_name; ada_name = a_name; definitionValue = definitionValue; acnEncodeValue = acnEncodeValue} - let items0, userDefinedValues = + let items0, userDefinedValues = match items |> Seq.exists (fun nm -> nm._value.IsSome) with - | false -> allocatedValuesToAllEnumItems items, false + | false -> allocatedValuesToAllEnumItems items, false | true -> allocatedValuesToAllEnumItems items, true let uperSizeInBits = GetNumberOfBitsForNonNegativeInteger(BigInteger((Seq.length items) - 1)) let items = items0|> List.mapi mapItem - - let acnProperties = + + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { IntegerAcnProperties.encodingProp = getIntEncodingProperty acnErrLoc props sizeProp = getIntSizeProperty acnErrLoc props - endiannessProp = getEndianessProperty props + endiannessProp = getEndiannessProperty props mappingFunction = getMappingFunctionProperty acnErrLoc props } | None -> {IntegerAcnProperties.encodingProp = None; sizeProp = None; endiannessProp = None; mappingFunction = None } - - let aligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetEnumeratedEncodingClass asn1.args.integerSizeInBytes items aligment loc acnProperties uperSizeInBits uperSizeInBits endodeValues + + let alignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetEnumeratedEncodingClass asn1.args.integerSizeInBytes items alignment loc acnProperties uperSizeInBits uperSizeInBits encodeValues match cons with | [] -> () - | _ -> + | _ -> match items |> List.filter (Asn1Fold.isValidValueGeneric cons (fun a b -> a = b.Name.Value)) with - | [] -> + | [] -> raise(SemanticError(loc, (sprintf "The constraints defined for this type do not allow any value" ))) | _ -> () - {Enumerated.acnProperties = acnProperties; items=items; cons = cons; withcons = withcons;uperMaxSizeInBits = uperSizeInBits; - uperMinSizeInBits=uperSizeInBits;encodeValues=endodeValues; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; - acnMaxSizeInBits = acnMaxSizeInBits;userDefinedValues=userDefinedValues; typeDef=typeDef; defaultInitVal="null"}, us1 + {Enumerated.acnProperties = acnProperties; items=items; cons = cons; withcons = withcons;uperMaxSizeInBits = uperSizeInBits; + uperMinSizeInBits=uperSizeInBits;encodeValues=encodeValues; acnEncodingClass = acnEncodingClass; acnMinSizeInBits=acnMinSizeInBits; + acnMaxSizeInBits = acnMaxSizeInBits;userDefinedValues=userDefinedValues; typeDef=typeDef}, us1 let rec private mergeAcnEncodingSpecs (thisType:AcnTypeEncodingSpec option) (baseType:AcnTypeEncodingSpec option) = match thisType, baseType with @@ -712,15 +697,15 @@ let rec private mergeAcnEncodingSpecs (thisType:AcnTypeEncodingSpec option) (bas let mergedProperties = thisType.acnProperties@baseType.acnProperties let mergedChildren = let thisTypeNames = thisType.children |> List.map(fun x -> x.name) - let baseTypeNames = - baseType.children |> - List.filter(fun x -> + let baseTypeNames = + baseType.children |> + List.filter(fun x -> match thisType.children with | [] -> true //if this type has children specification then use this type children - | _ -> false (*x.asn1Type.IsNone*)) |> //otherwise use base - List.map(fun x -> x.name) + | _ -> false (*x.asn1Type.IsNone*)) |> //otherwise use base + List.map(fun x -> x.name) let combinedNames = thisTypeNames@baseTypeNames |> Seq.distinctBy(fun x -> x.Value) |> Seq.toList - combinedNames |> + combinedNames |> List.choose(fun nm -> let e1 = thisType.children |> Seq.tryFind(fun x -> x.name = nm) let e2 = baseType.children |> Seq.tryFind(fun x -> x.name = nm) @@ -734,7 +719,7 @@ let rec private mergeAcnEncodingSpecs (thisType:AcnTypeEncodingSpec option) (bas Some ({name = nm; childEncodingSpec = combinedEncoingSpec; asn1Type = thisChild.asn1Type; argumentList = thisChild.argumentList; comments=thisChild.comments}) | None -> None) - Some {AcnTypeEncodingSpec.acnProperties = mergedProperties; children = mergedChildren; loc = thisType.loc; comments = thisType.comments; postion=thisType.postion; antlrSubTree=thisType.antlrSubTree} + Some {AcnTypeEncodingSpec.acnProperties = mergedProperties; children = mergedChildren; loc = thisType.loc; comments = thisType.comments; position=thisType.position; antlrSubTree=thisType.antlrSubTree} (* match asn1Type with @@ -745,18 +730,18 @@ let rec private mergeAcnEncodingSpecs (thisType:AcnTypeEncodingSpec option) (bas *) -(*Removes Type inclusion and RangeContraint_MIN_MAX constraints*) +(*Removes Type inclusion and RangeConstraint_MIN_MAX constraints*) let rec fixConstraint (asn1:Asn1Ast.AstRoot) (c:Asn1Ast.Asn1Constraint) = let intersect c1 cs = //let str = (c1::cs) |> List.map(fun (z:Asn1Ast.Asn1Constraint) -> z.Asn1Con) |> Seq.StrJoin (" | ") - let str (a:Asn1Ast.Asn1Constraint) (b:Asn1Ast.Asn1Constraint) = + let str (a:Asn1Ast.Asn1Constraint) (b:Asn1Ast.Asn1Constraint) = sprintf "(%s) | (%s)" a.Asn1Con b.Asn1Con cs |> List.fold(fun fc cc -> (Asn1Ast.IntersectionConstraint (str fc cc, fc,cc))) c1 let mergeConstraints (cc:Asn1Ast.Asn1Constraint list) constConstr = match cc with | [] -> [] | x1::[] -> [constConstr x1] - | x1::xs -> + | x1::xs -> let sc = intersect x1 xs [constConstr sc] let mergeConstraints2 (c1:Asn1Ast.Asn1Constraint list) (c2:Asn1Ast.Asn1Constraint list) constConstr = @@ -764,45 +749,45 @@ let rec fixConstraint (asn1:Asn1Ast.AstRoot) (c:Asn1Ast.Asn1Constraint) = | [], [] -> [] | _::_, [] -> c1 | [], _::_ -> c2 - | x1::xs1, x2::xs2 -> [constConstr (intersect x1 xs1) (intersect x2 xs2) ] + | x1::xs1, x2::xs2 -> [constConstr (intersect x1 xs1) (intersect x2 xs2) ] Asn1Ast.foldConstraint - (fun s v -> [Asn1Ast.SingleValueContraint(s, v)] ) - (fun s a b b1 b2 -> [Asn1Ast.RangeContraint(s, a,b,b1,b2)]) - (fun s a b1 -> [Asn1Ast.RangeContraint_val_MAX (s, a,b1)]) - (fun s a b1 -> [Asn1Ast.RangeContraint_MIN_val (s, a,b1)]) - (fun () -> []) + (fun s v -> [Asn1Ast.SingleValueConstraint(s, v)] ) + (fun s a b b1 b2 -> [Asn1Ast.RangeConstraint(s, a,b,b1,b2)]) + (fun s a b1 -> [Asn1Ast.RangeConstraint_val_MAX (s, a,b1)]) + (fun s a b1 -> [Asn1Ast.RangeConstraint_MIN_val (s, a,b1)]) + (fun () -> []) (fun s md ts -> let actTypeAllCons = Asn1Ast.GetActualTypeByNameAllConsIncluded md ts asn1 - actTypeAllCons.Constraints |> List.collect (fixConstraint asn1)) - (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.SizeContraint (s, c)) ) - (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.AlphabetContraint (s, c)) ) - (fun s sc l -> mergeConstraints sc (fun c -> Asn1Ast.WithComponentConstraint(s, c, l)) ) - (fun s ni cons -> + actTypeAllCons.Constraints |> List.collect (fixConstraint asn1)) + (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.SizeConstraint (s, c)) ) + (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.AlphabetConstraint (s, c)) ) + (fun s sc l -> mergeConstraints sc (fun c -> Asn1Ast.WithComponentConstraint(s, c, l)) ) + (fun s ni cons -> match cons with - | None -> [{ni with Contraint = None}] - | Some cons -> cons |> List.map (fun c -> {ni with Contraint = Some c})) - (fun s nameItems -> [Asn1Ast.WithComponentsConstraint (s, nameItems |> List.collect id)]) - (fun s c1 c2 b -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.UnionConstraint (s, c1,c2,b))) - (fun s c1 c2 -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.IntersectionConstraint (s, c1,c2))) - (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.AllExceptConstraint (s,c)) ) + | None -> [{ni with Constraint = None}] + | Some cons -> cons |> List.map (fun c -> {ni with Constraint = Some c})) + (fun s nameItems -> [Asn1Ast.WithComponentsConstraint (s, nameItems |> List.collect id)]) + (fun s c1 c2 b -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.UnionConstraint (s, c1,c2,b))) + (fun s c1 c2 -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.IntersectionConstraint (s, c1,c2))) + (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.AllExceptConstraint (s,c)) ) (fun s c1 c2 -> match c1,c2 with | [], [] -> [] | _::_, [] -> c1 | [], _::_ -> mergeConstraints c2 (fun c -> Asn1Ast.AllExceptConstraint (s, c)) | _, _ -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.ExceptConstraint (s, c1,c2))) - (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.RootConstraint (s, c)) ) - (fun s c1 c2 -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.RootConstraint2 (s, c1,c2))) + (fun s sc -> mergeConstraints sc (fun c -> Asn1Ast.RootConstraint (s, c)) ) + (fun s c1 c2 -> mergeConstraints2 c1 c2 (fun c1 c2 -> Asn1Ast.RootConstraint2 (s, c1,c2))) c let rec private mapAcnParamTypeToAcnAcnInsertedType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (p:AcnParamType) (props:GenericAcnProperty list) (curPath : ScopeNode list) (us:Asn1AcnMergeState) = - let acnAligment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnAlignment = tryGetProp props (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) match p with - | AcnPrmInteger acnErrLoc -> - let acnProperties = {IntegerAcnProperties.encodingProp = getIntEncodingProperty acnErrLoc props; sizeProp = getIntSizeProperty acnErrLoc props; endiannessProp = getEndianessProperty props; mappingFunction = getMappingFunctionProperty acnErrLoc props} - let encProp = + | AcnPrmInteger acnErrLoc -> + let acnProperties = {IntegerAcnProperties.encodingProp = getIntEncodingProperty acnErrLoc props; sizeProp = getIntSizeProperty acnErrLoc props; endiannessProp = getEndiannessProperty props; mappingFunction = getMappingFunctionProperty acnErrLoc props} + let encProp = match acnProperties.encodingProp with | Some e -> e | None -> raise(SemanticError(acnErrLoc, "Mandatory ACN property 'encoding' is missing")) @@ -812,34 +797,34 @@ let rec private mapAcnParamTypeToAcnAcnInsertedType (asn1:Asn1Ast.AstRoot) (acn: | TwosComplement -> false, Full | IntAscii -> false, Full | BCD -> true, PosInf(0I) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes acnAligment acnErrLoc acnProperties 0I 0I isUnsigned + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes acnAlignment acnErrLoc acnProperties 0I 0I isUnsigned let checkIntHasEnoughSpace asn1Min asn1Max = checkIntHasEnoughSpace acnEncodingClass acnProperties.mappingFunction.IsSome acnErrLoc asn1Min asn1Max let intClass = getIntEncodingClassByUperRange asn1.args uperRange - AcnInteger ({AcnInteger.acnProperties=acnProperties; acnAligment=acnAligment; acnEncodingClass = acnEncodingClass; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; cons=[]; withcons=[];isUnsigned=isUnsigned; uperRange= uperRange; intClass=intClass; checkIntHasEnoughSpace=checkIntHasEnoughSpace; inheritInfo=None; defaultValue="0"}), us + AcnInteger ({AcnInteger.acnProperties=acnProperties; acnAlignment=acnAlignment; acnEncodingClass = acnEncodingClass; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; cons=[]; withcons=[];isUnsigned=isUnsigned; uperRange= uperRange; intClass=intClass; checkIntHasEnoughSpace=checkIntHasEnoughSpace; inheritInfo=None; defaultValue="0"}), us | AcnPrmBoolean acnErrLoc -> - let acnProperties = + let acnProperties = match tryGetProp props (fun x -> match x with TRUE_VALUE e -> Some e | _ -> None) with | Some tv -> {BooleanAcnProperties.encodingPattern = Some (TrueValue tv)} | None -> match tryGetProp props (fun x -> match x with FALSE_VALUE e -> Some e | _ -> None) with | Some tv -> {BooleanAcnProperties.encodingPattern = Some (FalseValue tv)} | None -> {BooleanAcnProperties.encodingPattern = None} - let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBooleanEncodingClass acnAligment acnErrLoc acnProperties - AcnBoolean ({AcnBoolean.acnProperties=acnProperties; acnAligment=acnAligment; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; defaultValue="false"}), us + let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBooleanEncodingClass acnAlignment acnErrLoc acnProperties + AcnBoolean ({AcnBoolean.acnProperties=acnProperties; acnAlignment=acnAlignment; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; defaultValue="false"}), us | AcnPrmNullType acnErrLoc -> let acnProperties = { NullTypeAcnProperties.encodingPattern = tryGetProp props (fun x -> match x with PATTERN e -> Some e | _ -> None); savePosition = props |> Seq.exists(fun z -> match z with SAVE_POSITION -> true | _ -> false )} - let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetNullEncodingClass acnAligment acnErrLoc acnProperties - AcnNullType ({AcnNullType.acnProperties=acnProperties; acnAligment=acnAligment; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; defaultValue="0"}), us + let acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetNullEncodingClass acnAlignment acnErrLoc acnProperties + AcnNullType ({AcnNullType.acnProperties=acnProperties; acnAlignment=acnAlignment; Location = acnErrLoc; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; defaultValue="0"}), us | AcnPrmRefType (md,ts)-> let asn1Type0 = Asn1Ast.GetBaseTypeByName md ts asn1 - let baseProps = - acn.files |> - List.collect(fun f -> f.modules) |> - List.filter(fun acm -> acm.name.Value = md.Value) |> + let baseProps = + acn.files |> + List.collect(fun f -> f.modules) |> + List.filter(fun acm -> acm.name.Value = md.Value) |> List.collect(fun acm -> acm.typeAssignments) |> - List.filter(fun act -> act.name.Value = ts.Value) |> + List.filter(fun act -> act.name.Value = ts.Value) |> List.collect(fun act -> act.typeEncodingSpec.acnProperties) let props = match props with @@ -848,55 +833,51 @@ let rec private mapAcnParamTypeToAcnAcnInsertedType (asn1:Asn1Ast.AstRoot) (acn: match asn1Type0.Kind with | Asn1Ast.Enumerated nmItems -> let cons = asn1Type0.Constraints |> List.collect (fixConstraint asn1) |> List.map (ConstraintsMapping.getEnumConstraint asn1 asn1Type0) - let enumerated, ns = mergeEnumerated asn1 nmItems (None, ts.Location) (Some ts.Location) (Some {AcnTypeEncodingSpec.acnProperties = props; children = []; loc=ts.Location; comments = []; postion=(ts.Location, ts.Location); antlrSubTree=None}) props cons [] (AcnPrmGetTypeDefinition (curPath,md.Value,ts.Value)) us - AcnReferenceToEnumerated({AcnReferenceToEnumerated.modName = md; tasName = ts; enumerated = enumerated; acnAligment= acnAligment; defaultValue="null"}), ns - | Asn1Ast.IA5String + let enumerated, ns = mergeEnumerated asn1 nmItems (None, ts.Location) (Some ts.Location) (Some {AcnTypeEncodingSpec.acnProperties = props; children = []; loc=ts.Location; comments = []; position=(ts.Location, ts.Location); antlrSubTree=None}) props cons [] (AcnPrmGetTypeDefinition (curPath,md.Value,ts.Value)) us + AcnReferenceToEnumerated({AcnReferenceToEnumerated.modName = md; tasName = ts; enumerated = enumerated; acnAlignment= acnAlignment}), ns + | Asn1Ast.IA5String | Asn1Ast.NumericString -> let isNumeric = (asn1Type0.Kind = Asn1Ast.NumericString) let cons = asn1Type0.Constraints |> List.collect (fixConstraint asn1) |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 asn1Type0) let defaultCharSet = [|for i in 0..127 -> System.Convert.ToChar(i) |] let str, ns = mergeStringType asn1 None ts.Location (Some ts.Location) props cons [] defaultCharSet isNumeric (AcnPrmGetTypeDefinition (curPath,md.Value,ts.Value)) us - let defaultValue = - match asn1.args.targetLanguages with - | Scala::x -> "Array.fill(" + str.maxSize.acn.ToString() + "+1)(0)" - | _ -> "null" - AcnReferenceToIA5String({AcnReferenceToIA5String.modName = md; tasName = ts; str = str; acnAligment= acnAligment; defaultValue=defaultValue}), ns + AcnReferenceToIA5String({AcnReferenceToIA5String.modName = md; tasName = ts; str = str; acnAlignment= acnAlignment}), ns | Asn1Ast.Integer -> let cons = asn1Type0.Constraints |> List.collect (fixConstraint asn1) |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 asn1Type0) let uperRange = uPER.getIntTypeConstraintUperRange cons ts.Location - let alignmentSize = AcnEncodingClasses.getAlignmentSize acnAligment + let alignmentSize = AcnEncodingClasses.getAlignmentSize acnAlignment let uperMinSizeInBits, uperMaxSizeInBits = uPER.getRequiredBitsForIntUperEncoding asn1.args.integerSizeInBytes uperRange - let acnProperties = {IntegerAcnProperties.encodingProp = getIntEncodingProperty ts.Location props; sizeProp = getIntSizeProperty ts.Location props; endiannessProp = getEndianessProperty props; mappingFunction = getMappingFunctionProperty ts.Location props} + let acnProperties = {IntegerAcnProperties.encodingProp = getIntEncodingProperty ts.Location props; sizeProp = getIntSizeProperty ts.Location props; endiannessProp = getEndiannessProperty props; mappingFunction = getMappingFunctionProperty ts.Location props} let isUnsigned = match acnProperties.encodingProp with - | Some encProp -> + | Some encProp -> match encProp with | PosInt -> true | TwosComplement -> false | IntAscii -> false | BCD -> true | None -> - match acnProperties.sizeProp.IsNone && acnProperties.endiannessProp.IsNone with - | true -> + match acnProperties.sizeProp.IsNone && acnProperties.endiannessProp.IsNone with + | true -> match uperRange with | Concrete (a,b) when a >= 0I -> true //[a, b] | Concrete _ -> false | NegInf _ -> false //(-inf, b] | PosInf a when a >= 0I -> true //[a, +inf) | PosInf _ -> false //[a, +inf) - | Full _ -> false // (-inf, +inf) + | Full -> false // (-inf, +inf) | false -> raise(SemanticError(ts.Location, "Mandatory ACN property 'encoding' is missing")) - - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits = - AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes acnAligment ts.Location acnProperties uperMinSizeInBits uperMaxSizeInBits isUnsigned - + + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits = + AcnEncodingClasses.GetIntEncodingClass asn1.args.integerSizeInBytes acnAlignment ts.Location acnProperties uperMinSizeInBits uperMaxSizeInBits isUnsigned + let checkIntHasEnoughSpace asn1Min asn1Max = checkIntHasEnoughSpace acnEncodingClass acnProperties.mappingFunction.IsSome ts.Location asn1Min asn1Max let intClass = getIntEncodingClassByUperRange asn1.args uperRange - AcnInteger ({AcnInteger.acnProperties=acnProperties; acnAligment=acnAligment; acnEncodingClass = acnEncodingClass; Location = ts.Location; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits;cons=cons;withcons=[];isUnsigned=isUnsigned; uperRange= uperRange; intClass=intClass; defaultValue="0"; checkIntHasEnoughSpace=checkIntHasEnoughSpace; inheritInfo=Some {InheritanceInfo.modName=md.Value; tasName=ts.Value;hasAdditionalConstraints=false;}}), us + AcnInteger ({AcnInteger.acnProperties=acnProperties; acnAlignment=acnAlignment; acnEncodingClass = acnEncodingClass; Location = ts.Location; acnMinSizeInBits=acnMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits;cons=cons;withcons=[];isUnsigned=isUnsigned; uperRange= uperRange; intClass=intClass; defaultValue="0"; checkIntHasEnoughSpace=checkIntHasEnoughSpace; inheritInfo=Some {InheritanceInfo.modName=md.Value; tasName=ts.Value;hasAdditionalConstraints=false;}}), us | _ -> - let newParma = + let newParma = match asn1Type0.Kind with //| Asn1Ast.Integer -> AcnPrmInteger ts.Location | Asn1Ast.NullType -> AcnPrmNullType ts.Location @@ -913,48 +894,48 @@ let rec private mapAcnParamTypeToAcnAcnInsertedType (asn1:Asn1Ast.AstRoot) (acn: let rec mapAnyConstraint (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (cons:Asn1Ast.Asn1Constraint list) = let fixConstraint = (fixConstraint asn1) match t.Kind with - | Asn1Ast.Integer -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 t) |> List.map IntegerTypeConstraint - | Asn1Ast.Real -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getRealTypeConstraint asn1 t) |> List.map RealTypeConstraint - | Asn1Ast.ObjectIdentifier - | Asn1Ast.RelativeObjectIdentifier -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getObjectIdConstraint asn1 t) |> List.map ObjectIdConstraint - | Asn1Ast.TimeType tc -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getTimeConstraint asn1 t) |> List.map TimeConstraint - | Asn1Ast.IA5String -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) |> List.map IA5StringConstraint - | Asn1Ast.NumericString -> + | Asn1Ast.Integer -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 t) |> List.map IntegerTypeConstraint + | Asn1Ast.Real -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getRealTypeConstraint asn1 t) |> List.map RealTypeConstraint + | Asn1Ast.ObjectIdentifier + | Asn1Ast.RelativeObjectIdentifier -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getObjectIdConstraint asn1 t) |> List.map ObjectIdConstraint + | Asn1Ast.TimeType tc -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getTimeConstraint asn1 t) |> List.map TimeConstraint + | Asn1Ast.IA5String -> cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) |> List.map IA5StringConstraint - | Asn1Ast.OctetString -> + | Asn1Ast.NumericString -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) |> List.map IA5StringConstraint + | Asn1Ast.OctetString -> cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getOctetStringConstraint asn1 t) |> List.map OctetStringConstraint - | Asn1Ast.BitString namedBitList -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBitStringConstraint asn1 t) |> List.map BitStringConstraint + | Asn1Ast.BitString namedBitList -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBitStringConstraint asn1 t) |> List.map BitStringConstraint | Asn1Ast.NullType -> [NullConstraint] - | Asn1Ast.Boolean -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBoolConstraint asn1 t) |> List.map BoolConstraint - | Asn1Ast.Enumerated items -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getEnumConstraint asn1 t) |> List.map EnumConstraint - | Asn1Ast.SequenceOf chType -> - cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSequenceOfConstraint asn1 t chType) |> List.map SequenceOfConstraint - | Asn1Ast.Sequence children -> + | Asn1Ast.Boolean -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBoolConstraint asn1 t) |> List.map BoolConstraint + | Asn1Ast.Enumerated items -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getEnumConstraint asn1 t) |> List.map EnumConstraint + | Asn1Ast.SequenceOf chType -> + cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSequenceOfConstraint asn1 t chType) |> List.map SequenceOfConstraint + | Asn1Ast.Sequence children -> cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSeqConstraint asn1 t children) |> List.map SeqConstraint - | Asn1Ast.Choice children -> + | Asn1Ast.Choice children -> cons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getChoiceConstraint asn1 t children) |> List.map ChoiceConstraint - | Asn1Ast.ReferenceType rf -> + | Asn1Ast.ReferenceType rf -> let oldBaseType = Asn1Ast.GetBaseTypeByName rf.modName rf.tasName asn1 mapAnyConstraint asn1 oldBaseType cons let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Module) (t:Asn1Ast.Asn1Type) (curPath : ScopeNode list) (typeDefPath : ScopeNode list) (enmItemTypeDefPath : ScopeNode list) - (acnType:AcnTypeEncodingSpec option) + (acnType:AcnTypeEncodingSpec option) (originalLocation : SrcLoc option) //parameter not used. (refTypeCons:Asn1Ast.Asn1Constraint list) // constraints applied to this type originating from reference types --> uPER visible (withCons:Asn1Ast.Asn1Constraint list) // constraints applied to this type originating from with component and with components --> non uPER visible (acnArgs : AcnGenericTypes.RelativePath list) (acnParameters : AcnParameter list) - (inferitInfo : InheritanceInfo option) + (inheritInfo : InheritanceInfo option) (typeAssignmentInfo : AssignmentInfo option) (us:Asn1AcnMergeState) : (Asn1Type*Asn1AcnMergeState)= let acnProps = @@ -970,72 +951,72 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo //if debug.AsString = "RW90-DATAVIEW.UART-Config.timeout" then // printfn "%s" debug.AsString - let tfdArg = {GetTypeDifition_arg.asn1TypeKind = t.Kind; loc = t.Location; curPath = curPath; typeDefPath = typeDefPath; enmItemTypeDefPath = enmItemTypeDefPath; inferitInfo =inferitInfo ; typeAssignmentInfo = typeAssignmentInfo; rtlFnc = None} + let tfdArg = {GetTypeDefinition_arg.asn1TypeKind = t.Kind; loc = t.Location; curPath = curPath; typeDefPath = typeDefPath; enmItemTypeDefPath = enmItemTypeDefPath; inheritInfo =inheritInfo ; typeAssignmentInfo = typeAssignmentInfo; rtlFnc = None} let fixConstraint = (fixConstraint asn1) //let actualLocation = match originalLocation with Some l -> l | None -> t.Location let asn1Kind, kindState = match t.Kind with - | Asn1Ast.Integer -> + | Asn1Ast.Integer -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 t) let thisTypeCons = t.Constraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIntegerTypeConstraint asn1 t) let o, us1 = mergeInteger asn1 t.Location typeAssignmentInfo acnErrLoc combinedProperties cons wcons thisTypeCons tfdArg us Integer o, us1 - | Asn1Ast.Real -> + | Asn1Ast.Real -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getRealTypeConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getRealTypeConstraint asn1 t) let o, us1 = mergeReal asn1 t.Location acnErrLoc combinedProperties cons wcons tfdArg us Real o, us1 - | Asn1Ast.ObjectIdentifier - | Asn1Ast.RelativeObjectIdentifier -> + | Asn1Ast.ObjectIdentifier + | Asn1Ast.RelativeObjectIdentifier -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getObjectIdConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getObjectIdConstraint asn1 t) let o, us1 = mergeObjectIdentifier asn1 (t.Kind=Asn1Ast.RelativeObjectIdentifier) t.Location acnErrLoc combinedProperties cons wcons tfdArg us ObjectIdentifier o, us1 - | Asn1Ast.TimeType tc -> + | Asn1Ast.TimeType tc -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getTimeConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getTimeConstraint asn1 t) let o, us1 = mergeTimeType asn1 tc t.Location acnErrLoc combinedProperties cons wcons tfdArg us TimeType o, us1 - | Asn1Ast.IA5String -> + | Asn1Ast.IA5String -> let defaultCharSet = [|for i in 0..127 -> System.Convert.ToChar(i) |] let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) - let o, us1 = mergeStringType asn1 (Some t) t.Location acnErrLoc combinedProperties cons wcons defaultCharSet false (EnmStrGetTypeDifition_arg tfdArg) us + let o, us1 = mergeStringType asn1 (Some t) t.Location acnErrLoc combinedProperties cons wcons defaultCharSet false (EnmStrGetTypeDefinition_arg tfdArg) us IA5String o , us1 - | Asn1Ast.NumericString -> + | Asn1Ast.NumericString -> let defaultCharSet = [| ' ';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9'|] let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getIA5StringConstraint asn1 t) - let o, us1 = mergeStringType asn1 (Some t) t.Location acnErrLoc combinedProperties cons wcons defaultCharSet true (EnmStrGetTypeDifition_arg tfdArg) us + let o, us1 = mergeStringType asn1 (Some t) t.Location acnErrLoc combinedProperties cons wcons defaultCharSet true (EnmStrGetTypeDefinition_arg tfdArg) us NumericString o, us1 - | Asn1Ast.OctetString -> + | Asn1Ast.OctetString -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getOctetStringConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getOctetStringConstraint asn1 t) let o, us1 = mergeOctetStringType asn1 t.Location acnErrLoc combinedProperties cons wcons tfdArg us OctetString o, us1 - | Asn1Ast.BitString namedBitList -> + | Asn1Ast.BitString namedBitList -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBitStringConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBitStringConstraint asn1 t) let o, us1 = mergeBitStringType asn1 namedBitList t.Location acnErrLoc combinedProperties cons wcons tfdArg us BitString o, us1 - | Asn1Ast.NullType -> + | Asn1Ast.NullType -> let constraints = [] let o, us1 = mergeNullType acnErrLoc combinedProperties tfdArg us NullType o, us1 - | Asn1Ast.Boolean -> + | Asn1Ast.Boolean -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBoolConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getBoolConstraint asn1 t) let o, us1 = mergeBooleanType acnErrLoc combinedProperties cons wcons tfdArg us Boolean o, us1 - | Asn1Ast.Enumerated items -> + | Asn1Ast.Enumerated items -> let cons = t.Constraints@refTypeCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getEnumConstraint asn1 t) let wcons = withCons |> List.collect fixConstraint |> List.map (ConstraintsMapping.getEnumConstraint asn1 t) - let o, us1 = mergeEnumerated asn1 items (originalLocation, t.Location) acnErrLoc acnType combinedProperties cons wcons (EnmStrGetTypeDifition_arg tfdArg) us + let o, us1 = mergeEnumerated asn1 items (originalLocation, t.Location) acnErrLoc acnType combinedProperties cons wcons (EnmStrGetTypeDefinition_arg tfdArg) us Enumerated o, us1 - | Asn1Ast.SequenceOf chType -> + | Asn1Ast.SequenceOf chType -> let childWithCons = allCons |> List.choose(fun c -> match c with Asn1Ast.WithComponentConstraint (_,w,_) -> Some w| _ -> None) let myVisibleConstraints = t.Constraints@refTypeCons //|> List.choose(fun c -> match c with Asn1Ast.WithComponentConstraint _ -> None | _ -> Some c) let myNonVisibleConstraints = withCons //|> List.choose(fun c -> match c with Asn1Ast.WithComponentConstraint _ -> None | _ -> Some c) @@ -1043,19 +1024,19 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo let cons = myVisibleConstraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSequenceOfConstraint asn1 t chType) let wcons = myNonVisibleConstraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSequenceOfConstraint asn1 t chType) - let childEncSpec, acnArgs = + let childEncSpec, acnArgs = match acnType with | None -> None, [] - | Some acnType -> + | Some acnType -> match acnType.children with | [] -> None, [] | c1::[] -> Some c1.childEncodingSpec, c1.argumentList | c1::c2::_ -> raise(SemanticError(c1.name.Location, (sprintf "%s Unexpected field name" c2.name.Value))) - - let typeDef, us1 = getSizeableTypeDifition tfdArg us - + + let typeDef, us1 = getSizeableTypeDefinition tfdArg us + let newChType, us2 = mergeType asn1 acn m chType (curPath@[SQF]) (typeDefPath@[SQF]) (enmItemTypeDefPath@[SQF]) childEncSpec None [] childWithCons acnArgs [] None None us1 @@ -1071,7 +1052,7 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo //let minSize, maxSize = uPER.getSizeMinAndMaxValue t.Location sizeUperRange //let fixAsn1Size = match minSize = maxSize with true -> Some minSize | false -> None - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { SizeableAcnProperties.sizeProp = getSizeableSizeProperty minSize.acn maxSize.acn acnErrLoc combinedProperties} | None -> {SizeableAcnProperties.sizeProp = None } @@ -1082,12 +1063,12 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo let acnUperMinSizeInBits, _ =uPER.getSizeableTypeSize minSize.acn maxSize.acn newChType.acnMinSizeInBits let _, acnUperMaxSizeInBits = uPER.getSizeableTypeSize minSize.acn maxSize.acn newChType.acnMinSizeInBits - let aligment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetSequenceOfEncodingClass aligment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn newChType.acnMinSizeInBits newChType.acnMaxSizeInBits hasNCount + let alignment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetSequenceOfEncodingClass alignment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn newChType.acnMinSizeInBits newChType.acnMaxSizeInBits hasNCount let newKind = {SequenceOf.child=newChType; acnProperties = acnProperties; cons = cons; withcons = wcons;minSize=minSize; maxSize =maxSize; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits=uperMinSizeInBits; acnEncodingClass = acnEncodingClass; acnMinSizeInBits = acnMinSizeInBits; acnMaxSizeInBits=acnMaxSizeInBits; typeDef=typeDef} SequenceOf newKind, us2 - | Asn1Ast.Sequence children -> + | Asn1Ast.Sequence children -> let childrenNameConstraints = allCons |> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint (_,w) -> Some w| _ -> None) |> List.collect id let myVisibleConstraints = refTypeCons@t.Constraints //|> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint _ -> None | _ -> Some c) let myNonVisibleConstraints = withCons //|> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint _ -> None | _ -> Some c) @@ -1096,20 +1077,20 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo let cons = myVisibleConstraints|> List.collect fixConstraint |> List.map (ConstraintsMapping.getSeqConstraint asn1 t children) let wcons = myNonVisibleConstraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getSeqConstraint asn1 t children) - let typeDef, us1 = getSequenceTypeDifition tfdArg us + let typeDef, us1 = getSequenceTypeDefinition tfdArg us let mergeChild (cc:ChildSpec option) (c:Asn1Ast.ChildInfo) (us:Asn1AcnMergeState) = let childNamedConstraints = childrenNameConstraints |> List.filter(fun x -> x.Name = c.Name) - let childWithCons = childNamedConstraints |> List.choose(fun nc -> nc.Contraint) - let asn1OptionalityFromWithComponents = - childNamedConstraints |> - List.choose(fun nc -> + let childWithCons = childNamedConstraints |> List.choose(fun nc -> nc.Constraint) + let asn1OptionalityFromWithComponents = + childNamedConstraints |> + List.choose(fun nc -> match nc.Mark with | Asn1Ast.NoMark -> None | Asn1Ast.MarkPresent -> Some AlwaysPresent | Asn1Ast.MarkAbsent -> Some AlwaysAbsent | Asn1Ast.MarkOptional -> Some (Optional ({Optional.defaultValue = None; acnPresentWhen= None})) ) |> - Seq.distinct |> Seq.toList + Seq.distinct |> Seq.toList let newOptionality = match c.Optionality with @@ -1128,30 +1109,30 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo | newOpt::_ -> Some newOpt | Some (Asn1Ast.Optional opt) -> match asn1OptionalityFromWithComponents with - | [] - | (Optional _)::_ -> + | [] + | (Optional _)::_ -> Some (Optional {Optional.defaultValue = opt.defaultValue |> Option.map (ValuesMapping.mapValue asn1 c.Type) ; acnPresentWhen = None}) | x::_ -> Some x let newOptionality = - let acnPresentWhenConditions = + let acnPresentWhenConditions = match cc with | None -> [] - | Some cc -> + | Some cc -> match tryGetProp cc.childEncodingSpec.acnProperties (fun x -> match x with PRESENT_WHEN e -> Some e | _ -> None) with - | None -> - match tryGetProp cc.childEncodingSpec.acnProperties (fun x -> match x with PRESENT_WHEN_EXP e -> Some e | _ -> None) with + | None -> + match tryGetProp cc.childEncodingSpec.acnProperties (fun x -> match x with PRESENT_WHEN_EXP e -> Some e | _ -> None) with | None -> [] | Some acnExp -> [PresenceWhenBoolExpression acnExp] - | Some lst -> - lst |> - List.iter( fun gp -> - match gp with - | GP_PresenceBool l -> () + | Some lst -> + lst |> + List.iter( fun gp -> + match gp with + | GP_PresenceBool l -> () | GP_PresenceInt (l,v) -> let errMsg = sprintf "expecting a single boolean ACN field, or single ACN boolean parameter or a boolean expression composed by ASN.1 fields. The present-when attribute in the form %s==%A can be used only in choice alternatives" l.AsString v.Value raise(SemanticError(l.location, errMsg)) - | GP_PresenceStr (l,s) -> + | GP_PresenceStr (l,s) -> let errMsg = sprintf "expecting a single boolean ACN field, or single ACN boolean parameter or a boolean expression composed by ASN.1 fields. The present-when attribute in the form %s==%s can be used only in choice alternatives" l.AsString s.Value raise(SemanticError(l.location, errMsg)) ) lst |> List.choose(fun gp -> match gp with GP_PresenceBool l -> Some (PresenceWhenBool l) | _ -> None) @@ -1161,33 +1142,33 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo | _ -> raise(SemanticError(cc.Value.name.Location, (sprintf "present-when attribute cannot be applied here since component %s is not optional" cc.Value.name.Value))) match newOptionality with - | None - | Some AlwaysAbsent + | None + | Some AlwaysAbsent | Some AlwaysPresent -> checkForPresentWhenConditions () newOptionality | Some (Optional opt) -> - let acnPresentWhen = + let acnPresentWhen = match acnPresentWhenConditions with | [] -> None - | x::_ -> Some x + | x::_ -> Some x Some (Optional {Optional.defaultValue = opt.defaultValue ; acnPresentWhen = acnPresentWhen}) - + match cc with - | None -> - let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[SEQ_CHILD c.Name.Value]) (typeDefPath@[SEQ_CHILD c.Name.Value]) (enmItemTypeDefPath@[SEQ_CHILD c.Name.Value]) None None [] childWithCons [] [] None None us + | None -> + let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) (typeDefPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) (enmItemTypeDefPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) None None [] childWithCons [] [] None None us Asn1Child ({Asn1Child.Name = c.Name; _c_name = c.c_name; _scala_name = c.scala_name; _ada_name = c.ada_name; Type = newChild; Optionality = newOptionality;asn1Comments = c.Comments |> Seq.toList; acnComments=[]}), us1 | Some cc -> match cc.asn1Type with - | None -> - let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[SEQ_CHILD c.Name.Value]) (typeDefPath@[SEQ_CHILD c.Name.Value]) (enmItemTypeDefPath@[SEQ_CHILD c.Name.Value]) (Some cc.childEncodingSpec) None [] childWithCons cc.argumentList [] None None us + | None -> + let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) (typeDefPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) (enmItemTypeDefPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) (Some cc.childEncodingSpec) None [] childWithCons cc.argumentList [] None None us Asn1Child ({Asn1Child.Name = c.Name; _c_name = c.c_name; _scala_name = c.scala_name; _ada_name = c.ada_name; Type = newChild; Optionality = newOptionality; asn1Comments = c.Comments |> Seq.toList; acnComments = cc.comments}), us1 | Some xx -> - //let tdprm = {GetTypeDifition_arg.asn1TypeKind = t.Kind; loc = t.Location; curPath = (curPath@[SEQ_CHILD c.Name.Value]); typeDefPath = (typeDefPath@[SEQ_CHILD c.Name.Value]); inferitInfo =None ; typeAssignmentInfo = None; rtlFnc = None} - let newType, us1 = mapAcnParamTypeToAcnAcnInsertedType asn1 acn xx cc.childEncodingSpec.acnProperties (curPath@[SEQ_CHILD c.Name.Value]) us - AcnChild({AcnChild.Name = c.Name; id = ReferenceToType(curPath@[SEQ_CHILD c.Name.Value]); Type = newType; Comments = cc.comments |> Seq.toArray}), us1 + //let tdprm = {GetTypeDefinition_arg.asn1TypeKind = t.Kind; loc = t.Location; curPath = (curPath@[SEQ_CHILD c.Name.Value]); typeDefPath = (typeDefPath@[SEQ_CHILD c.Name.Value]); inheritInfo =None ; typeAssignmentInfo = None; rtlFnc = None} + let newType, us1 = mapAcnParamTypeToAcnAcnInsertedType asn1 acn xx cc.childEncodingSpec.acnProperties (curPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]) us + AcnChild({AcnChild.Name = c.Name; id = ReferenceToType(curPath@[SEQ_CHILD (c.Name.Value, c.Optionality.IsSome)]); Type = newType; Comments = cc.comments |> Seq.toArray}), us1 - let mergedChildren, chus = + let mergedChildren, chus = match acnType with | None -> children |> foldMap (fun st ch -> mergeChild None ch st ) us1 | Some acnEncSpec -> @@ -1197,13 +1178,13 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo // MAKE SURE ACN CHILDREN ARE SUPERSET OF ASN1 CHILDREN !!!!! children |> List.filter(fun c -> not (acnChildren |> List.exists(fun c2 -> c2.name = c.Name))) |> List.iter(fun c -> raise(SemanticError(acnEncSpec.loc, (sprintf "No ACN encoding specification was provided for component %s" c.Name.Value))) ) //detect acn inserted children which already defined in ASN.1 - acnChildren |> - List.choose(fun c -> match c.asn1Type with None -> None | Some pt -> (Some (c,pt))) |> - List.choose(fun (acnC,pt) -> + acnChildren |> + List.choose(fun c -> match c.asn1Type with None -> None | Some pt -> (Some (c,pt))) |> + List.choose(fun (acnC,pt) -> match children |> List.tryFind(fun asn1C -> asn1C.Name = acnC.name) with | None -> None | Some asn1C -> Some (asn1C, acnC, pt)) |> - List.iter(fun (asn1C, acnC, pt) -> + List.iter(fun (asn1C, acnC, pt) -> raise(SemanticError(acnC.name.Location, (sprintf "Component '%s' cannot be defined as an ACN inserted field. Remove the type '%s' from the ACN file or remove th component from the ANS.1 file" acnC.name.Value (pt.ToString())))) ) @@ -1211,30 +1192,30 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo foldMap(fun st acnChild -> match children |> Seq.tryFind (fun a -> a.Name = acnChild.name) with | Some x -> mergeChild (Some acnChild) x st - | None -> + | None -> match acnChild.asn1Type with | Some xx -> - let newType, nest = mapAcnParamTypeToAcnAcnInsertedType asn1 acn xx acnChild.childEncodingSpec.acnProperties (curPath@[SEQ_CHILD acnChild.name.Value]) st - AcnChild({AcnChild.Name = acnChild.name; id = ReferenceToType(curPath@[SEQ_CHILD acnChild.name.Value]); Type = newType; Comments = acnChild.comments |> Seq.toArray}), nest + let newType, nest = mapAcnParamTypeToAcnAcnInsertedType asn1 acn xx acnChild.childEncodingSpec.acnProperties (curPath@[SEQ_CHILD (acnChild.name.Value, false)]) st + AcnChild({AcnChild.Name = acnChild.name; id = ReferenceToType(curPath@[SEQ_CHILD (acnChild.name.Value, false)]); Type = newType; Comments = acnChild.comments |> Seq.toArray}), nest | None -> raise(SemanticError(acnChild.name.Location, (sprintf "invalid name %s" acnChild.name.Value)))) us1 - + let uperBitMaskSize = children |> Seq.filter(fun c -> c.Optionality.IsSome) |> Seq.length |> BigInteger let asn1Children = mergedChildren |> List.choose(fun c -> match c with Asn1Child c -> Some c | AcnChild _ -> None) let uperMaxChildrenSize = asn1Children |> List.map(fun x -> x.Type.uperMaxSizeInBits) |> Seq.sum let uperMinChildrenSize = asn1Children |> List.filter(fun x -> x.Optionality.IsNone) |> List.map(fun x -> x.Type.uperMinSizeInBits) |> Seq.sum - - let aligment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let alignmentSize = AcnEncodingClasses.getAlignmentSize aligment + + let alignment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let alignmentSize = AcnEncodingClasses.getAlignmentSize alignment let acnBitMaskSize = - mergedChildren |> + mergedChildren |> List.filter(fun c -> match c.Optionality with | Some AlwaysAbsent -> false | Some (Optional p) when p.acnPresentWhen.IsNone -> true | _ -> false) |> Seq.length |> BigInteger - let minChildrenSize = - mergedChildren |> + let minChildrenSize = + mergedChildren |> List.map(fun c -> match c.Optionality with | Some (Optional _) -> 0I @@ -1242,7 +1223,7 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo let maxChildrenSize = mergedChildren |> List.map(fun c -> c.acnMaxSizeInBits) |> Seq.sum let acnMaxSizeInBits = alignmentSize + acnBitMaskSize + maxChildrenSize let acnMinSizeInBits = alignmentSize + acnBitMaskSize + minChildrenSize - let acnProperties = + let acnProperties = { SequenceAcnProperties.postEncodingFunction = tryGetProp combinedProperties (fun x -> match x with POST_ENCODING_FUNCTION (md,fn) -> Some (PostEncodingFunction (md,fn)) | _ -> None); preDecodingFunction = tryGetProp combinedProperties (fun x -> match x with PRE_DECODING_FUNCTION (md,fn) -> Some (PreDecodingFunction (md,fn)) | _ -> None) @@ -1251,7 +1232,7 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo match asn1.args.mappingFunctionsModule with | Some _ -> () | None -> - let fncName = + let fncName = match acnProperties.postEncodingFunction with | Some (PostEncodingFunction fncName) -> Some fncName | None -> @@ -1265,31 +1246,31 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo *) Sequence ({Sequence.children = mergedChildren; acnProperties=acnProperties; cons=cons; withcons = wcons;uperMaxSizeInBits=uperBitMaskSize+uperMaxChildrenSize; uperMinSizeInBits=uperBitMaskSize+uperMinChildrenSize;acnMaxSizeInBits=acnMaxSizeInBits;acnMinSizeInBits=acnMinSizeInBits; typeDef=typeDef}), chus - | Asn1Ast.Choice children -> + | Asn1Ast.Choice children -> let childrenNameConstraints = t.Constraints@refTypeCons |> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint (_,w) -> Some w| _ -> None) |> List.collect id let myVisibleConstraints = t.Constraints@refTypeCons //|> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint _ -> None | _ -> Some c) let myNonVisibleConstraints = withCons //|> List.choose(fun c -> match c with Asn1Ast.WithComponentsConstraint _ -> None | _ -> Some c) let cons = myVisibleConstraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getChoiceConstraint asn1 t children) let wcons = myNonVisibleConstraints |> List.collect fixConstraint |> List.map (ConstraintsMapping.getChoiceConstraint asn1 t children) - let typeDef, us1 = getChoiceTypeDifition tfdArg us - + let typeDef, us1 = getChoiceTypeDefinition tfdArg us + let mergeChild (cc:ChildSpec option) (c:Asn1Ast.ChildInfo) (us:Asn1AcnMergeState)= let childNamedConstraints = childrenNameConstraints |> List.filter(fun x -> x.Name = c.Name) - let childWithCons = childNamedConstraints |> List.choose(fun nc -> nc.Contraint) - let asn1OptionalityFromWithComponents = - childNamedConstraints |> - List.choose(fun nc -> + let childWithCons = childNamedConstraints |> List.choose(fun nc -> nc.Constraint) + let asn1OptionalityFromWithComponents = + childNamedConstraints |> + List.choose(fun nc -> match nc.Mark with | Asn1Ast.NoMark -> None | Asn1Ast.MarkPresent -> Some ChoiceAlwaysPresent | Asn1Ast.MarkAbsent -> Some ChoiceAlwaysAbsent | Asn1Ast.MarkOptional -> None ) |> - Seq.distinct |> Seq.toList + Seq.distinct |> Seq.toList let newOptionality = match c.Optionality with - | None + | None | Some (Asn1Ast.Optional _) -> match asn1OptionalityFromWithComponents with | [] -> None @@ -1305,23 +1286,23 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo - let acnPresentWhenConditions = + let acnPresentWhenConditions = match cc with | None -> [] - | Some cc -> + | Some cc -> match tryGetProp cc.childEncodingSpec.acnProperties (fun x -> match x with PRESENT_WHEN e -> Some e | _ -> None) with | None -> [] - | Some lst -> - lst |> - List.choose(fun gp -> - match gp with - | GP_PresenceInt (p,v) -> Some (PresenceInt (p,v)) - | GP_PresenceStr (p,v) -> Some (PresenceStr (p,v)) + | Some lst -> + lst |> + List.choose(fun gp -> + match gp with + | GP_PresenceInt (p,v) -> Some (PresenceInt (p,v)) + | GP_PresenceStr (p,v) -> Some (PresenceStr (p,v)) | _ -> None) let present_when_name = match asn1.args.renamePolicy with - | AlwaysPrefixTypeName -> + | AlwaysPrefixTypeName -> let activeLang = match asn1.args.targetLanguages with | x1::_ -> x1 @@ -1340,17 +1321,17 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo match cc with - | None -> + | None -> let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[CH_CHILD (c.Name.Value, present_when_name, "")]) (enmItemTypeDefPath@[CH_CHILD (c.Name.Value, present_when_name, "")]) (typeDefPath@[CH_CHILD (c.Name.Value, present_when_name, "")]) None None [] childWithCons [] [] None None us {ChChildInfo.Name = c.Name; _c_name = c.c_name; _scala_name = c.scala_name; _ada_name = c.ada_name; Type = newChild; acnPresentWhenConditions = acnPresentWhenConditions; asn1Comments = c.Comments|> Seq.toList; acnComments = []; present_when_name = present_when_name; Optionality = newOptionality}, us1 | Some cc -> - let enumClassName = + let enumClassName = match us.args.targetLanguages with | Scala::x -> typeDef[Scala].typeName | _ -> "" let newChild, us1 = mergeType asn1 acn m c.Type (curPath@[CH_CHILD (c.Name.Value, present_when_name, enumClassName)]) (typeDefPath@[CH_CHILD (c.Name.Value, present_when_name, enumClassName)]) (enmItemTypeDefPath@[CH_CHILD (c.Name.Value, present_when_name, enumClassName)]) (Some cc.childEncodingSpec) None [] childWithCons cc.argumentList [] None None us {ChChildInfo.Name = c.Name; _c_name = c.c_name; _scala_name = c.scala_name; _ada_name = c.ada_name; Type = newChild; acnPresentWhenConditions = acnPresentWhenConditions; asn1Comments = c.Comments |> Seq.toList; acnComments = cc.comments ; present_when_name = present_when_name; Optionality = newOptionality}, us1 - let mergedChildren, chus = + let mergedChildren, chus = match acnType with | None -> children |> foldMap (fun st ch -> mergeChild None ch st) us1 | Some acnEncSpec -> @@ -1379,19 +1360,19 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo | [] -> () | x1::[] -> () | _ -> raise(SemanticError(t.Location,"Only one alternative can be marked as ALWAYS PRESENT")) - - let acnProperties = + + let acnProperties = {ChoiceAcnProperties.enumDeterminant = tryGetProp combinedProperties (fun x -> match x with CHOICE_DETERMINANT e -> Some e | _ -> None)} let acnLoc = acnType |> Option.map (fun z -> z.loc) let indexSize = GetChoiceUperDeterminantLengthInBits(BigInteger(Seq.length children)) let minChildSize = mergedChildren |> List.map(fun x -> x.Type.uperMinSizeInBits) |> Seq.min let maxChildSize = mergedChildren |> List.map(fun x -> x.Type.uperMaxSizeInBits) |> Seq.max - let aligment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let acnMinSizeInBits, acnMaxSizeInBits = AcnEncodingClasses.GetChoiceEncodingClass mergedChildren aligment t.Location acnProperties + let alignment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + let acnMinSizeInBits, acnMaxSizeInBits = AcnEncodingClasses.GetChoiceEncodingClass mergedChildren alignment t.Location acnProperties //let mergedChildren = // match asn1.args.renamePolicy with - // | AlwaysPrefixTypeName -> + // | AlwaysPrefixTypeName -> // let activeLang = // match asn1.args.targetLanguages |> List.exists ((=) C) with // | true -> C @@ -1399,30 +1380,30 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo // mergedChildren |> List.map(fun x -> {x with present_when_name = typeDef.[activeLang].typeName + "_" + x.present_when_name}) // | _ -> mergedChildren - Choice ({Choice.children = mergedChildren; acnProperties = acnProperties; cons=cons; withcons = wcons; - uperMaxSizeInBits=indexSize+maxChildSize; uperMinSizeInBits=indexSize+minChildSize; acnMinSizeInBits =acnMinSizeInBits; - acnMaxSizeInBits=acnMaxSizeInBits; acnLoc = acnLoc; typeDef=typeDef; defaultInitVal="null"}), chus + Choice ({Choice.children = mergedChildren; acnProperties = acnProperties; cons=cons; withcons = wcons; + uperMaxSizeInBits=indexSize+maxChildSize; uperMinSizeInBits=indexSize+minChildSize; acnMinSizeInBits =acnMinSizeInBits; + acnMaxSizeInBits=acnMaxSizeInBits; acnLoc = acnLoc; typeDef=typeDef}), chus - | Asn1Ast.ReferenceType rf -> + | Asn1Ast.ReferenceType rf -> let acnArguments = acnArgs let oldBaseType = Asn1Ast.GetBaseTypeByName rf.modName rf.tasName asn1 //t.Constraints@refTypeCons@withCons let withCompCons = withCons//allCons |> List.choose(fun c -> match c with Asn1Ast.WithComponentConstraint _ -> Some c| Asn1Ast.WithComponentsConstraint _ -> Some c | _ -> None) let restCons = t.Constraints@refTypeCons//allCons |> List.choose(fun c -> match c with Asn1Ast.WithComponentConstraint _ -> None | Asn1Ast.WithComponentsConstraint _ -> None | _ -> Some c) - let acnTypeAssig = tryFindAcnTypeByName rf.modName rf.tasName acn - let baseTypeAcnParams = - match acnTypeAssig with + let acnTypeAssign = tryFindAcnTypeByName rf.modName rf.tasName acn + let baseTypeAcnParams = + match acnTypeAssign with | None -> [] | Some x -> x.acnParameters - + let baseTypeAcnEncSpec = - match acnTypeAssig with + match acnTypeAssign with | None -> None | Some x -> Some x.typeEncodingSpec - let mergedAcnEncSpec = + let mergedAcnEncSpec = //if a reference type has a component constraint (i.e. it is actually a SEQUENCE, CHOICE or SEQUENCE OF) then we should not merge the ACN spec //We must take the the ACN specification only from this type and not the base type. The reason is that with the WITH COMONENTS constraints you can - //change the definition of the type (i.e. make child as always absent). + //change the definition of the type (i.e. make child as always absent). match t.Constraints@refTypeCons |> Seq.exists(fun c -> match c with Asn1Ast.WithComponentConstraint _ -> true | Asn1Ast.WithComponentsConstraint _ -> true | _ -> false) with | true -> acnType | false -> mergeAcnEncodingSpecs acnType baseTypeAcnEncSpec @@ -1435,19 +1416,19 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo | [] -> [MD rf.modName.Value; TA rf.tasName.Value] | _ -> typeDefPath let newEnmItemTypeDefPath = [MD rf.modName.Value; TA rf.tasName.Value] - //let typeDef, us1 = getRefereceTypeDefinition asn1 t {tfdArg with typeDefPath = newTypeDefPath; inferitInfo =inheritanceInfo } us - let typeDef, us1 = getRefereceTypeDefinition asn1 t {tfdArg with typeDefPath = newTypeDefPath} us + //let typeDef, us1 = getReferenceTypeDefinition asn1 t {tfdArg with typeDefPath = newTypeDefPath; inheritInfo =inheritanceInfo } us + let typeDef, us1 = getReferenceTypeDefinition asn1 t {tfdArg with typeDefPath = newTypeDefPath} us let hasChildren, hasAcnProps = match acnType with | None -> false, false - | Some acnEncSpec -> + | Some acnEncSpec -> let b1 = acnEncSpec.children.Length > 0 let b2 =acnEncSpec.acnProperties.Length>0 b1,b2 - - + + let resolvedType, us2 = mergeType asn1 acn m oldBaseType curPath newTypeDefPath newEnmItemTypeDefPath mergedAcnEncSpec (Some t.Location) restCons withCompCons acnArgs baseTypeAcnParams inheritanceInfo typeAssignmentInfo us1 - let hasExtraConstrainsOrChildrenOrAcnArgs = + let hasExtraConstrainsOrChildrenOrAcnArgs = let b1 = hasAdditionalConstraints || hasChildren || acnArguments.Length > 0 || hasAcnProps match resolvedType.Kind with | ReferenceType baseRef -> b1 || baseRef.hasExtraConstrainsOrChildrenOrAcnArgs @@ -1457,57 +1438,57 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo let toByte sizeInBits = sizeInBits/8I + (if sizeInBits % 8I = 0I then 0I else 1I) - - let aligment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) - let uperMinSizeInBits, uperMaxSizeInBits, acnMinSizeInBits, acnMaxSizeInBits, encodingOptions = + let alignment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + + let uperMinSizeInBits, uperMaxSizeInBits, acnMinSizeInBits, acnMaxSizeInBits, encodingOptions = match rf.refEnc with - | None -> + | None -> resolvedType.uperMinSizeInBits, resolvedType.uperMaxSizeInBits, resolvedType.acnMinSizeInBits, resolvedType.acnMaxSizeInBits, None - | Some ContainedInBitString -> + | Some ContainedInBitString -> let minSize = {SIZE.uper = resolvedType.uperMinSizeInBits; acn = resolvedType.acnMinSizeInBits} let maxSize = {SIZE.uper = resolvedType.uperMaxSizeInBits; acn = resolvedType.acnMaxSizeInBits} - let hasNCount = minSize.uper <> maxSize.uper + let hasNCount = minSize.uper <> maxSize.uper let uperMinSizeInBits, uperMaxSizeInBits = uPER.getSizeableTypeSize minSize.uper maxSize.uper 1I - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> { SizeableAcnProperties.sizeProp = getSizeableSizeProperty minSize.acn maxSize.acn acnErrLoc combinedProperties} | None -> {SizeableAcnProperties.sizeProp = None } - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBitStringEncodingClass aligment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetBitStringEncodingClass alignment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount uperMinSizeInBits, uperMaxSizeInBits, acnMinSizeInBits, acnMaxSizeInBits, (Some {EncodeWithinOctetOrBitStringProperties.acnEncodingClass = acnEncodingClass; octOrBitStr = ContainedInBitString; minSize = minSize; maxSize=maxSize}) - | Some ContainedInOctString -> + | Some ContainedInOctString -> let minSize = {SIZE.uper = toByte resolvedType.uperMinSizeInBits; acn = toByte resolvedType.acnMinSizeInBits} let maxSize = {SIZE.uper = toByte resolvedType.uperMaxSizeInBits; acn = toByte resolvedType.acnMaxSizeInBits} let hasNCount = (minSize.uper <> maxSize.uper) || (minSize.acn <> maxSize.acn) let uperMinSizeInBits, uperMaxSizeInBits = uPER.getSizeableTypeSize minSize.uper maxSize.uper 8I - let acnProperties = + let acnProperties = match acnErrLoc with | Some acnErrLoc -> {SizeableAcnProperties.sizeProp = getSizeableSizeProperty minSize.acn maxSize.acn acnErrLoc combinedProperties} | None -> {SizeableAcnProperties.sizeProp = None} - let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetOctetStringEncodingClass aligment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount + let acnEncodingClass, acnMinSizeInBits, acnMaxSizeInBits= AcnEncodingClasses.GetOctetStringEncodingClass alignment loc acnProperties uperMinSizeInBits uperMaxSizeInBits minSize.acn maxSize.acn hasNCount uperMinSizeInBits, uperMaxSizeInBits, acnMinSizeInBits, acnMaxSizeInBits, (Some {EncodeWithinOctetOrBitStringProperties.acnEncodingClass = acnEncodingClass; octOrBitStr = ContainedInOctString; minSize = minSize; maxSize=maxSize}) - let newRef = {ReferenceType.modName = rf.modName; tasName = rf.tasName; tabularized = rf.tabularized; acnArguments = acnArguments; resolvedType=resolvedType; hasConstraints = hasAdditionalConstraints; typeDef=typeDef; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits = uperMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; encodingOptions=encodingOptions; hasExtraConstrainsOrChildrenOrAcnArgs=hasExtraConstrainsOrChildrenOrAcnArgs; refCons = refCons; defaultInitVal = "null"} + let newRef = {ReferenceType.modName = rf.modName; tasName = rf.tasName; tabularized = rf.tabularized; acnArguments = acnArguments; resolvedType=resolvedType; hasConstraints = hasAdditionalConstraints; typeDef=typeDef; uperMaxSizeInBits = uperMaxSizeInBits; uperMinSizeInBits = uperMinSizeInBits; acnMaxSizeInBits = acnMaxSizeInBits; acnMinSizeInBits = acnMinSizeInBits; encodingOptions=encodingOptions; hasExtraConstrainsOrChildrenOrAcnArgs=hasExtraConstrainsOrChildrenOrAcnArgs; refCons = refCons} ReferenceType newRef, us2 - + { Asn1Type.Kind = asn1Kind id = ReferenceToType curPath - acnAligment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) + acnAlignment = tryGetProp combinedProperties (fun x -> match x with ALIGNTONEXT e -> Some e | _ -> None) Location = t.Location acnLocation = acnErrLoc acnParameters = acnParameters |> List.map(fun prm -> {prm with id = (ReferenceToType (curPath@[(PRM prm.name)]))}) - inheritInfo = inferitInfo + inheritInfo = inheritInfo typeAssignmentInfo = typeAssignmentInfo parameterizedTypeInstance = t.parameterizedTypeInstance moduleName = t.moduleName - acnEncSpecPostion = acnType |> Option.map (fun x -> x.postion) - acnEncSpecAntlrSubTree = + acnEncSpecPosition = acnType |> Option.map (fun x -> x.position) + acnEncSpecAntlrSubTree = match acnType with | None -> None | Some st -> st.antlrSubTree @@ -1516,17 +1497,17 @@ let rec private mergeType (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Mo }, kindState let private mergeTAS (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Module) (am:AcnModule option) (tas:Asn1Ast.TypeAssignment) (us:Asn1AcnMergeState) : (TypeAssignment*Asn1AcnMergeState) = -// let acnTas = +// let acnTas = // match am with // | None -> None // | Some x -> x.typeAssignments |> Seq.tryFind(fun z -> z.name = tas.Name) - let acnParameters, acnComments = - match tas.acnInfo with - | None -> [], [] + let acnParameters, acnComments = + match tas.acnInfo with + | None -> [], [] | Some acnTas -> acnTas.acnParameters, acnTas.comments let typeEncodingSpec = tas.Type.acnInfo let newType, us1 = mergeType asn1 acn m tas.Type [MD m.Name.Value; TA tas.Name.Value] [MD m.Name.Value; TA tas.Name.Value] [MD m.Name.Value; TA tas.Name.Value] typeEncodingSpec (*(acnTas |> Option.map(fun x -> x.typeEncodingSpec))*) None [] [] [] acnParameters None (Some (TypeAssignmentInfo {TypeAssignmentInfo.modName = m.Name.Value; tasName = tas.Name.Value})) us - let newTas = + let newTas = { TypeAssignment.Name = tas.Name c_name = tas.c_name @@ -1544,7 +1525,7 @@ let private mergeValueAssignment (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast. | Asn1Ast.ReferenceType rf -> (Some ({InheritanceInfo.modName = rf.modName.Value; tasName = rf.tasName.Value; hasAdditionalConstraints=false}))//(Some {InheritanceInfo.id = ReferenceToType [MD rf.modName.Value; TA rf.tasName.Value]; hasAdditionalConstraints=false}) | _ -> None let newType, us1 = mergeType asn1 acn m vas.Type [MD m.Name.Value; VA vas.Name.Value] [MD m.Name.Value; VA vas.Name.Value] [MD m.Name.Value; VA vas.Name.Value] None None [] [] [] [] inheritInfo (Some (ValueAssignmentInfo {ValueAssignmentInfo.modName = m.Name.Value; vasName = vas.Name.Value})) us - let newVas = + let newVas = { ValueAssignment.Name = vas.Name c_name = vas.c_name @@ -1559,7 +1540,7 @@ let private mergeModule (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Modul let acnModule = acn.files |> Seq.collect(fun f -> f.modules) |> Seq.tryFind (fun x -> x.name = m.Name) let newTases, us1 = m.TypeAssignments |> foldMap (fun st tas -> mergeTAS asn1 acn m acnModule tas st) us let newVaes, us2 = m.ValueAssignments |> foldMap (fun st vas -> mergeValueAssignment asn1 acn m acnModule vas st) us1 - let newModule = + let newModule = { Asn1Module.Name = m.Name TypeAssignments = newTases @@ -1567,18 +1548,18 @@ let private mergeModule (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (m:Asn1Ast.Asn1Modul Imports = m.Imports Exports = m.Exports Comments = m.Comments - postion = m.postion + position = m.position } newModule, us2 let private mergeFile (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (f:Asn1Ast.Asn1File) (us:Asn1AcnMergeState): (Asn1File*Asn1AcnMergeState) = let newModules, us1 = f.Modules |> foldMap (fun st m -> mergeModule asn1 acn m st) us - let newFile = + let newFile = { Asn1File.FileName = f.FileName Tokens = f.Tokens - Modules = newModules + Modules = newModules } newFile, us1 @@ -1586,10 +1567,10 @@ let private mergeFile (asn1:Asn1Ast.AstRoot) (acn:AcnAst) (f:Asn1Ast.Asn1File) ( //let rec registerPrimitiveTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKind) getRtlDefinitionFunc : (FE_PrimitiveTypeDefinition*Asn1AcnMergeState)= let mergeAsn1WithAcnAst (asn1:Asn1Ast.AstRoot) (acn:AcnGenericTypes.AcnAst ,acnParseResults:CommonTypes.AntlrParserResult list) = - let initialState = {Asn1AcnMergeState.allocatedTypeNames = []; allocatedFE_TypeDefinition= Map.empty; args = asn1.args; temporaryTypesAllocation = Map.empty} + let initialState = {Asn1AcnMergeState.allocatedTypeNames = []; allocatedFE_TypeDefinition= Map.empty; args = asn1.args; temporaryTypesAllocation = Map.empty} let state = seq { - for l in ProgrammingLanguage.AllLanguages do + for l in ProgrammingLanguage.AllLanguages do for f in asn1.Files do for m in f.Modules do for tas in m.TypeAssignments do @@ -1597,12 +1578,12 @@ let mergeAsn1WithAcnAst (asn1:Asn1Ast.AstRoot) (acn:AcnGenericTypes.AcnAst ,acnP let programUnit = ToC m.Name.Value let proposedTypedefName = ToC (asn1.args.TypePrefix + tas.Name.Value) yield (l, id, tas.Type, programUnit, proposedTypedefName) - } |> Seq.toList - |> foldMap (fun st (l, id, t, programUnit, proposedTypedefName) -> + } |> Seq.toList + |> foldMap (fun st (l, id, t, programUnit, proposedTypedefName) -> temporaryRegisterTypeDefinition st l id programUnit proposedTypedefName //match t.Kind with - //| Asn1Ast.ReferenceType rf -> registerAnyTypeDefinition asn1 t st l id (FEI_NewSubTypeDefinition (ReferenceToType [MD rf.modName.Value; TA rf.tasName.Value])) - //| _ -> registerAnyTypeDefinition asn1 t st l id FEI_NewTypeDefinition + //| Asn1Ast.ReferenceType rf -> registerAnyTypeDefinition asn1 t st l id (FEI_NewSubTypeDefinition (ReferenceToType [MD rf.modName.Value; TA rf.tasName.Value])) + //| _ -> registerAnyTypeDefinition asn1 t st l id FEI_NewTypeDefinition ) initialState |> snd //let acn = CreateAcnAst acnParseResults let files, finalState = asn1.Files |> foldMap (fun st f -> mergeFile asn1 acn f st) state diff --git a/FrontEndAst/AcnEncodingClasses.fs b/FrontEndAst/AcnEncodingClasses.fs index 9f830e33f..526e244d6 100644 --- a/FrontEndAst/AcnEncodingClasses.fs +++ b/FrontEndAst/AcnEncodingClasses.fs @@ -8,15 +8,15 @@ open Asn1Fold open Asn1AcnAstUtilFunctions open AcnGenericTypes -let getAlignmentSize (aligment: AcnAligment option) = - match aligment with +let getAlignmentSize (alignment: AcnAlignment option) = + match alignment with | None -> 0I | Some NextByte -> 7I | Some NextWord -> 15I | Some NextDWord -> 31I -let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment option) errLoc (p : IntegerAcnProperties) (uperMinSizeInBits:BigInteger) (uperMaxSizeInBits:BigInteger) isUnsigned= - let alignmentSize = getAlignmentSize aligment +let GetIntEncodingClass (integerSizeInBytes:BigInteger) (alignment: AcnAlignment option) errLoc (p : IntegerAcnProperties) (uperMinSizeInBits:BigInteger) (uperMaxSizeInBits:BigInteger) isUnsigned= + let alignmentSize = getAlignmentSize alignment let maxDigitsInInteger = match integerSizeInBytes with | _ when integerSizeInBytes = 8I && isUnsigned -> UInt64.MaxValue.ToString().Length @@ -26,37 +26,37 @@ let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment o | _ -> raise(SemanticError(errLoc, (sprintf "Unsuported integer size :%A" integerSizeInBytes))) let maxDigitsInInteger = BigInteger maxDigitsInInteger - - let encClass, minSizeInBits, maxSizeInBits = - match p.encodingProp.IsNone && p.sizeProp.IsNone && p.endiannessProp.IsNone with + + let encClass, minSizeInBits, maxSizeInBits = + match p.encodingProp.IsNone && p.sizeProp.IsNone && p.endiannessProp.IsNone with | true -> Integer_uPER, uperMinSizeInBits, uperMaxSizeInBits - | false -> - let endianess = + | false -> + let endianness = match p.endiannessProp with | Some e -> e | None -> BigEndianness - let encProp = + let encProp = match p.encodingProp with | Some e -> e | None -> raise(SemanticError(errLoc, "Mandatory ACN property 'encoding' is missing")) - let sizeProp = + let sizeProp = match p.sizeProp with | Some e -> e | None -> raise(SemanticError(errLoc, "Mandatory ACN property 'size' is missing")) let bUINT = isUnsigned let maxFxVal = integerSizeInBytes*8I - match encProp, sizeProp, endianess with + match encProp, sizeProp, endianness with | PosInt, _,_ when not bUINT -> raise(SemanticError(errLoc, "Acn property pos-int cannot be applied to signed INTEGER types")) - | PosInt, Fixed(fixedSizeInBits) , BigEndianness when fixedSizeInBits = 8I -> + | PosInt, Fixed(fixedSizeInBits) , BigEndianness when fixedSizeInBits = 8I -> match p.endiannessProp with | Some BigEndianness -> - let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" + let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" Console.Error.WriteLine(AntlrParse.formatSemanticWarning errLoc errMsg) | _ -> () PositiveInteger_ConstSize_8, 8I, 8I - | PosInt, Fixed(fixedSizeInBits) , LittleEndianness when fixedSizeInBits = 8I -> - let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" + | PosInt, Fixed(fixedSizeInBits) , LittleEndianness when fixedSizeInBits = 8I -> + let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" Console.Error.WriteLine(AntlrParse.formatSemanticWarning errLoc errMsg) PositiveInteger_ConstSize_8, 8I, 8I | PosInt, Fixed(fixedSizeInBits), BigEndianness when fixedSizeInBits = 16I-> PositiveInteger_ConstSize_big_endian_16, 16I, 16I @@ -72,12 +72,12 @@ let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment o | TwosComplement, Fixed(fixedSizeInBits) , BigEndianness when fixedSizeInBits = 8I -> match p.endiannessProp with | Some BigEndianness -> - let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" + let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" Console.Error.WriteLine(AntlrParse.formatSemanticWarning errLoc errMsg) | _ -> () TwosComplement_ConstSize_8, 8I, 8I - | TwosComplement, Fixed(fixedSizeInBits) , LittleEndianness when fixedSizeInBits = 8I -> - let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" + | TwosComplement, Fixed(fixedSizeInBits) , LittleEndianness when fixedSizeInBits = 8I -> + let errMsg = "endianness property has not effect here.\nLittle/big endian can be applied only for fixed size encodings and size must be 16 or 32 or 64\n" Console.Error.WriteLine(AntlrParse.formatSemanticWarning errLoc errMsg) TwosComplement_ConstSize_8, 8I, 8I | TwosComplement, Fixed(fixedSizeInBits), BigEndianness when fixedSizeInBits = 16I -> TwosComplement_ConstSize_big_endian_16, 16I, 16I @@ -91,7 +91,7 @@ let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment o | TwosComplement, IntNullTerminated _, _ -> raise(SemanticError(errLoc, "Acn properties twos-complement and null-terminated are mutually exclusive")) | IntAscii, Fixed(fxVal) , BigEndianness when fxVal > maxDigitsInInteger*8I+8I -> raise(SemanticError(errLoc, (sprintf "Size must be less than %A" (maxDigitsInInteger*8I+8I)))) | IntAscii, Fixed(fxVal) , BigEndianness when fxVal % 8I <> 0I -> raise(SemanticError(errLoc, "size value should be multiple of 8")) - | IntAscii, Fixed(fxVal) , BigEndianness -> + | IntAscii, Fixed(fxVal) , BigEndianness -> match bUINT with | true -> ASCII_UINT_ConstSize fxVal, fxVal, fxVal | false -> ASCII_ConstSize fxVal, fxVal, fxVal @@ -99,7 +99,7 @@ let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment o | BCD, Fixed(fxVal) , BigEndianness when fxVal % 4I <> 0I -> raise(SemanticError(errLoc, "size value should be multiple of 4")) | BCD, Fixed(fxVal) , BigEndianness -> BCD_ConstSize fxVal, fxVal, fxVal | BCD, IntNullTerminated b, BigEndianness -> BCD_VarSize_NullTerminated b, 4I, 4I+maxDigitsInInteger*4I - | IntAscii, IntNullTerminated nullBytes, BigEndianness -> + | IntAscii, IntNullTerminated nullBytes, BigEndianness -> let nullBytesLength = BigInteger (nullBytes.Length*8) match bUINT with | true -> ASCII_UINT_VarSize_NullTerminated nullBytes, nullBytesLength, nullBytesLength + maxDigitsInInteger*8I @@ -110,137 +110,137 @@ let GetIntEncodingClass (integerSizeInBytes:BigInteger) (aligment: AcnAligment o encClass, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize -let GetEnumeratedEncodingClass (integerSizeInBytes:BigInteger) (items:NamedItem list) (aligment: AcnAligment option) errLoc (p : IntegerAcnProperties) uperMinSizeInBits uperMaxSizeInBits endodeValues = - match endodeValues with - | false -> - GetIntEncodingClass integerSizeInBytes aligment errLoc p uperMinSizeInBits uperMaxSizeInBits true - | true -> +let GetEnumeratedEncodingClass (integerSizeInBytes:BigInteger) (items:NamedItem list) (alignment: AcnAlignment option) errLoc (p : IntegerAcnProperties) uperMinSizeInBits uperMaxSizeInBits encodeValues = + match encodeValues with + | false -> + GetIntEncodingClass integerSizeInBytes alignment errLoc p uperMinSizeInBits uperMaxSizeInBits true + | true -> let minVal = items |> List.map(fun x -> x.acnEncodeValue) |> List.min let maxVal = items |> List.map(fun x -> x.acnEncodeValue) |> List.max let uperSizeForValues = GetNumberOfBitsForNonNegativeInteger(maxVal-minVal) - GetIntEncodingClass integerSizeInBytes aligment errLoc p uperSizeForValues uperSizeForValues (minVal >= 0I) + GetIntEncodingClass integerSizeInBytes alignment errLoc p uperSizeForValues uperSizeForValues (minVal >= 0I) (* - ###### - # # ###### ## # - # # # # # # - ###### ##### # # # - # # # ###### # - # # # # # # - # # ###### # # ###### - + ###### + # # ###### ## # + # # # # # # + ###### ##### # # # + # # # ###### # + # # # # # # + # # ###### # # ###### + *) -let GetRealEncodingClass (aligment: AcnAligment option) errLoc (p : RealAcnProperties) uperMinSizeInBits uperMaxSizeInBits = - let alignmentSize = getAlignmentSize aligment - let encClass, minSizeInBits, maxSizeInBits = - match p.encodingProp.IsNone && p.endiannessProp.IsNone with +let GetRealEncodingClass (alignment: AcnAlignment option) errLoc (p : RealAcnProperties) uperMinSizeInBits uperMaxSizeInBits = + let alignmentSize = getAlignmentSize alignment + let encClass, minSizeInBits, maxSizeInBits = + match p.encodingProp.IsNone && p.endiannessProp.IsNone with | true -> Real_uPER, uperMinSizeInBits, uperMaxSizeInBits | false -> - let endianess = + let endianness = match p.endiannessProp with | Some e -> e | None -> BigEndianness - let encProp = + let encProp = match p.encodingProp with | Some e -> e | None -> raise(SemanticError(errLoc, "Mandatory ACN property 'encoding' is missing")) - match encProp, endianess with + match encProp, endianness with | IEEE754_32, BigEndianness -> Real_IEEE754_32_big_endian, 32I, 32I | IEEE754_64, BigEndianness -> Real_IEEE754_64_big_endian, 64I, 64I | IEEE754_32, LittleEndianness -> Real_IEEE754_32_little_endian, 32I, 32I | IEEE754_64, LittleEndianness -> Real_IEEE754_64_little_endian, 64I, 64I - encClass, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize + encClass, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize (* - ### # ####### ##### - # # # # # # ##### ##### # # # #### - # # # # # # # # # ## # # # - # # # ###### ##### # # # # # # # # - # ####### # # # ##### # # # # # ### - # # # # # # # # # # # # ## # # - ### # # ##### ##### # # # # # # #### + ### # ####### ##### + # # # # # # ##### ##### # # # #### + # # # # # # # # # ## # # # + # # # ###### ##### # # # # # # # # + # ####### # # # ##### # # # # # ### + # # # # # # # # # # # # ## # # + ### # # ##### ##### # # # # # # #### *) -let GetStringEncodingClass (aligment: AcnAligment option) errLoc (p : StringAcnProperties) (uperMinSizeInBits:BigInteger) (uperMaxSizeInBits:BigInteger) (asn1Min:BigInteger) (asn1Max:BigInteger) alphaSet = - let alignmentSize = getAlignmentSize aligment +let GetStringEncodingClass (alignment: AcnAlignment option) errLoc (p : StringAcnProperties) (uperMinSizeInBits:BigInteger) (uperMaxSizeInBits:BigInteger) (asn1Min:BigInteger) (asn1Max:BigInteger) alphaSet = + let alignmentSize = getAlignmentSize alignment let lengthDeterminantSize = GetNumberOfBitsForNonNegativeInteger (asn1Max-asn1Min) - let bAsciiEncoding = + let bAsciiEncoding = match p.encodingProp with | Some StrAscii -> true | None -> false let charSizeInBits = match bAsciiEncoding with | true -> 8I - | false -> + | false -> let allowedBytes = alphaSet |> Array.map(fun c -> (System.Text.Encoding.ASCII.GetBytes (c.ToString())).[0]) |> Set.ofArray GetNumberOfBitsForNonNegativeInteger (BigInteger(alphaSet.Length - 1)) - let encClass, minSizeInBits, maxSizeInBits = + let encClass, minSizeInBits, maxSizeInBits = match bAsciiEncoding, p.sizeProp with | false, None -> Acn_Enc_String_uPER charSizeInBits, uperMinSizeInBits, uperMaxSizeInBits | false, Some (StrExternalField longField) -> Acn_Enc_String_CharIndex_External_Field_Determinant (charSizeInBits, longField) , asn1Min*charSizeInBits, asn1Max*charSizeInBits | false, Some (StrNullTerminated b) -> raise(BugErrorException(sprintf "when a string type has the acn property 'size null-terminated' it must also have the acn property 'encoding ASCII'" )) | true, None -> Acn_Enc_String_uPER_Ascii charSizeInBits, lengthDeterminantSize + asn1Min*charSizeInBits, lengthDeterminantSize + asn1Max*charSizeInBits | true, Some (StrExternalField longField) -> Acn_Enc_String_Ascii_External_Field_Determinant (charSizeInBits, longField), asn1Min*charSizeInBits, asn1Max*charSizeInBits - | true, Some (StrNullTerminated nullChars) -> Acn_Enc_String_Ascii_Null_Teminated (charSizeInBits, nullChars), asn1Min*charSizeInBits + (BigInteger (nullChars.Length * 8)), asn1Max*charSizeInBits + (BigInteger (nullChars.Length * 8)) + | true, Some (StrNullTerminated nullChars) -> Acn_Enc_String_Ascii_Null_Terminated (charSizeInBits, nullChars), asn1Min*charSizeInBits + (BigInteger (nullChars.Length * 8)), asn1Max*charSizeInBits + (BigInteger (nullChars.Length * 8)) encClass, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize //banner text from this link //http://patorjk.com/software/taag/#p=display&v=2&f=ANSI%20Shadow&t=Octet%20String%0A (* - ███████╗███████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗███████╗ ██████╗ ███████╗ ██████╗ ██████╗████████╗███████╗████████╗ ██╗██████╗ ██╗████████╗ ███████╗████████╗██████╗ ██╗███╗ ██╗ ██████╗ -██╔════╝██╔════╝██╔═══██╗██║ ██║██╔════╝████╗ ██║██╔════╝██╔════╝ ██╔═══██╗██╔════╝ ██╔═══██╗██╔════╝╚══██╔══╝██╔════╝╚══██╔══╝██╔╝██╔══██╗██║╚══██╔══╝ ██╔════╝╚══██╔══╝██╔══██╗██║████╗ ██║██╔════╝ + ███████╗███████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗███████╗ ██████╗ ███████╗ ██████╗ ██████╗████████╗███████╗████████╗ ██╗██████╗ ██╗████████╗ ███████╗████████╗██████╗ ██╗███╗ ██╗ ██████╗ +██╔════╝██╔════╝██╔═══██╗██║ ██║██╔════╝████╗ ██║██╔════╝██╔════╝ ██╔═══██╗██╔════╝ ██╔═══██╗██╔════╝╚══██╔══╝██╔════╝╚══██╔══╝██╔╝██╔══██╗██║╚══██╔══╝ ██╔════╝╚══██╔══╝██╔══██╗██║████╗ ██║██╔════╝ ███████╗█████╗ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║██║ █████╗ ██║ ██║█████╗ ██║ ██║██║ ██║ █████╗ ██║ ██╔╝ ██████╔╝██║ ██║ ███████╗ ██║ ██████╔╝██║██╔██╗ ██║██║ ███╗ ╚════██║██╔══╝ ██║▄▄ ██║██║ ██║██╔══╝ ██║╚██╗██║██║ ██╔══╝ ██║ ██║██╔══╝ ██║ ██║██║ ██║ ██╔══╝ ██║ ██╔╝ ██╔══██╗██║ ██║ ╚════██║ ██║ ██╔══██╗██║██║╚██╗██║██║ ██║ ███████║███████╗╚██████╔╝╚██████╔╝███████╗██║ ╚████║╚██████╗███████╗ ╚██████╔╝██║ ╚██████╔╝╚██████╗ ██║ ███████╗ ██║██╔╝ ██████╔╝██║ ██║ ███████║ ██║ ██║ ██║██║██║ ╚████║╚██████╔╝ -╚══════╝╚══════╝ ╚══▀▀═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝ +╚══════╝╚══════╝ ╚══▀▀═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝ *) -let GetOctetBitSeqofEncodingClass (aligment: AcnAligment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize bOcteOrBitString hasNCount = - let alignmentSize = getAlignmentSize aligment - - let encClass, minSizeInBits, maxSizeInBits = +let GetOctetBitSeqofEncodingClass (alignment: AcnAlignment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize bOcteOrBitString hasNCount = + let alignmentSize = getAlignmentSize alignment + + let encClass, minSizeInBits, maxSizeInBits = match p.sizeProp with - | None -> + | None -> match hasNCount with | false -> SZ_EC_FIXED_SIZE, asn1Min*internalMaxSize, asn1Max*internalMaxSize - | true -> + | true -> let lenSize = GetNumberOfBitsForNonNegativeInteger(asn1Max-asn1Min) - SZ_EC_LENGTH_EMBEDDED lenSize, asn1Min*internalMaxSize + lenSize, asn1Max*internalMaxSize + lenSize + SZ_EC_LENGTH_EMBEDDED lenSize, asn1Min*internalMaxSize + lenSize, asn1Max*internalMaxSize + lenSize //let minSizeInBits, maxSizeInBits = uPER.getSizeableTypeSize asn1Min asn1Max internalMaxSize //SZ_EC_uPER, minSizeInBits, maxSizeInBits - | Some p -> + | Some p -> match p with | SzExternalField p -> SZ_EC_ExternalField p, asn1Min*internalMinSize, asn1Max*internalMaxSize | SzNullTerminated tp -> SZ_EC_TerminationPattern tp, (BigInteger tp.Value.Length) + asn1Min*internalMinSize, (BigInteger tp.Value.Length) + asn1Max*internalMaxSize encClass, minSizeInBits+alignmentSize, maxSizeInBits+alignmentSize -let GetOctetStringEncodingClass (aligment: AcnAligment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max hasNCount = - GetOctetBitSeqofEncodingClass aligment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max 8I 8I true hasNCount +let GetOctetStringEncodingClass (alignment: AcnAlignment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max hasNCount = + GetOctetBitSeqofEncodingClass alignment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max 8I 8I true hasNCount -let GetBitStringEncodingClass (aligment: AcnAligment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max hasNCount = - GetOctetBitSeqofEncodingClass aligment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max 1I 1I true hasNCount +let GetBitStringEncodingClass (alignment: AcnAlignment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max hasNCount = + GetOctetBitSeqofEncodingClass alignment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max 1I 1I true hasNCount -let GetSequenceOfEncodingClass (aligment: AcnAligment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize hasNCount = - GetOctetBitSeqofEncodingClass aligment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize false hasNCount +let GetSequenceOfEncodingClass (alignment: AcnAlignment option) errLoc (p : SizeableAcnProperties) uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize hasNCount = + GetOctetBitSeqofEncodingClass alignment errLoc p uperMinSizeInBits uperMaxSizeInBits asn1Min asn1Max internalMinSize internalMaxSize false hasNCount -let GetNullEncodingClass (aligment: AcnAligment option) errLoc (p : NullTypeAcnProperties) = - let alignmentSize = getAlignmentSize aligment +let GetNullEncodingClass (alignment: AcnAlignment option) errLoc (p : NullTypeAcnProperties) = + let alignmentSize = getAlignmentSize alignment match p.encodingPattern with | None -> alignmentSize, alignmentSize | Some (PATTERN_PROP_BITSTR_VALUE p) -> alignmentSize + p.Value.Length.AsBigInt, alignmentSize + p.Value.Length.AsBigInt | Some (PATTERN_PROP_OCTSTR_VALUE p) -> alignmentSize + (p.Length*8).AsBigInt, alignmentSize + (p.Length*8).AsBigInt -let GetBooleanEncodingClass (aligment: AcnAligment option) errLoc (p : BooleanAcnProperties) = - let alignmentSize = getAlignmentSize aligment +let GetBooleanEncodingClass (alignment: AcnAlignment option) errLoc (p : BooleanAcnProperties) = + let alignmentSize = getAlignmentSize alignment match p.encodingPattern with | None -> alignmentSize + 1I, alignmentSize + 1I | Some (TrueValue p) -> alignmentSize + p.Value.Length.AsBigInt, alignmentSize + p.Value.Length.AsBigInt @@ -248,16 +248,16 @@ let GetBooleanEncodingClass (aligment: AcnAligment option) errLoc (p : BooleanA -let GetChoiceEncodingClass (children : ChChildInfo list) (aligment: AcnAligment option) errLoc (p : ChoiceAcnProperties) = +let GetChoiceEncodingClass (children : ChChildInfo list) (alignment: AcnAlignment option) errLoc (p : ChoiceAcnProperties) = let maxChildSize = children |> List.map(fun c -> c.Type.acnMaxSizeInBits) |> Seq.max let minChildSize = children |> List.map(fun c -> c.Type.acnMinSizeInBits) |> Seq.min - let alignmentSize = getAlignmentSize aligment + let alignmentSize = getAlignmentSize alignment - let presenceDeterminentByAcn = + let presenceDeterminantByAcn = p.enumDeterminant.IsSome || (children |> Seq.exists(fun z -> not z.acnPresentWhenConditions.IsEmpty)) - match presenceDeterminentByAcn with - | false -> + match presenceDeterminantByAcn with + | false -> let indexSize = GetChoiceUperDeterminantLengthInBits(BigInteger(Seq.length children)) alignmentSize + indexSize + minChildSize, alignmentSize + indexSize + maxChildSize | true -> diff --git a/FrontEndAst/AcnGenericCreateFromAntlr.fs b/FrontEndAst/AcnGenericCreateFromAntlr.fs index 737d1eb99..39b66ec07 100644 --- a/FrontEndAst/AcnGenericCreateFromAntlr.fs +++ b/FrontEndAst/AcnGenericCreateFromAntlr.fs @@ -49,15 +49,6 @@ type private AcnConstant = { type MyErr = Err1 | Err2 -let aaaa () = - let aa = result { - let! a = Ok "aaa" - let! b2 = Error 12 - let c = if a="23" then a else b2 - return c - } - 0 - let rec private EvaluateConstant (constants:AcnConstant list) intConstant : Result= match intConstant with | IntConst(a) -> Ok a.Value @@ -66,24 +57,24 @@ let rec private EvaluateConstant (constants:AcnConstant list) intConstant : Resu |None -> Error (Semantic_Error(consLookUp.Location, (sprintf "Unknown symbol '%s'" consLookUp.Value))) |Some(cn) -> EvaluateAcnIntExpression constants cn.Value -and private EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr : Result = +and private EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr : Result = match acnExpr with | IntegerExpr(consta) -> EvaluateConstant constants consta - | UnMinExp(exp1) -> //-(EvaluateAcnIntExpression constants exp1) + | UnMinExp(exp1) -> //-(EvaluateAcnIntExpression constants exp1) result { let! a1 = EvaluateAcnIntExpression constants exp1 return -a1; } - | SumExpr(exp1,exp2) - | MinExpr(exp1,exp2) - | MulExpr(exp1,exp2) - | DivExpr(exp1,exp2) - | ModExpr(exp1,exp2) - | PowExpr(exp1,exp2) -> + | SumExpr(exp1,exp2) + | MinExpr(exp1,exp2) + | MulExpr(exp1,exp2) + | DivExpr(exp1,exp2) + | ModExpr(exp1,exp2) + | PowExpr(exp1,exp2) -> result { let! a1 = EvaluateAcnIntExpression constants exp1 let! a2 = EvaluateAcnIntExpression constants exp2 - let! c = + let! c = match acnExpr with | SumExpr(_,_) -> Ok (a1 + a2) | MinExpr(_,_) -> Ok (a1 - a2) @@ -104,14 +95,14 @@ and private EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr : Res let private CreateLongField(t:ITree) = t.Children |> List.map(fun x -> x.TextL) |> AcnGenericTypes.RelativePath let private CreateAcnParamType (t:ITree) : Result = - + match t.Type with | acnParser.INTEGER -> Ok (AcnGenericTypes.AcnParamType.AcnPrmInteger t.Location ) | acnParser.BOOLEAN -> Ok (AcnGenericTypes.AcnParamType.AcnPrmBoolean t.Location ) | acnParser.NULL -> Ok (AcnGenericTypes.AcnParamType.AcnPrmNullType t.Location ) - | acnParser.REFERENCED_TYPE -> + | acnParser.REFERENCED_TYPE -> result { - let! (mdName, tsName) = + let! (mdName, tsName) = match t.Children with | first::[] -> Ok (first.GetAncestor(acnParser.MODULE_DEF).GetChild(0).TextL,first.TextL) | first::sec::[] -> Ok (first.TextL,sec.TextL) @@ -136,34 +127,34 @@ let private GetParams (files:CommonTypes.AntlrParserResult list) modName tasName files |> List.map (fun pr -> GetParamsAux pr.rootItem) |> List.collect(fun x -> x) -let rec createPresentWhenBoooExpresssion (t:ITree) integerSizeInBytes : Result = +let rec createPresentWhenBoolExpresssion (t:ITree) integerSizeInBytes : Result = result { match t.Type with | acnParser.INT -> return (IntegerConstantExp(t.BigIntL integerSizeInBytes)) | acnParser.UID -> return (AcnIntegerConstExp(t.TextL)) | acnParser.REAL -> return (RealConstantExp(t.DoubleL)) | acnParser.LONG_FIELD -> return (Asn1LongField (CreateLongField t)) - | acnParser.OR - | acnParser.AND - | acnParser.EQUAL - | acnParser.NOTEQUAL - | acnParser.LTE - | acnParser.LT - | acnParser.GTE - | acnParser.GT - | acnParser.EQUAL - | acnParser.NOTEQUAL - | acnParser.LTE - | acnParser.LT - | acnParser.GTE - | acnParser.GT - | acnParser.MULTIPLICATION - | acnParser.DIVISION + | acnParser.OR + | acnParser.AND + | acnParser.EQUAL + | acnParser.NOTEQUAL + | acnParser.LTE + | acnParser.LT + | acnParser.GTE + | acnParser.GT + | acnParser.EQUAL + | acnParser.NOTEQUAL + | acnParser.LTE + | acnParser.LT + | acnParser.GTE + | acnParser.GT + | acnParser.MULTIPLICATION + | acnParser.DIVISION | acnParser.MODULO -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes - let! a2 = createPresentWhenBoooExpresssion (t.GetChild 1) integerSizeInBytes - let! ret = + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes + let! a2 = createPresentWhenBoolExpresssion (t.GetChild 1) integerSizeInBytes + let! ret = match t.Type with | acnParser.OR -> Ok( OrExpression(t.Location, a1, a2) ) | acnParser.AND -> Ok( AndExpression(t.Location, a1, a2) ) @@ -173,54 +164,54 @@ let rec createPresentWhenBoooExpresssion (t:ITree) integerSizeInBytes : Result Ok( LessThanExpression(t.Location, a1, a2) ) | acnParser.GTE -> Ok( GreaterThanEqualExpression(t.Location, a1, a2) ) | acnParser.GT -> Ok( GreaterThanExpression(t.Location, a1, a2) ) - | acnParser.MULTIPLICATION -> Ok( MultipicationExpression(t.Location, a1, a2) ) + | acnParser.MULTIPLICATION -> Ok( MultiplicationExpression(t.Location, a1, a2) ) | acnParser.DIVISION -> Ok( DivisionExpression(t.Location, a1, a2)) | acnParser.MODULO -> Ok( ModuloExpression(t.Location, a1, a2)) - | _ -> Error (Bug_Error "createPresentWhenBoooExpresssion") + | _ -> Error (Bug_Error "createPresentWhenBoolExpresssion") return ret - | acnParser.PLUS when t.Children.Length > 1 -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes - let! a2 = createPresentWhenBoooExpresssion (t.GetChild 1) integerSizeInBytes + | acnParser.PLUS when t.Children.Length > 1 -> + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes + let! a2 = createPresentWhenBoolExpresssion (t.GetChild 1) integerSizeInBytes return AdditionExpression(t.Location, a1, a2) - | acnParser.MINUS when t.Children.Length > 1 -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes - let! a2 = createPresentWhenBoooExpresssion (t.GetChild 1) integerSizeInBytes + | acnParser.MINUS when t.Children.Length > 1 -> + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes + let! a2 = createPresentWhenBoolExpresssion (t.GetChild 1) integerSizeInBytes return SubtractionExpression(t.Location, a1, a2) - | acnParser.PLUS (*unary*) -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes + | acnParser.PLUS (*unary*) -> + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes return a1 - | acnParser.MINUS (*unary*) -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes - return MinusUnaryExpression(t.Location, a1) - | acnParser.BANG (*unary*) -> - let! a1 = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes + | acnParser.MINUS (*unary*) -> + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes + return MinusUnaryExpression(t.Location, a1) + | acnParser.BANG (*unary*) -> + let! a1 = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes return NotUnaryExpression(t.Location, a1) - | _ -> - let! e = Error (Bug_Error("createPresentWhenBoooExpresssion Unsupported operation")) + | _ -> + let! e = Error (Bug_Error("createPresentWhenBoolExpresssion Unsupported operation")) return e } -let private CreateNamedExpression integerSizeInBytes (t:ITree) : Result= - let CreateAcnIntegerConstant (t:ITree) = +let private CreateNamedExpression integerSizeInBytes (t:ITree) : Result= + let CreateAcnIntegerConstant (t:ITree) = match t.Type with | acnParser.INT -> Ok (IntConst(t.BigIntL integerSizeInBytes)) | acnParser.UID -> Ok (RefConst(t.TextL)) | _ -> Error (Bug_Error("AcnCreateFromAntlr::CreateAcnIntegerConstant")) - let rec CreateExpression (t:ITree) = + let rec CreateExpression (t:ITree) = result { match t.Type with - | acnParser.INT | acnParser.UID -> + | acnParser.INT | acnParser.UID -> let! a1 = CreateAcnIntegerConstant t return IntegerExpr(a1) - | acnParser.PLUS - | acnParser.MINUS - | acnParser.MULTIPLICATION - | acnParser.DIVISION - | acnParser.MODULO + | acnParser.PLUS + | acnParser.MINUS + | acnParser.MULTIPLICATION + | acnParser.DIVISION + | acnParser.MODULO | acnParser.POWER_SYMBOL -> let! a1 = CreateExpression (t.GetChild(0)) let! a2 = CreateExpression (t.GetChild(1)) @@ -234,10 +225,10 @@ let private CreateNamedExpression integerSizeInBytes (t:ITree) : Result let! e = Error (Bug_Error "CreateExpression") return e - | acnParser.UNARY_MINUS -> + | acnParser.UNARY_MINUS -> let! a1 = CreateExpression (t.GetChild(0)) return UnMinExp(a1) - | _ -> + | _ -> let! e = Error (Bug_Error "AcnCreateFromAntlr::CreateExpression Unsupported operator") return e } @@ -251,16 +242,16 @@ let private CreateNamedExpression integerSizeInBytes (t:ITree) : Result) (t:ITree) : Result = - let CreateAcnIntegerConstant (t:ITree) : Result = +let private createAcnProperty integerSizeInBytes (acnConstants : Map) (t:ITree) : Result = + let CreateAcnIntegerConstant (t:ITree) : Result = match t.Type with | acnParser.INT -> Ok (t.BigIntL integerSizeInBytes) - | acnParser.UID -> + | acnParser.UID -> match acnConstants.TryFind t.Text with | Some ret -> Ok ({IntLoc.Location = t.Location; Value=ret}) | None -> Error (Semantic_Error(t.Location, (sprintf "No ACN constant is defined with name '%s'" t.Text))) | _ -> Error (Bug_Error("AcnCreateFromAntlr::CreateAcnIntegerConstant")) - let GetActualString (str:string) = + let GetActualString (str:string) = let strVal = str.Substring(1) strVal.Remove(strVal.Length-2).Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "") @@ -273,62 +264,62 @@ let private creareAcnProperty integerSizeInBytes (acnConstants : Map Ok (ENCODING GP_Ascii ) | acnParser.IEEE754_1985_32 -> Ok (ENCODING GP_IEEE754_32 ) | acnParser.IEEE754_1985_64 -> Ok (ENCODING GP_IEEE754_64 ) - | _ -> Error (Bug_Error("creareAcnProperty_ENCODING")) + | _ -> Error (Bug_Error("createAcnProperty_ENCODING")) | acnParser.SIZE -> result { match t.GetChild(0).Type with | acnParser.NULL_TERMINATED -> return SIZE GP_NullTerminated - | acnParser.INT - | acnParser.UID -> + | acnParser.INT + | acnParser.UID -> let! exp = CreateAcnIntegerConstant (t.GetChild 0) return (SIZE (GP_Fixed exp) ) | acnParser.LONG_FIELD -> return (SIZE (GP_SizeDeterminant (CreateLongField (t.GetChild 0)) )) - | _ -> - let! e = Error (Bug_Error("creareAcnProperty_SIZE")) + | _ -> + let! e = Error (Bug_Error("createAcnProperty_SIZE")) return e } | acnParser.ALIGNTONEXT -> - match t.GetChild(0).Type with + match t.GetChild(0).Type with | acnParser.BYTE -> Ok( ALIGNTONEXT AcnGenericTypes.NextByte ) | acnParser.WORD -> Ok( ALIGNTONEXT AcnGenericTypes.NextWord ) | acnParser.DWORD -> Ok( ALIGNTONEXT AcnGenericTypes.NextDWord ) - | _ -> Error (Bug_Error("creareAcnProperty_ALIGNTONEXT")) + | _ -> Error (Bug_Error("createAcnProperty_ALIGNTONEXT")) | acnParser.ENCODE_VALUES -> Ok ENCODE_VALUES | acnParser.SAVE_POSITION -> Ok SAVE_POSITION - | acnParser.PRESENT_WHEN -> - let CreateAcnPresenseCondition(t:ITree) = + | acnParser.PRESENT_WHEN -> + let CreateAcnPresenseCondition(t:ITree) = result { match t.Type with | acnParser.LONG_FIELD -> return (GP_PresenceBool(CreateLongField t)) - | acnParser.EQUAL -> + | acnParser.EQUAL -> let! exp = CreateAcnIntegerConstant (t.GetChild 1) return (GP_PresenceInt ((CreateLongField(t.GetChild 0)), exp)) - | acnParser.PRESENT_WHEN_STR_EQUAL -> + | acnParser.PRESENT_WHEN_STR_EQUAL -> let txt = (t.GetChild 1).Text.Replace("\"","") let txtL = { StringLoc.Value = txt; Location = (t.GetChild 1).Location} return (GP_PresenceStr ((CreateLongField(t.GetChild 0)), txtL )) - | _ -> - let! e = Error (Bug_Error("creareAcnProperty_PRESENT_WHEN")) + | _ -> + let! e = Error (Bug_Error("createAcnProperty_PRESENT_WHEN")) return e } result { //let! aaa = t.Children |> List.map CreateAcnPresenseCondition |> List.sequenceResultM - let! aaa = t.Children |> List.traverseResultM CreateAcnPresenseCondition + let! aaa = t.Children |> List.traverseResultM CreateAcnPresenseCondition return PRESENT_WHEN (aaa ) } - | acnParser.PRESENT_WHEN_EXP -> + | acnParser.PRESENT_WHEN_EXP -> result { - let! retExp = createPresentWhenBoooExpresssion (t.GetChild 0) integerSizeInBytes + let! retExp = createPresentWhenBoolExpresssion (t.GetChild 0) integerSizeInBytes return PRESENT_WHEN_EXP retExp } - | acnParser.TRUE_VALUE -> + | acnParser.TRUE_VALUE -> let v = { StringLoc.Value = GetActualString(t.GetChild(0).Text); Location = t.GetChild(0).Location} Ok (TRUE_VALUE v) - | acnParser.FALSE_VALUE -> + | acnParser.FALSE_VALUE -> let v = { StringLoc.Value = GetActualString(t.GetChild(0).Text); Location = t.GetChild(0).Location} Ok (FALSE_VALUE v) - | acnParser.PATTERN -> + | acnParser.PATTERN -> //let tp = t match t.GetChild(0).Type with | acnParser.BitStringLiteral -> @@ -336,35 +327,35 @@ let private creareAcnProperty integerSizeInBytes (acnConstants : Map let strVal = GetActualString(t.GetChild(0).Text) - let chars = strVal.ToCharArray() - let bytes = FsUtils.getAsTupples chars '0' |> List.map (fun (x1,x2)-> t.GetValueL (System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier))) + let chars = strVal.ToCharArray() + let bytes = FsUtils.getAsTupples chars '0' |> List.map (fun (x1,x2)-> t.GetValueL (System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier))) Ok (PATTERN (AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE bytes)) - | _ -> raise(BugErrorException("creareAcnProperty_PATTERN")) - + | _ -> raise(BugErrorException("createAcnProperty_PATTERN")) + | acnParser.DETERMINANT -> Ok (CHOICE_DETERMINANT (CreateLongField(t.GetChild 0))) - | acnParser.ENDIANNES -> - match t.GetChild(0).Type with - | acnParser.BIG -> Ok (ENDIANNES AcnGenericTypes.BigEndianness) - | acnParser.LITTLE -> Ok (ENDIANNES AcnGenericTypes.LittleEndianness) - | _ -> Error (Bug_Error("creareAcnProperty_ENDIANNES")) - | acnParser.MAPPING_FUNCTION -> + | acnParser.ENDIANNESS -> + match t.GetChild(0).Type with + | acnParser.BIG -> Ok (ENDIANNESS AcnGenericTypes.BigEndianness) + | acnParser.LITTLE -> Ok (ENDIANNESS AcnGenericTypes.LittleEndianness) + | _ -> Error (Bug_Error("createAcnProperty_ENDIANNES")) + | acnParser.MAPPING_FUNCTION -> match t.ChildCount > 1 with | false -> Ok (MAPPING_FUNCTION (None, t.GetChild(0).TextL)) | true -> Ok (MAPPING_FUNCTION (Some (t.GetChild(0).TextL), t.GetChild(2).TextL)) - | acnParser.POST_ENCODING_FUNCTION -> + | acnParser.POST_ENCODING_FUNCTION -> match t.ChildCount > 1 with | false -> Ok (POST_ENCODING_FUNCTION (None, t.GetChild(0).TextL)) | true -> Ok (POST_ENCODING_FUNCTION (Some (t.GetChild(0).TextL), t.GetChild(2).TextL)) - | acnParser.POST_DECODING_VALIDATOR -> + | acnParser.POST_DECODING_VALIDATOR -> match t.ChildCount > 1 with | false -> Ok (PRE_DECODING_FUNCTION (None, t.GetChild(0).TextL)) | true -> Ok (PRE_DECODING_FUNCTION (Some (t.GetChild(0).TextL), t.GetChild(2).TextL)) | acnParser.INT -> Ok (ENUM_SET_VALUE (t.BigIntL integerSizeInBytes)) - | acnParser.TERMINATION_PATTERN -> + | acnParser.TERMINATION_PATTERN -> let tp = t result { - let! bitPattern = + let! bitPattern = let literal = GetActualString (tp.GetChild(0).Text) match tp.GetChild(0).Type with | acnParser.BitStringLiteral -> @@ -372,7 +363,7 @@ let private creareAcnProperty integerSizeInBytes (acnConstants : Map let byteArr = octetStringLiteralToByteArray literal Ok ({ StringLoc.Value = byteArrayToBitStringValue byteArr; Location = tp.GetChild(0).Location}) - | _ -> Error (Bug_Error("creareAcnProperty_TERMINATION_PATTERN")) + | _ -> Error (Bug_Error("createAcnProperty_TERMINATION_PATTERN")) return (TERMINATION_PATTERN bitPattern) } @@ -383,17 +374,17 @@ let private creareAcnProperty integerSizeInBytes (acnConstants : Map) (thisAcnFile: CommonTypes.AntlrParserResult) (alreadyTakenComments:System.Collections.Generic.List) (encSpecITree:ITree) : Result = result { - let! acnProperties = + let! acnProperties = match encSpecITree.GetOptChild(acnParser.ENCODING_PROPERTIES) with | None -> Ok [] - | Some(propList) -> propList.Children |> List.traverseResultM (creareAcnProperty integerSizeInBytes acnConstants) - - let! children = + | Some(propList) -> propList.Children |> List.traverseResultM (createAcnProperty integerSizeInBytes acnConstants) + + let! children = match encSpecITree.GetOptChild(acnParser.CHILDREN_ENC_SPEC) with | Some childrenList -> let createChild (t:ITree) = result { - let name = + let name = match t.GetOptChild(acnParser.LID) with | None -> StringLoc.ByValue "#" | Some(lid) -> lid.TextL @@ -402,15 +393,15 @@ let rec private createTypeEncodingSpec integerSizeInBytes (allAcnFiles: CommonT | None -> [] | Some(argList) -> argList.Children |> List.map CreateLongField let comments = Antlr.Comment.GetComments(thisAcnFile.tokens, alreadyTakenComments, thisAcnFile.tokens.[t.TokenStopIndex].Line, t.TokenStartIndex - 1, t.TokenStopIndex + 2, true) - let! childEncodingSpec = createTypeEncodingSpec integerSizeInBytes allAcnFiles acnConstants thisAcnFile alreadyTakenComments (t.GetChildByType acnParser.ENCODING_SPEC) + let! childEncodingSpec = createTypeEncodingSpec integerSizeInBytes allAcnFiles acnConstants thisAcnFile alreadyTakenComments (t.GetChildByType acnParser.ENCODING_SPEC) let! asn1Type = result { match t.Type with | acnParser.CHILD -> return None - | acnParser.CHILD_NEW -> + | acnParser.CHILD_NEW -> let! p = CreateAcnParamType (t.GetChild 1) return (Some p ) - | _ -> + | _ -> let! e = Error (Bug_Error("createTypeEncodingSpec_CHILD")) return e } @@ -421,7 +412,7 @@ let rec private createTypeEncodingSpec integerSizeInBytes (allAcnFiles: CommonT | None -> Ok [] let pos = encSpecITree.Location, (encSpecITree.GetChildByType(acnParser.R_SBRACKET)).Location - return {AcnTypeEncodingSpec.acnProperties = acnProperties; children = children; loc = encSpecITree.Location; comments=[]; postion = pos; antlrSubTree = Some encSpecITree} + return {AcnTypeEncodingSpec.acnProperties = acnProperties; children = children; loc = encSpecITree.Location; comments=[]; position = pos; antlrSubTree = Some encSpecITree} } let private CreateTypeAssignment integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) (acnConstants : Map) (thisAcnFile: CommonTypes.AntlrParserResult) (alreadyTakenComments:System.Collections.Generic.List) (tasTree:ITree) : Result = @@ -429,10 +420,10 @@ let private CreateTypeAssignment integerSizeInBytes (allAcnFiles: CommonTypes.An let tasNameL = tasTree.GetChildByType(acnParser.UID).TextL let encSpecITree = tasTree.GetChildByType(acnParser.ENCODING_SPEC) - let! prms = + let! prms = match tasTree.GetOptChild(acnParser.PARAM_LIST) with | None -> Ok [] - | Some(paramList) -> + | Some(paramList) -> let CreateParam (x:ITree) = result { let prmName = x.GetChild(1).Text @@ -440,12 +431,12 @@ let private CreateTypeAssignment integerSizeInBytes (allAcnFiles: CommonTypes.An //check that all parameters are used let refs = encSpecITree.AllChildren |> List.filter(fun x -> x.Type = acnParser.LONG_FIELD && x.ChildCount=1) |> List.map(fun x -> x.GetChild(0).Text) match refs |> Seq.tryFind(fun x -> x = prmName) with - | Some(_) -> + | Some(_) -> //parameter id is initially set to an invalid value. //It takes the correct value when the ASN.1 is constructed. let! t = CreateAcnParamType (x.GetChild(0)) return {AcnGenericTypes.AcnParameter.name = prmName; AcnGenericTypes.AcnParameter.asn1Type=t ; AcnGenericTypes.AcnParameter.loc = loc; AcnGenericTypes.id = ReferenceToType([]) } - | None -> + | None -> let! e = Error(Semantic_Error(loc, sprintf "unreferenced parameter '%s'" prmName)) return e } @@ -456,28 +447,28 @@ let private CreateTypeAssignment integerSizeInBytes (allAcnFiles: CommonTypes.An //tasTree.TokenStartIndex let acnFile = allAcnFiles |> Seq.find(fun z -> z.rootItem = tasTree.Root) let pos = { - RangeWithinFile.filename= tasTree.Root.FileName; + RangeWithinFile.filename= tasTree.Root.FileName; startPos= let startToken = acnFile.tokens.[tasTree.TokenStartIndex] - {|line=startToken.Line;charPos=startToken.CharPositionInLine |}; + {|line=startToken.Line;charPos=startToken.CharPositionInLine |}; endPos= let endToken = acnFile.tokens.[tasTree.TokenStopIndex] {|line=endToken.Line;charPos=endToken.CharPositionInLine + tasTree.Text.Length|} } return {AcnTypeAssignment.name = tasNameL; acnParameters = prms; typeEncodingSpec = typeEncodingSpec; comments = comments |> Seq.toList; position=pos} } - + let private CreateModule integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) (acnConstants : Map) (thisAcnFile: CommonTypes.AntlrParserResult) (alreadyTakenComments:System.Collections.Generic.List) (modTree : ITree) : Result = result { let modNameL = modTree.GetChildByType(acnParser.UID).TextL let tasITreeList = modTree.GetChildrenByType(acnParser.TYPE_ENCODING) - + //check for duplicate type assignments in the ACN module do! tasITreeList |> List.map(fun x -> x.GetChildByType(acnParser.UID).TextL) |> CheckForDuplicates2 - let! newTasses = tasITreeList |> List.traverseResultM (fun tasTree -> CreateTypeAssignment integerSizeInBytes allAcnFiles acnConstants thisAcnFile alreadyTakenComments tasTree) - + let! newTasses = tasITreeList |> List.traverseResultM (fun tasTree -> CreateTypeAssignment integerSizeInBytes allAcnFiles acnConstants thisAcnFile alreadyTakenComments tasTree) + return {AcnModule.name = modNameL; typeAssignments = newTasses} } @@ -491,17 +482,17 @@ let private CheckCircularDependenciesInAcnConstants (constants : List) : match t.Type with | acnParser.UID -> return [t.TextL] | acnParser.INT -> return [] - | acnParser.PLUS |acnParser.MINUS | acnParser.MULTIPLICATION | acnParser.DIVISION | acnParser.MODULO | acnParser.POWER_SYMBOL -> + | acnParser.PLUS |acnParser.MINUS | acnParser.MULTIPLICATION | acnParser.DIVISION | acnParser.MODULO | acnParser.POWER_SYMBOL -> let! child1Names = GetNamesFromExpr (t.GetChild(0)) let! child2Names = GetNamesFromExpr (t.GetChild(1)) return child1Names@child2Names - | acnParser.UNARY_MINUS -> - let! childNames = GetNamesFromExpr (t.GetChild(0)) + | acnParser.UNARY_MINUS -> + let! childNames = GetNamesFromExpr (t.GetChild(0)) return childNames - | _ -> + | _ -> let! e = Error (Bug_Error("CheckCircularDependenciesInAcnConstants.HandleConstant.GetNamesFromExpr Unsupported operator")) return e - } + } result { let! e = GetNamesFromExpr (t.GetChild(1)) return (t.GetChild(0).TextL, e) @@ -509,29 +500,29 @@ let private CheckCircularDependenciesInAcnConstants (constants : List) : result { let! constantsExpanded = constants |> List.traverseResultM HandleConstant let independentConstants = constantsExpanded |> List.filter(fun (nm, lst) -> lst.IsEmpty ) |> List.map fst - let dependentConstansts = constantsExpanded |> List.filter(fun (nm, lst) -> not (lst.IsEmpty) ) + let dependentConstants = constantsExpanded |> List.filter(fun (nm, lst) -> not (lst.IsEmpty) ) let comparer (s1:StringLoc) (s2:StringLoc) = s1.Value = s2.Value - let aa = DoTopologicalSort2_noexc independentConstants dependentConstansts comparer + let aa = DoTopologicalSort2_noexc independentConstants dependentConstants comparer match aa with | Ok _ -> Ok() |> ignore | Error cyclicDepds -> match cyclicDepds with - | [] -> + | [] -> let! e = Error (Bug_Error("")) return e - | (x,_)::xs -> - let printConstant (md:StringLoc, deps: StringLoc list) = + | (x,_)::xs -> + let printConstant (md:StringLoc, deps: StringLoc list) = sprintf "Anc constant '%s' depends on : %s" md.Value (deps |> List.map(fun z -> "'" + z.Value + "'") |> Seq.StrJoin ", ") let names = cyclicDepds |> List.map printConstant |> Seq.StrJoin "\n\tand\n" //let names = cyclicDepds |> Seq.map (fun (n,_) -> n.Value) |> Seq.StrJoin ", " let! e = Error (Semantic_Error(x.Location, sprintf "Cyclic dependencies in ACN constants: %s" names)) return e - + } -let private LoadAcnFile integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) (acnConstants : Map) (thisAcnFile: CommonTypes.AntlrParserResult) : Result = +let private LoadAcnFile integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) (acnConstants : Map) (thisAcnFile: CommonTypes.AntlrParserResult) : Result = result { let alreadyTakenComments = new System.Collections.Generic.List(); @@ -539,7 +530,7 @@ let private LoadAcnFile integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParser return {AcnFile.antlrResult = thisAcnFile; modules = modules} } -let CreateAcnAst_no_exc integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) : Result = +let CreateAcnAst_no_exc integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) : Result = result { ITree.RegisterFiles(allAcnFiles|> Seq.map(fun pr -> (pr.rootItem, pr.fileName))) let constants = seq { @@ -551,26 +542,26 @@ let CreateAcnAst_no_exc integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParse let constantNames = constants |> List.map(fun c -> c.GetChild(0).TextL) // check that all constant names are unique - do! constantNames |> CheckForDuplicates2 + do! constantNames |> CheckForDuplicates2 do! CheckCircularDependenciesInAcnConstants constants let! constantValues = constants |> List.traverseResultM (CreateNamedExpression integerSizeInBytes) - let! acnConstantsList = - constantValues |> - List.traverseResultM(fun c -> - result { + let! acnConstantsList = + constantValues |> + List.traverseResultM(fun c -> + result { let! e = EvaluateAcnIntExpression constantValues c.Value return (c.Name.Value, e) } - ) + ) let acnConstantsMap = acnConstantsList |> Map.ofList let! acnFiles = allAcnFiles |> List.traverseResultM (LoadAcnFile integerSizeInBytes allAcnFiles acnConstantsMap) return {AcnAst.files = acnFiles; acnConstants = acnConstantsMap} } -let CreateAcnAst integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) : AcnAst = +let CreateAcnAst integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult list) : AcnAst = match CreateAcnAst_no_exc integerSizeInBytes allAcnFiles with | Ok ret -> ret | Error(Semantic_Error(l,m)) -> raise (SemanticError(l,m)) @@ -579,22 +570,22 @@ let CreateAcnAst integerSizeInBytes (allAcnFiles: CommonTypes.AntlrParserResult let someTests () = - + let c1 = IntegerExpr(IntConst (IntLoc.ByValue 100I)) - + let constants = [{AcnConstant.Name = StringLoc.ByValue "t"; Value = IntegerExpr(IntConst (IntLoc.ByValue 100I))}] - - + + let e1 = IntegerExpr(IntConst (IntLoc.ByValue 10I)) let e2 = IntegerExpr(RefConst (StringLoc.ByValue "z")) let add12 = SumExpr(e2,e1) let res = EvaluateAcnIntExpression constants add12 - + match res with | Ok (a1) -> printfn "%A" a1 - | Error (Semantic_Error(_,e)) + | Error (Semantic_Error(_,e)) | Error (User_Error e) | Error (Bug_Error e) -> printfn "%A" e @@ -608,7 +599,7 @@ let tryFindAcnTypeByName modName tasName (r:AcnAst) = let rec printDebug (exp:AcnExpression) : (int*string) = - let printUnary op e1 mp = + let printUnary op e1 mp = let cp, ct = printDebug e1 mp, if cp >= mp then sprintf "%s(%s)" op ct else sprintf "%s%s" op ct let printBinary op e1 e2 mp = @@ -625,7 +616,7 @@ let rec printDebug (exp:AcnExpression) : (int*string) = | MinusUnaryExpression (_,e1) -> printUnary "-" e1 1 | AdditionExpression (_,e1, e2) -> printBinary "+" e1 e2 3 // 1, sprintf "(%s) + (%s)" (printDebug e1) (printDebug e2) | SubtractionExpression (_,e1, e2) -> printBinary "-" e1 e2 3 //3, sprintf "(%s) - (%s)" (printDebug e1) (printDebug e2) - | MultipicationExpression (_,e1, e2) -> printBinary "*" e1 e2 2 //3, sprintf "(%s) * (%s)" (printDebug e1) (printDebug e2) + | MultiplicationExpression (_,e1, e2) -> printBinary "*" e1 e2 2 //3, sprintf "(%s) * (%s)" (printDebug e1) (printDebug e2) | DivisionExpression (_,e1, e2) -> printBinary "/" e1 e2 2 //2, sprintf "(%s) / (%s)" (printDebug e1) (printDebug e2) | ModuloExpression (_,e1, e2) -> printBinary "%" e1 e2 2 //2, sprintf "(%s) %% (%s)" (printDebug e1) (printDebug e2) | LessThanEqualExpression (_,e1, e2) -> printBinary "<=" e1 e2 4 //4, sprintf "(%s) <= (%s)" (printDebug e1) (printDebug e2) diff --git a/FrontEndAst/AcnType2.fs b/FrontEndAst/AcnType2.fs index 92cb6d1ca..07909dcb6 100644 --- a/FrontEndAst/AcnType2.fs +++ b/FrontEndAst/AcnType2.fs @@ -2,7 +2,7 @@ open FsUtils open System.Numerics -type RelativePath = +type RelativePath = | RelativePath of string list @@ -43,7 +43,7 @@ type AcnEndianness = | LittleEndianness | BigEndianness // Default -type AcnAligment = +type AcnAlignment = | NextByte | NextWord | NextDWord @@ -55,10 +55,10 @@ type AcnSizeProperty = -type AcnProperty = +type AcnProperty = | Encoding of AcnEncoding // used by int, real, enum | SizeProperty of AcnSizeProperty // used by int, real, and all sizeable types - | Aligment of AcnAligment // * + | Alignment of AcnAlignment // * | EncodeValues // used by enums => values will be encoded and not indexes | BooleanEncoding of AcnBooleanEncoding // bool | NullValue of StringLoc // null @@ -66,11 +66,11 @@ type AcnProperty = | EnumeratorResetValue of string*BigInteger // used by enum children to redefine values | MappingFunction of StringLoc // used by int with - override this.ToString() = + override this.ToString() = match this with | Encoding enc -> sprintf "encoding %A" enc | SizeProperty sz -> sprintf "size %A" sz - | Aligment al -> sprintf "aligment %A" al + | Alignment al -> sprintf "alignment %A" al | EncodeValues -> "encode-values" | BooleanEncoding ben -> sprintf "pattern '%A'" ben | NullValue pattern -> sprintf "pattern '%s'" pattern.Value @@ -78,11 +78,11 @@ with | EnumeratorResetValue (enChildName,vl) -> enChildName + vl.ToString() | MappingFunction funcName -> funcName.Value -// present when property defintion +// present when property definition // this property is not part of the ACN type itself but part of the AcnChildInfo type PresentWhenCondition = - | PresenceBool of RelativePath // applied to SEQEUNCE or Choice child - | PresenceInt of RelativePath*AcnIntegerConstant // applied to SEQEUNCE or Choice child + | PresenceBool of RelativePath // applied to SEQUENCE or Choice child + | PresenceInt of RelativePath*AcnIntegerConstant // applied to SEQUENCE or Choice child | PresenceStr of RelativePath*string diff --git a/FrontEndAst/AcnTypes.fs b/FrontEndAst/AcnTypes.fs index c263ed4a5..b32b552bb 100644 --- a/FrontEndAst/AcnTypes.fs +++ b/FrontEndAst/AcnTypes.fs @@ -50,10 +50,10 @@ type AcnConstant = { Value : AcnIntExpr } -type AcnProperty = +type AcnProperty = | Encoding of encoding // used by int, real, enum | SizeProperty of sizeProperty // used by int, real, and all sizeable types - | Aligment of aligment // * + | Alignment of alignment // * | EncodeValues // used by enums => values will be encoded and not indexes | BooleanEncoding of booleanEncoding // bool | NullValue of StringLoc // null @@ -61,11 +61,11 @@ type AcnProperty = | EnumeratorResetValue of string*BigInteger // used by enum children to redefine values | MappingFunction of StringLoc // used by int with - override this.ToString() = + override this.ToString() = match this with | Encoding enc -> sprintf "encoding %A" enc | SizeProperty sz -> sprintf "size %A" sz - | Aligment al -> sprintf "aligment %A" al + | Alignment al -> sprintf "alignment %A" al | EncodeValues -> "encode-values" | BooleanEncoding ben -> sprintf "pattern '%A'" ben | NullValue pattern -> sprintf "pattern '%s'" pattern.Value @@ -73,7 +73,7 @@ with | EnumeratorResetValue (enChildName,vl) -> enChildName + vl.ToString() | MappingFunction funcName -> funcName.Value -and aligment = +and alignment = | NextByte | NextWord | NextDWord @@ -107,12 +107,12 @@ type ParamMode = type AcnType = { TypeID : AbsPath ImpMode : AcnTypeImplMode - Properties : list //does not contain the properties with long fields + Properties : list //does not contain the properties with long fields Location : SrcLoc Comments: string array acnParameters : AcnParameter list } -with +with override x.ToString() = x.TypeID |> Seq.StrJoin "." and AcnTempType = { // this type is not encoded decoded. It is declared locally at the tas level // and it is used for passing values @@ -146,11 +146,11 @@ type LongReference = { Kind : LongReferenceKind Location : SrcLoc } -with - override x.ToString() = +with + override x.ToString() = let decType = x.TypeID |> Seq.StrJoin "." - let determnant = x.LongRef |> Seq.StrJoin "." - sprintf "%s %s %s" decType (x.Kind.ToString() ) determnant + let determinant = x.LongRef |> Seq.StrJoin "." + sprintf "%s %s %s" decType (x.Kind.ToString() ) determinant and Point = @@ -160,29 +160,29 @@ and Point = member x.AbsPath = match x with TypePoint(a) | ParamPoint(a) | TempPoint(a) -> a member x.ReplacePath newPath = - match x with + match x with | TypePoint(_) -> TypePoint newPath | ParamPoint(_) -> ParamPoint newPath | TempPoint(a) -> TempPoint newPath -and LongReferenceKind = +and LongReferenceKind = //| SizeDeterminant // points to an integer type that acts as a size determinant to a SEQUENCE OF, BIT STRINT, OCTET STRING etc | RefTypeArgument of string // string is the param name - | PresenceBool // points to a SEQEUNCE or Choice child - | PresenceInt of acnIntegerConstant // points to a SEQEUNCE or Choice child + | PresenceBool // points to a SEQUENCE or Choice child + | PresenceInt of acnIntegerConstant // points to a SEQUENCE or Choice child | PresenceStr of string - | ChoiceDeteterminant // points to Enumerated type acting as CHOICE determinant. + | ChoiceDeterminant // points to Enumerated type acting as CHOICE determinant. with - override x.ToString() = + override x.ToString() = match x with //| SizeDeterminant -> "size" | RefTypeArgument argName -> sprintf "RefArg<%s>" argName | PresenceBool -> "present-when-bool" | PresenceInt vl -> sprintf "present-when-int %A" vl | PresenceStr stVal -> sprintf "present-when-str %s" stVal - | ChoiceDeteterminant -> "choice-determinant" + | ChoiceDeterminant -> "choice-determinant" type AcnAst = { Constants : list @@ -193,25 +193,25 @@ type AcnAst = { let rec EvaluateConstant (constants:list) intConstant = - let rec EvaluateConstantAux = function + let rec EvaluateConstantAux = function | IntegerExpr(consta) -> EvaluateConstant constants consta | SumExpr(exp1,exp2) -> (EvaluateConstantAux exp1) + (EvaluateConstantAux exp2) | MinExpr(exp1,exp2) -> (EvaluateConstantAux exp1) - (EvaluateConstantAux exp2) | MulExpr(exp1,exp2) -> (EvaluateConstantAux exp1) * (EvaluateConstantAux exp2) | DivExpr(exp1,exp2) -> (EvaluateConstantAux exp1) / (EvaluateConstantAux exp2) | ModExpr(exp1,exp2) -> (EvaluateConstantAux exp1) % (EvaluateConstantAux exp2) - | PowExpr(exp1,exp2) -> + | PowExpr(exp1,exp2) -> System.Numerics.BigInteger.Pow(EvaluateConstantAux exp1, int (EvaluateConstantAux exp2)) - | UnMinExp(exp1) -> -(EvaluateConstantAux exp1) + | UnMinExp(exp1) -> -(EvaluateConstantAux exp1) match intConstant with | IntConst(a) -> a.Value | RefConst(consLookUp) -> match constants |> Seq.tryFind(fun c-> c.Name.Value = consLookUp.Value) with |None -> raise(SemanticError(consLookUp.Location, (sprintf "Unknown symbol '%s'" consLookUp.Value))) |Some(cn) -> EvaluateConstantAux cn.Value - - + + diff --git a/FrontEndAst/Asn1AcnAst.fs b/FrontEndAst/Asn1AcnAst.fs index 920d99652..96384fc40 100644 --- a/FrontEndAst/Asn1AcnAst.fs +++ b/FrontEndAst/Asn1AcnAst.fs @@ -36,7 +36,7 @@ type SeqOfValue = list and SeqValue = list and ChValue = NamedValue and RefValue = ((StringLoc*StringLoc)*Asn1Value) -and ObjectIdenfierValue = ((ResolvedObjectIdentifierValueCompoent list)*(ObjectIdentifierValueCompoent list)) +and ObjectIdentifierValue = ((ResolvedObjectIdentifierValueComponent list)*(ObjectIdentifierValueComponent list)) and NamedValue = { name : StringLoc @@ -50,20 +50,20 @@ and Asn1Value = { } and Asn1ValueKind = - | IntegerValue of IntegerValue - | RealValue of RealValue + | IntegerValue of IntegerValue + | RealValue of RealValue | StringValue of (SingleStringValue list*SrcLoc) - | BooleanValue of BooleanValue - | BitStringValue of BitStringValue + | BooleanValue of BooleanValue + | BitStringValue of BitStringValue | TimeValue of TimeValue | OctetStringValue of OctetStringValue - | EnumValue of EnumValue - | SeqOfValue of SeqOfValue - | SeqValue of SeqValue - | ChValue of ChValue + | EnumValue of EnumValue + | SeqOfValue of SeqOfValue + | SeqValue of SeqValue + | ChValue of ChValue | NullValue of NullValue - | RefValue of RefValue - | ObjOrRelObjIdValue of ObjectIdenfierValue + | RefValue of RefValue + | ObjOrRelObjIdValue of ObjectIdentifierValue ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -72,14 +72,14 @@ and Asn1ValueKind = type GenericConstraint<'v> = - | UnionConstraint of string*GenericConstraint<'v>*GenericConstraint<'v>*bool //left,righ, virtual constraint + | UnionConstraint of string*GenericConstraint<'v>*GenericConstraint<'v>*bool //left,right, virtual constraint | IntersectionConstraint of string*GenericConstraint<'v>*GenericConstraint<'v> | AllExceptConstraint of string*GenericConstraint<'v> | ExceptConstraint of string*GenericConstraint<'v>*GenericConstraint<'v> | RootConstraint of string*GenericConstraint<'v> | RootConstraint2 of string*GenericConstraint<'v>*GenericConstraint<'v> | SingleValueConstraint of string*'v - with + with member this.ASN1 = match this with @@ -92,17 +92,17 @@ type GenericConstraint<'v> = | SingleValueConstraint (s,_) -> s -type RangeTypeConstraint<'v1,'v2> = - | RangeUnionConstraint of string*RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2>*bool //left,righ, virtual constraint +type RangeTypeConstraint<'v1,'v2> = + | RangeUnionConstraint of string*RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2>*bool //left,right, virtual constraint | RangeIntersectionConstraint of string*RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeAllExceptConstraint of string*RangeTypeConstraint<'v1,'v2> | RangeExceptConstraint of string*RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeRootConstraint of string*RangeTypeConstraint<'v1,'v2> | RangeRootConstraint2 of string*RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeSingleValueConstraint of string*'v2 - | RangeContraint of string*('v1) *('v1)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | RangeContraint_val_MAX of string*('v1) *bool //min, InclusiveMin(=true) - | RangeContraint_MIN_val of string*('v1) *bool //max, InclusiveMax(=true) + | RangeConstraint of string*('v1) *('v1)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | RangeConstraint_val_MAX of string*('v1) *bool //min, InclusiveMin(=true) + | RangeConstraint_MIN_val of string*('v1) *bool //max, InclusiveMax(=true) with member this.ASN1 = match this with @@ -113,28 +113,28 @@ type RangeTypeConstraint<'v1,'v2> = | RangeRootConstraint (s,_) -> s | RangeRootConstraint2 (s,_,_) -> s | RangeSingleValueConstraint (s,_) -> s - | RangeContraint (s,_,_,_,_) -> s - | RangeContraint_val_MAX (s,_,_) -> s - | RangeContraint_MIN_val (s,_,_) -> s + | RangeConstraint (s,_,_,_,_) -> s + | RangeConstraint_val_MAX (s,_,_) -> s + | RangeConstraint_MIN_val (s,_,_) -> s type IntegerTypeConstraint = RangeTypeConstraint type PosIntTypeConstraint = RangeTypeConstraint type CharTypeConstraint = RangeTypeConstraint - + type RealTypeConstraint = RangeTypeConstraint -type SizableTypeConstraint<'v> = - | SizeUnionConstraint of string*SizableTypeConstraint<'v>*SizableTypeConstraint<'v>*bool //left,righ, virtual constraint +type SizableTypeConstraint<'v> = + | SizeUnionConstraint of string*SizableTypeConstraint<'v>*SizableTypeConstraint<'v>*bool //left,right, virtual constraint | SizeIntersectionConstraint of string*SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeAllExceptConstraint of string*SizableTypeConstraint<'v> | SizeExceptConstraint of string*SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeRootConstraint of string*SizableTypeConstraint<'v> | SizeRootConstraint2 of string*SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeSingleValueConstraint of string*'v - | SizeContraint of string*PosIntTypeConstraint - with + | SizeConstraint of string*PosIntTypeConstraint + with member this.ASN1 = match this with @@ -145,19 +145,19 @@ type SizableTypeConstraint<'v> = | SizeRootConstraint (s,_) -> s | SizeRootConstraint2 (s,_,_) -> s | SizeSingleValueConstraint (s,_) -> s - | SizeContraint (s,_) -> s + | SizeConstraint (s,_) -> s -type IA5StringConstraint = - | StrUnionConstraint of string*IA5StringConstraint*IA5StringConstraint*bool //left,righ, virtual constraint +type IA5StringConstraint = + | StrUnionConstraint of string*IA5StringConstraint*IA5StringConstraint*bool //left,right, virtual constraint | StrIntersectionConstraint of string*IA5StringConstraint*IA5StringConstraint | StrAllExceptConstraint of string*IA5StringConstraint | StrExceptConstraint of string*IA5StringConstraint*IA5StringConstraint | StrRootConstraint of string*IA5StringConstraint | StrRootConstraint2 of string*IA5StringConstraint*IA5StringConstraint | StrSingleValueConstraint of string*string - | StrSizeContraint of string*PosIntTypeConstraint - | AlphabetContraint of string*CharTypeConstraint - with + | StrSizeConstraint of string*PosIntTypeConstraint + | AlphabetConstraint of string*CharTypeConstraint + with member this.ASN1 = match this with @@ -168,8 +168,8 @@ type IA5StringConstraint = | StrRootConstraint (s,_) -> s | StrRootConstraint2 (s,_,_) -> s | StrSingleValueConstraint (s,_) -> s - | StrSizeContraint (s,_) -> s - | AlphabetContraint (s,_) -> s + | StrSizeConstraint (s,_) -> s + | AlphabetConstraint (s,_) -> s @@ -183,7 +183,7 @@ type OctetStringConstraint = SizableTypeConstraint type BoolConstraint = GenericConstraint type EnumConstraint = GenericConstraint -type ObjectIdConstraint = GenericConstraint +type ObjectIdConstraint = GenericConstraint type TimeConstraint = GenericConstraint @@ -191,15 +191,15 @@ type TimeConstraint = GenericConstraint //type SequenceConstraint = GenericConstraint type SeqOrChoiceConstraint<'v> = - | SeqOrChUnionConstraint of string*SeqOrChoiceConstraint<'v>*SeqOrChoiceConstraint<'v>*bool //left,righ, virtual constraint + | SeqOrChUnionConstraint of string*SeqOrChoiceConstraint<'v>*SeqOrChoiceConstraint<'v>*bool //left,right, virtual constraint | SeqOrChIntersectionConstraint of string*SeqOrChoiceConstraint<'v>*SeqOrChoiceConstraint<'v> | SeqOrChAllExceptConstraint of string*SeqOrChoiceConstraint<'v> | SeqOrChExceptConstraint of string*SeqOrChoiceConstraint<'v>*SeqOrChoiceConstraint<'v> | SeqOrChRootConstraint of string*SeqOrChoiceConstraint<'v> | SeqOrChRootConstraint2 of string*SeqOrChoiceConstraint<'v>*SeqOrChoiceConstraint<'v> | SeqOrChSingleValueConstraint of string*'v - | SeqOrChWithComponentsConstraint of string*NamedConstraint list - with + | SeqOrChWithComponentsConstraint of string*NamedConstraint list + with member this.ASN1 = match this with @@ -217,17 +217,17 @@ and SeqConstraint = SeqOrChoiceConstraint and ChoiceConstraint = SeqOrChoiceConstraint -and SequenceOfConstraint = - | SeqOfSizeUnionConstraint of string*SequenceOfConstraint*SequenceOfConstraint*bool //left,righ, virtual constraint +and SequenceOfConstraint = + | SeqOfSizeUnionConstraint of string*SequenceOfConstraint*SequenceOfConstraint*bool //left,right, virtual constraint | SeqOfSizeIntersectionConstraint of string*SequenceOfConstraint*SequenceOfConstraint | SeqOfSizeAllExceptConstraint of string*SequenceOfConstraint | SeqOfSizeExceptConstraint of string*SequenceOfConstraint*SequenceOfConstraint | SeqOfSizeRootConstraint of string*SequenceOfConstraint | SeqOfSizeRootConstraint2 of string*SequenceOfConstraint*SequenceOfConstraint | SeqOfSizeSingleValueConstraint of string*SeqOfValue - | SeqOfSizeContraint of string*PosIntTypeConstraint + | SeqOfSizeConstraint of string*PosIntTypeConstraint | SeqOfSeqWithComponentConstraint of string*AnyConstraint*SrcLoc - with + with member this.ASN1 = match this with @@ -238,25 +238,25 @@ and SequenceOfConstraint = | SeqOfSizeRootConstraint (s,_) -> s | SeqOfSizeRootConstraint2 (s,_,_) -> s | SeqOfSizeSingleValueConstraint (s,_) -> s - | SeqOfSizeContraint (s,_) -> s + | SeqOfSizeConstraint (s,_) -> s | SeqOfSeqWithComponentConstraint (s,_,_) -> s - + and AnyConstraint = | IntegerTypeConstraint of IntegerTypeConstraint - | IA5StringConstraint of IA5StringConstraint - | RealTypeConstraint of RealTypeConstraint + | IA5StringConstraint of IA5StringConstraint + | RealTypeConstraint of RealTypeConstraint | OctetStringConstraint of OctetStringConstraint | BitStringConstraint of BitStringConstraint - | BoolConstraint of BoolConstraint - | EnumConstraint of EnumConstraint + | BoolConstraint of BoolConstraint + | EnumConstraint of EnumConstraint | ObjectIdConstraint of ObjectIdConstraint | SequenceOfConstraint of SequenceOfConstraint | SeqConstraint of SeqConstraint | ChoiceConstraint of ChoiceConstraint - | NullConstraint + | NullConstraint | TimeConstraint of TimeConstraint - with + with member this.ASN1 = match this with @@ -273,11 +273,11 @@ and AnyConstraint = | ChoiceConstraint (x) -> x.ASN1 | NullConstraint -> "" | TimeConstraint (x) -> x.ASN1 - + and NamedConstraint = { Name: StringLoc - Contraint:AnyConstraint option + Constraint:AnyConstraint option Mark:Asn1Ast.NamedConstraintMark } @@ -288,9 +288,9 @@ type NamedItem = { scala_name:string ada_name:string definitionValue : BigInteger // the value in the header file - + // the value encoded by ACN. It can (a) the named item index (i.e. like uper), (b) The definition value, (c) The redefined value from acn properties - acnEncodeValue : BigInteger + acnEncodeValue : BigInteger Comments: string array } @@ -299,12 +299,12 @@ type Optional = { acnPresentWhen : PresenceWhenBool option } -type Asn1Optionality = +type Asn1Optionality = | AlwaysAbsent | AlwaysPresent | Optional of Optional -type Asn1ChoiceOptionality = +type Asn1ChoiceOptionality = | ChoiceAlwaysAbsent | ChoiceAlwaysPresent @@ -346,16 +346,16 @@ type RealEncodingClass = | Real_IEEE754_64_little_endian type StringAcnEncodingClass = - | Acn_Enc_String_uPER of BigInteger //char size in bits, as in uper + | Acn_Enc_String_uPER of BigInteger //char size in bits, as in uper | Acn_Enc_String_uPER_Ascii of BigInteger //char size in bits, as in uper but with charset (0..255) - | Acn_Enc_String_Ascii_Null_Teminated of BigInteger*(byte list) //char size in bits, byte = the null character + | Acn_Enc_String_Ascii_Null_Terminated of BigInteger*(byte list) //char size in bits, byte = the null character | Acn_Enc_String_Ascii_External_Field_Determinant of BigInteger*RelativePath //char size in bits, encode ascii, size is provided by an external length determinant | Acn_Enc_String_CharIndex_External_Field_Determinant of BigInteger*RelativePath //char size in bits, encode char index, size is provided by an external length determinant type SizeableAcnEncodingClass = - //| SZ_EC_uPER - | SZ_EC_FIXED_SIZE - | SZ_EC_LENGTH_EMBEDDED of BigInteger //embedded length determinant size in bits + //| SZ_EC_uPER + | SZ_EC_FIXED_SIZE + | SZ_EC_LENGTH_EMBEDDED of BigInteger //embedded length determinant size in bits | SZ_EC_ExternalField of RelativePath | SZ_EC_TerminationPattern of BitStringValue @@ -378,7 +378,7 @@ type DoubleUperRange = uperRange type UInt32UperRange = uperRange type IntegerClass = - | ASN1SCC_Int8 of BigInteger*BigInteger + | ASN1SCC_Int8 of BigInteger*BigInteger | ASN1SCC_Int16 of BigInteger*BigInteger | ASN1SCC_Int32 of BigInteger*BigInteger | ASN1SCC_Int64 of BigInteger*BigInteger @@ -443,7 +443,6 @@ type StringType = { acnEncodingClass : StringAcnEncodingClass isNumeric : bool typeDef : Map - defaultInitVal : String } @@ -477,7 +476,6 @@ type BitString = { acnEncodingClass : SizeableAcnEncodingClass typeDef : Map namedBitList : NamedBit1 list - defaultInitVal : String } type TimeType = { @@ -503,7 +501,7 @@ type NullType = { defaultInitVal : String } -type Boolean = { +type Boolean = { acnProperties : BooleanAcnProperties cons : BoolConstraint list withcons : BoolConstraint list @@ -515,7 +513,7 @@ type Boolean = { defaultInitVal : String } -type ObjectIdentifier = { +type ObjectIdentifier = { acnProperties : ObjectIdTypeAcnProperties cons : ObjectIdConstraint list withcons : ObjectIdConstraint list @@ -541,15 +539,13 @@ type Enumerated = { encodeValues : bool userDefinedValues : bool //if true, the user has associated at least one item with a value typeDef : Map - defaultInitVal : String } type AcnReferenceToEnumerated = { modName : StringLoc tasName : StringLoc enumerated : Enumerated - acnAligment : AcnAligment option - defaultValue : string + acnAlignment : AcnAlignment option } @@ -557,15 +553,14 @@ type AcnReferenceToIA5String = { modName : StringLoc tasName : StringLoc str : StringType - acnAligment : AcnAligment option - defaultValue : string + acnAlignment : AcnAlignment option } type AcnInteger = { acnProperties : IntegerAcnProperties cons : IntegerTypeConstraint list withcons : IntegerTypeConstraint list - acnAligment : AcnAligment option + acnAlignment : AcnAlignment option acnMaxSizeInBits : BigInteger acnMinSizeInBits : BigInteger acnEncodingClass : IntEncodingClass @@ -580,7 +575,7 @@ type AcnInteger = { type AcnBoolean = { acnProperties : BooleanAcnProperties - acnAligment : AcnAligment option + acnAlignment : AcnAlignment option acnMaxSizeInBits : BigInteger acnMinSizeInBits : BigInteger Location : SrcLoc //Line no, Char pos @@ -589,14 +584,14 @@ type AcnBoolean = { type AcnNullType = { acnProperties : NullTypeAcnProperties - acnAligment : AcnAligment option + acnAlignment : AcnAlignment option acnMaxSizeInBits : BigInteger acnMinSizeInBits : BigInteger Location : SrcLoc //Line no, Char pos defaultValue : string } -type AcnInsertedType = +type AcnInsertedType = | AcnInteger of AcnInteger | AcnNullType of AcnNullType | AcnBoolean of AcnBoolean @@ -610,44 +605,42 @@ with | AcnBoolean _ -> "BOOLEAN" | AcnReferenceToEnumerated o -> sprintf "%s.%s" o.modName.Value o.tasName.Value | AcnReferenceToIA5String o -> sprintf "%s.%s" o.modName.Value o.tasName.Value - member this.acnAligment = + member this.acnAlignment = match this with - | AcnInteger o -> o.acnAligment - | AcnNullType o -> o.acnAligment - | AcnBoolean o -> o.acnAligment - | AcnReferenceToEnumerated o -> o.acnAligment - | AcnReferenceToIA5String o -> o.acnAligment + | AcnInteger o -> o.acnAlignment + | AcnNullType o -> o.acnAlignment + | AcnBoolean o -> o.acnAlignment + | AcnReferenceToEnumerated o -> o.acnAlignment + | AcnReferenceToIA5String o -> o.acnAlignment member this.savePosition = - match this with + match this with | AcnInteger a -> false | AcnBoolean a -> false - | AcnNullType a -> a.acnProperties.savePosition + | AcnNullType a -> a.acnProperties.savePosition | AcnReferenceToEnumerated a -> false | AcnReferenceToIA5String a -> false - - type Asn1Type = { id : ReferenceToType parameterizedTypeInstance : bool Kind : Asn1TypeKind - acnAligment : AcnAligment option + acnAlignment : AcnAlignment option acnParameters : AcnParameter list Location : SrcLoc //Line no, Char pos moduleName : string acnLocation : SrcLoc option /// Indicates that this type - /// is a subclass (or inherits) from referencType + /// is a subclass (or inherits) from referenceType /// (i.e. this type resolves the reference type) inheritInfo : InheritanceInfo option /// it indicates that this type is directly under a type assignment. typeAssignmentInfo : AssignmentInfo option - acnEncSpecPostion : (SrcLoc*SrcLoc) option //start pos, end pos - acnEncSpecAntlrSubTree :ITree option + acnEncSpecPosition : (SrcLoc*SrcLoc) option //start pos, end pos + acnEncSpecAntlrSubTree : ITree option unitsOfMeasure : string option } @@ -707,7 +700,7 @@ and AcnChild = { Comments : string array } -and SeqChildInfo = +and SeqChildInfo = | Asn1Child of Asn1Child | AcnChild of AcnChild @@ -716,7 +709,7 @@ and Asn1Child = { Name : StringLoc _c_name : string _scala_name : string - _ada_name : string + _ada_name : string Type : Asn1Type Optionality : Asn1Optionality option asn1Comments : string list @@ -740,14 +733,13 @@ and Choice = { acnMinSizeInBits : BigInteger acnLoc : SrcLoc option typeDef : Map - defaultInitVal : String } and ChChildInfo = { Name : StringLoc _c_name : string _scala_name : string - _ada_name : string + _ada_name : string present_when_name : string // Does not contain the "_PRESENT". Not to be used directly by backends. Type : Asn1Type acnPresentWhenConditions : AcnPresentWhenConditionChoiceChild list @@ -781,7 +773,6 @@ and ReferenceType = { acnMinSizeInBits : BigInteger encodingOptions : EncodeWithinOctetOrBitStringProperties option refCons : AnyConstraint list - defaultInitVal : String } @@ -814,7 +805,7 @@ type Asn1Module = { Imports : list Exports : Asn1Ast.Exports Comments : string array - postion : SrcLoc*SrcLoc //start pos, end pos + position : SrcLoc*SrcLoc //start pos, end pos } type Asn1File = { @@ -838,21 +829,26 @@ type ReferenceToEnumerated = { enm : Enumerated } -type AcnDependencyKind = +type AcnDependencyKind = | AcnDepIA5StringSizeDeterminant of (SIZE*SIZE*StringAcnProperties) // The asn1Type has a size dependency in IA5String etc - | AcnDepSizeDeterminant of (SIZE*SIZE*SizeableAcnProperties) // The asn1Type has a size dependency a SEQUENCE OF, BIT STRINT, OCTET STRING etc - | AcnDepSizeDeterminant_bit_oct_str_containt of ReferenceType // The asn1Type has a size dependency a BIT STRINT, OCTET STRING containing another type + | AcnDepSizeDeterminant of (SIZE*SIZE*SizeableAcnProperties) // The asn1Type has a size dependency a SEQUENCE OF, BIT STRING, OCTET STRING etc + | AcnDepSizeDeterminant_bit_oct_str_contain of ReferenceType // The asn1Type has a size dependency a BIT STRING, OCTET STRING containing another type | AcnDepRefTypeArgument of AcnParameter // string is the param name - | AcnDepPresenceBool // points to a SEQEUNCE or Choice child + | AcnDepPresenceBool // points to a SEQUENCE or Choice child | AcnDepPresence of (RelativePath*Choice) | AcnDepPresenceStr of (RelativePath*Choice*StringType) - | AcnDepChoiceDeteterminant of (ReferenceToEnumerated*Choice) // points to Enumerated type acting as CHOICE determinant. + | AcnDepChoiceDeterminant of (ReferenceToEnumerated*Choice*bool) // points to Enumerated type acting as CHOICE determinant; is optional + with + member this.isString = + match this with + | AcnDepIA5StringSizeDeterminant _ -> true + | _ -> false type Determinant = | AcnChildDeterminant of AcnChild | AcnParameterDeterminant of AcnParameter - with - member this.id = + with + member this.id = match this with | AcnChildDeterminant c -> c.id | AcnParameterDeterminant p -> p.id @@ -871,7 +867,7 @@ type AcnInsertedFieldDependencies = { type Asn1AcnMergeState = { - args:CommandLineSettings + args:CommandLineSettings allocatedTypeNames : (ProgrammingLanguage*string*string) list //language, program unit, type definition name allocatedFE_TypeDefinition : Map<(ProgrammingLanguage*ReferenceToType), FE_TypeDefinition> temporaryTypesAllocation : Map<(ProgrammingLanguage*ReferenceToType), string> diff --git a/FrontEndAst/Asn1AcnAstUtilFunctions.fs b/FrontEndAst/Asn1AcnAstUtilFunctions.fs index 35313b99c..198e58bfb 100644 --- a/FrontEndAst/Asn1AcnAstUtilFunctions.fs +++ b/FrontEndAst/Asn1AcnAstUtilFunctions.fs @@ -31,7 +31,7 @@ type Asn1Type with | Choice x -> x.uperMinSizeInBits | ObjectIdentifier x -> x.uperMinSizeInBits | ReferenceType x -> x.uperMinSizeInBits - + member this.uperMaxSizeInBits = match this.Kind with @@ -133,7 +133,7 @@ type Asn1Type with - member this.FT_TypeDefintion = + member this.FT_TypeDefinition = match this.Kind with | Integer o -> o.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList | ObjectIdentifier o -> o.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList @@ -149,7 +149,7 @@ type Asn1Type with | SequenceOf o -> o.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList | Sequence o -> o.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_SequenceTypeDefinition d)) |> Map.ofList | Choice o -> o.typeDef |> Map.toList |> List.map (fun (l, d) -> (l, FE_ChoiceTypeDefinition d)) |> Map.ofList - | ReferenceType o-> o.typeDef + | ReferenceType o-> o.typeDef member this.SaveBitStreamPosition = match this.Kind with @@ -194,13 +194,13 @@ type AcnInsertedType with | AcnBoolean x -> x.acnMaxSizeInBits | AcnReferenceToEnumerated x -> x.enumerated.acnMaxSizeInBits | AcnReferenceToIA5String x -> x.str.acnMaxSizeInBits - member this.acnAligment = + member this.acnAlignment = match this with - | AcnInteger x -> x.acnAligment - | AcnNullType x -> x.acnAligment - | AcnBoolean x -> x.acnAligment - | AcnReferenceToEnumerated x -> x.acnAligment - | AcnReferenceToIA5String x -> x.acnAligment + | AcnInteger x -> x.acnAlignment + | AcnNullType x -> x.acnAlignment + | AcnBoolean x -> x.acnAlignment + | AcnReferenceToEnumerated x -> x.acnAlignment + | AcnReferenceToIA5String x -> x.acnAlignment member this.Location = match this with | AcnInteger x -> x.Location @@ -208,7 +208,7 @@ type AcnInsertedType with | AcnBoolean x -> x.Location | AcnReferenceToEnumerated x -> x.tasName.Location | AcnReferenceToIA5String x -> x.tasName.Location - + type BitString with member this.MaxOctets = int (ceil ((double this.maxSize.uper)/8.0)) @@ -222,7 +222,7 @@ type SeqChildInfo with member this.acnMinSizeInBits = match this with - | Asn1Child x -> + | Asn1Child x -> match x.Optionality with | None -> x.Type.acnMinSizeInBits | Some(AlwaysAbsent) -> 0I @@ -231,17 +231,17 @@ type SeqChildInfo with | AcnChild x -> x.Type.acnMinSizeInBits member this.acnMaxSizeInBits = match this with - | Asn1Child x -> + | Asn1Child x -> match x.Optionality with | None -> x.Type.acnMaxSizeInBits | Some(AlwaysAbsent) -> 0I | Some(AlwaysPresent) -> x.Type.acnMaxSizeInBits | Some(Optional o) -> x.Type.acnMaxSizeInBits | AcnChild x -> x.Type.acnMaxSizeInBits - member this.acnAligment = + member this.acnAlignment = match this with - | Asn1Child x -> x.Type.acnAligment - | AcnChild x -> x.Type.acnAligment + | Asn1Child x -> x.Type.acnAlignment + | AcnChild x -> x.Type.acnAlignment member this.Optionality = match this with | Asn1Child x -> x.Optionality @@ -283,7 +283,7 @@ let getIntEncodingClassByUperRange (args:CommandLineSettings) (uperRange:BigInte let int32 = ASN1SCC_Int32 (BigInteger System.Int32.MinValue, BigInteger System.Int32.MaxValue) let int16 = ASN1SCC_Int16 (BigInteger System.Int16.MinValue, BigInteger System.Int16.MaxValue) let int8 = ASN1SCC_Int8 (BigInteger System.SByte.MinValue, BigInteger System.SByte.MaxValue) - + let uint64 = ASN1SCC_UInt64 (0I, BigInteger System.UInt64.MaxValue) let uint32 = ASN1SCC_UInt32 (0I, BigInteger System.UInt32.MaxValue) let uint16 = ASN1SCC_UInt16 (0I, BigInteger System.UInt16.MaxValue) @@ -306,7 +306,7 @@ let getIntEncodingClassByUperRange (args:CommandLineSettings) (uperRange:BigInte if BigInteger System.SByte.MinValue <= a && b <= BigInteger System.SByte.MaxValue then int8 elif BigInteger System.Int16.MinValue <= a && b <= BigInteger System.Int16.MaxValue then int16 elif BigInteger System.Int32.MinValue <= a && b <= BigInteger System.Int32.MaxValue then int32 - else + else int64 | false -> (ASN1SCC_Int (args.SIntMin, args.SIntMax)) @@ -321,7 +321,7 @@ let getIntEncodingClassByUperRange (args:CommandLineSettings) (uperRange:BigInte | NegInf _ -> foo int64 int32 fat_int | PosInf a when a >= 0I -> foo uint64 uint32 fat_uint | PosInf _ -> foo int64 int32 fat_int - | Full _ -> foo int64 int32 fat_int + | Full -> foo int64 int32 fat_int type Integer with @@ -331,7 +331,7 @@ type Integer with type IntegerClass with member this.Min = match this with - | ASN1SCC_Int8 (a,_) -> a + | ASN1SCC_Int8 (a,_) -> a | ASN1SCC_Int16 (a,_) -> a | ASN1SCC_Int32 (a,_) -> a | ASN1SCC_Int64 (a,_) -> a @@ -343,7 +343,7 @@ type IntegerClass with | ASN1SCC_UInt (a,_) -> a member this.Max = match this with - | ASN1SCC_Int8 (_,b) -> b + | ASN1SCC_Int8 (_,b) -> b | ASN1SCC_Int16 (_,b) -> b | ASN1SCC_Int32 (_,b) -> b | ASN1SCC_Int64 (_,b) -> b @@ -353,9 +353,9 @@ type IntegerClass with | ASN1SCC_UInt32 (_,b) -> b | ASN1SCC_UInt64 (_,b) -> b | ASN1SCC_UInt (_,b) -> b - member this.IsPositive = + member this.IsPositive = match this with - | ASN1SCC_Int8 (_) -> false + | ASN1SCC_Int8 (_) -> false | ASN1SCC_Int16 (_) -> false | ASN1SCC_Int32 (_) -> false | ASN1SCC_Int64 (_) -> false @@ -370,10 +370,10 @@ type IntegerClass with let getAcnIntegerClass (args:CommandLineSettings) (i:AcnInteger) = getIntEncodingClassByUperRange args i.uperRange -type ObjectIdentifier with +type ObjectIdentifier with member this.AllCons = this.cons@this.withcons -type TimeType with +type TimeType with member this.AllCons = this.cons@this.withcons @@ -432,7 +432,7 @@ type Choice with type Asn1Child with - member this.getBackendName0 l = + member this.getBackendName0 l = match l with | CommonTypes.C -> this._c_name | CommonTypes.Scala -> this._scala_name @@ -460,7 +460,7 @@ let locateTypeByRefId (r:AstRoot) (ReferenceToType nodes) = let rec locateType (parent:Asn1OrAcnOrPrmType) (nodes:ScopeNode list) = match nodes with | [] -> parent - | (SEQ_CHILD chName)::rest -> + | (SEQ_CHILD chName)::rest -> match parent with | ASN1_TYPE t -> match t.Kind with @@ -471,7 +471,7 @@ let locateTypeByRefId (r:AstRoot) (ReferenceToType nodes) = | None -> raise(UserException(sprintf "Invalid child name '%s'" chName )) | _ -> raise(UserException(sprintf "Invalid path '%s'" origPath.AsString )) | _ -> raise(UserException(sprintf "Invalid path '%s'" origPath.AsString )) - | (CH_CHILD (chName, _))::rest -> + | (CH_CHILD (chName, _))::rest -> match parent with | ASN1_TYPE t -> match t.Kind with @@ -498,23 +498,23 @@ let locateTypeByRefId (r:AstRoot) (ReferenceToType nodes) = | _ -> raise(UserException(sprintf "Invalid path '%s'" origPath.AsString )) match nodes with - | (MD mdName)::(TA tasName)::restPath -> - let md = + | (MD mdName)::(TA tasName)::restPath -> + let md = match r.Files |> List.collect(fun f -> f.Modules) |> Seq.tryFind (fun m -> m.Name.Value = mdName) with | Some md -> md | None -> raise(UserException(sprintf "Invalid module name '%s'" mdName )) - let tas = + let tas = match md.TypeAssignments |> Seq.tryFind(fun tas -> tas.Name.Value = tasName) with | Some tas -> tas | None -> raise(UserException(sprintf "Invalid tas name '%s'" tasName )) locateType (ASN1_TYPE tas.Type) restPath | _ -> raise(UserException(sprintf "Invalid module name " )) - + *) type AstRoot with member r.Modules = r.Files |> List.collect(fun f -> f.Modules) - member r.GetModuleByName(name:StringLoc) = + member r.GetModuleByName(name:StringLoc) = let (n,loc) = name.AsTupple match r.Modules |> Seq.tryFind( fun m -> m.Name = name) with | Some(m) -> m @@ -523,7 +523,7 @@ type AstRoot with type Asn1Module with member this.ExportedTypes = match this.Exports with - | Asn1Ast.All -> + | Asn1Ast.All -> let importedTypes = this.Imports |> List.collect(fun imp -> imp.Types) |> List.map(fun x -> x.Value) (this.TypeAssignments |> List.map(fun x -> x.Name.Value))@importedTypes | Asn1Ast.OnlySome(typesAndVars) -> @@ -537,11 +537,11 @@ type Asn1Module with member m.TryGetTypeAssignmentByName name (r:AstRoot) = match m.TypeAssignments|> Seq.tryFind(fun x -> x.Name = name) with | Some t -> Some t - | None -> - let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) + | None -> + let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with - | firstMod::_ -> + | firstMod::_ -> match r.Modules |> Seq.tryFind( fun m -> m.Name = firstMod) with | Some(m) -> m.TryGetTypeAssignmentByName name r | None -> None @@ -550,22 +550,22 @@ type Asn1Module with member m.GetTypeAssignmentByName name (r:AstRoot) = match m.TypeAssignments|> Seq.tryFind(fun x -> x.Name = name) with | Some(t) -> t - | None -> - let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) + | None -> + let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with | firstMod::tail -> r.GetModuleByName(firstMod).GetTypeAssignmentByName name r - | [] -> + | [] -> let (n,loc) = name.AsTupple raise(SemanticError(loc, sprintf "No Type Assignment with name: %s is defined in Module %s" n m.Name.Value)) member m.GetValueAsigByName(name:StringLoc) (r:AstRoot) = let (n,loc) = name.AsTupple - let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) + let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) match value with | Some(v) -> v | None -> - let othMods = m.Imports - |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) + let othMods = m.Imports + |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with | firstMod::tail -> r.GetModuleByName(firstMod).GetValueAsigByName name r diff --git a/FrontEndAst/Asn1Ast.fs b/FrontEndAst/Asn1Ast.fs index ca736f419..82e62fe4d 100644 --- a/FrontEndAst/Asn1Ast.fs +++ b/FrontEndAst/Asn1Ast.fs @@ -43,7 +43,7 @@ and Asn1ValueKind = | SeqValue of list | ChValue of StringLoc*Asn1Value | NullValue - | ObjOrRelObjIdValue of ObjectIdentifierValueCompoent list + | ObjOrRelObjIdValue of ObjectIdentifierValueComponent list | TimeValue of Asn1DateTimeValueLoc @@ -56,15 +56,15 @@ type NamedConstraintMark = | MarkOptional -type Asn1Constraint = - | SingleValueContraint of string*Asn1Value - | RangeContraint of string*Asn1Value*Asn1Value*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | RangeContraint_val_MAX of string*Asn1Value*bool //min, InclusiveMin(=true) - | RangeContraint_MIN_val of string*Asn1Value*bool //max, InclusiveMax(=true) - | RangeContraint_MIN_MAX - | TypeInclusionConstraint of string*StringLoc*StringLoc - | SizeContraint of string*Asn1Constraint - | AlphabetContraint of string*Asn1Constraint +type Asn1Constraint = + | SingleValueConstraint of string*Asn1Value + | RangeConstraint of string*Asn1Value*Asn1Value*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | RangeConstraint_val_MAX of string*Asn1Value*bool //min, InclusiveMin(=true) + | RangeConstraint_MIN_val of string*Asn1Value*bool //max, InclusiveMax(=true) + | RangeConstraint_MIN_MAX + | TypeInclusionConstraint of string*StringLoc*StringLoc + | SizeConstraint of string*Asn1Constraint + | AlphabetConstraint of string*Asn1Constraint | UnionConstraint of string*Asn1Constraint*Asn1Constraint*bool //left,righ, virtual constraint | IntersectionConstraint of string*Asn1Constraint*Asn1Constraint | AllExceptConstraint of string*Asn1Constraint @@ -76,7 +76,7 @@ type Asn1Constraint = and NamedConstraint = { Name:StringLoc; - Contraint:Asn1Constraint option + Constraint:Asn1Constraint option Mark:NamedConstraintMark } @@ -112,13 +112,13 @@ type Optional = { defaultValue : Asn1Value option } -type Asn1Optionality = +type Asn1Optionality = | AlwaysAbsent | AlwaysPresent | Optional of Optional - + type Asn1Type = { @@ -138,11 +138,11 @@ and Asn1TypeKind = | Real | IA5String | NumericString - | OctetString + | OctetString | NullType | TimeType of TimeTypeClass | BitString of list - | Boolean + | Boolean | ObjectIdentifier | RelativeObjectIdentifier | Enumerated of list @@ -163,7 +163,7 @@ and ChildInfo = { Name : StringLoc; c_name : string scala_name : string - ada_name : string + ada_name : string present_when_name : string // used only by choices. Does not contain the "_PRESENT". Not to be used directly by backends. Type : Asn1Type Optionality : Asn1Optionality option @@ -207,7 +207,7 @@ type Asn1Module = { Imports : list Exports : Exports Comments : string array - postion : SrcLoc*SrcLoc //start pos, end pos + position : SrcLoc*SrcLoc //start pos, end pos } type Asn1File = { @@ -226,7 +226,7 @@ type AstRoot = { type AstRoot with member r.Modules = r.Files |> List.collect(fun f -> f.Modules) - member r.GetModuleByName(name:StringLoc) = + member r.GetModuleByName(name:StringLoc) = let (n,loc) = name.AsTupple match r.Modules |> Seq.tryFind( fun m -> m.Name = name) with | Some(m) -> m @@ -235,7 +235,7 @@ type AstRoot with type Asn1Module with member this.ExportedTypes = match this.Exports with - | All -> + | All -> let importedTypes = this.Imports |> List.collect(fun imp -> imp.Types) |> List.map(fun x -> x.Value) (this.TypeAssignments |> List.map(fun x -> x.Name.Value))@importedTypes | OnlySome(typesAndVars) -> @@ -248,11 +248,11 @@ type Asn1Module with member m.TryGetTypeAssignmentByName name (r:AstRoot) = match m.TypeAssignments|> Seq.tryFind(fun x -> x.Name = name) with | Some t -> Some t - | None -> - let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) + | None -> + let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with - | firstMod::_ -> + | firstMod::_ -> match r.Modules |> Seq.tryFind( fun m -> m.Name = firstMod) with | Some(m) -> m.TryGetTypeAssignmentByName name r | None -> None @@ -261,22 +261,22 @@ type Asn1Module with member m.GetTypeAssignmentByName name (r:AstRoot) = match m.TypeAssignments|> Seq.tryFind(fun x -> x.Name = name) with | Some(t) -> t - | None -> - let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) + | None -> + let othMods = m.Imports |> Seq.filter(fun imp -> imp.Types |> Seq.exists((=) name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with | firstMod::tail -> r.GetModuleByName(firstMod).GetTypeAssignmentByName name r - | [] -> + | [] -> let (n,loc) = name.AsTupple raise(SemanticError(loc, sprintf "No Type Assignment with name: %s is defined in Module %s" n m.Name.Value)) member m.GetValueAsigByName(name:StringLoc) (r:AstRoot) = let (n,loc) = name.AsTupple - let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) + let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) match value with | Some(v) -> v | None -> - let othMods = m.Imports - |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) + let othMods = m.Imports + |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with | firstMod::tail -> r.GetModuleByName(firstMod).GetValueAsigByName name r @@ -339,14 +339,14 @@ let rec GetValueAsInt (v:Asn1Value) r= | _ -> raise(SemanticError (v.Location, sprintf "Expecting Integer value")) let GetActualTypeAllConsIncluded t (r:AstRoot) = - let rec GetActualTypeAux (t:Asn1Type) (addionalConstraints:list) = + let rec GetActualTypeAux (t:Asn1Type) (additionalConstraints:list) = match t.Kind with | ReferenceType ref -> let newmod = r.GetModuleByName(ref.modName) let tas = newmod.GetTypeAssignmentByName ref.tasName r - GetActualTypeAux tas.Type (t.Constraints@addionalConstraints) - | _ -> {t with Constraints = (t.Constraints@addionalConstraints)} - GetActualTypeAux t [] + GetActualTypeAux tas.Type (t.Constraints@additionalConstraints) + | _ -> {t with Constraints = (t.Constraints@additionalConstraints)} + GetActualTypeAux t [] let GetActualTypeByNameAllConsIncluded modName tasName (r:AstRoot) = let mdl = r.GetModuleByName(modName) @@ -373,19 +373,19 @@ let rec getASN1Name (r:AstRoot) (t:Asn1Type) = | TimeType _ -> "TIME" | ReferenceType _ -> getASN1Name r (GetActualType t r) -let rec GetMySelfAndChildren (t:Asn1Type) = +let rec GetMySelfAndChildren (t:Asn1Type) = seq { yield t match t.Kind with | SequenceOf(conType) -> yield! GetMySelfAndChildren conType - | Sequence(children) | Choice(children)-> - for ch in children do + | Sequence(children) | Choice(children)-> + for ch in children do yield! GetMySelfAndChildren ch.Type - |_ -> () + |_ -> () } (* type ChildInfo with - member c.CName (lang:ProgrammingLanguage) = + member c.CName (lang:ProgrammingLanguage) = match lang with | Ada -> c.ada_name | C -> c.c_name @@ -393,28 +393,23 @@ type ChildInfo with *) type NamedItem with - member c.CEnumName (r:AstRoot) (lang:ProgrammingLanguage) = + member c.CEnumName (r:AstRoot) (lang:ProgrammingLanguage) = match lang with |Ada -> ToC2 (r.args.TypePrefix + c.ada_name) |C -> ToC2 (r.args.TypePrefix + c.c_name) |Scala -> ToC2 (r.args.TypePrefix + c.scala_name) -// member c.EnumName (lang:ProgrammingLanguage) = -// match lang with -// |Ada -> c.ada_name -// |C -> c.c_name -// |Scala -> c.scala_name type Asn1Constraint with member this.Asn1Con = match this with - | SingleValueContraint (s,_) -> s - | RangeContraint (s,_,_,_,_) -> s - | RangeContraint_val_MAX (s,_,_) -> s - | RangeContraint_MIN_val (s,_,_) -> s - | RangeContraint_MIN_MAX -> "(MIN .. MAX)" + | SingleValueConstraint (s,_) -> s + | RangeConstraint (s,_,_,_,_) -> s + | RangeConstraint_val_MAX (s,_,_) -> s + | RangeConstraint_MIN_val (s,_,_) -> s + | RangeConstraint_MIN_MAX -> "(MIN .. MAX)" | TypeInclusionConstraint (s,_,_) -> s - | SizeContraint (s,_) -> s - | AlphabetContraint (s,_) -> s + | SizeConstraint (s,_) -> s + | AlphabetConstraint (s,_) -> s | UnionConstraint (s,_,_,_) -> s | IntersectionConstraint (s,_,_) -> s | AllExceptConstraint (s,_) -> s @@ -425,47 +420,47 @@ type Asn1Constraint with | WithComponentsConstraint (s,_) -> s -let foldConstraint - singleValueFunc rangeContraintFunc rangeContraint_val_MAX rangeContraint_MIN_val rangeContraint_MIN_MAX - typeInclusionConstraint sizeContraint alphabetContraint +let foldConstraint + singleValueFunc rangeConstraintFunc rangeConstraint_val_MAX rangeConstraint_MIN_val rangeConstraint_MIN_MAX + typeInclusionConstraint sizeConstraint alphabetConstraint withComponentConstraint namedItemConstraint withComponentsConstraint - unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 + unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 c = let rec loopRecursiveConstraint c = match c with - | SingleValueContraint (s,v) -> singleValueFunc s v - | RangeContraint (s,a,b,inclusiveMin,inclusiveMax) -> - rangeContraintFunc s a b inclusiveMin inclusiveMax - | RangeContraint_val_MAX (s,a, inclusive) -> rangeContraint_val_MAX s a inclusive - | RangeContraint_MIN_val (s,b, inclusive) -> rangeContraint_MIN_val s b inclusive - | RangeContraint_MIN_MAX -> rangeContraint_MIN_MAX () + | SingleValueConstraint (s,v) -> singleValueFunc s v + | RangeConstraint (s,a,b,inclusiveMin,inclusiveMax) -> + rangeConstraintFunc s a b inclusiveMin inclusiveMax + | RangeConstraint_val_MAX (s,a, inclusive) -> rangeConstraint_val_MAX s a inclusive + | RangeConstraint_MIN_val (s,b, inclusive) -> rangeConstraint_MIN_val s b inclusive + | RangeConstraint_MIN_MAX -> rangeConstraint_MIN_MAX () | TypeInclusionConstraint (s,md,ts) -> typeInclusionConstraint s md ts - | SizeContraint (s,c) -> sizeContraint s (loopRecursiveConstraint c) - | AlphabetContraint (s,c) -> alphabetContraint s (loopRecursiveConstraint c) + | SizeConstraint (s,c) -> sizeConstraint s (loopRecursiveConstraint c) + | AlphabetConstraint (s,c) -> alphabetConstraint s (loopRecursiveConstraint c) | WithComponentConstraint (s,c,l) -> withComponentConstraint s (loopRecursiveConstraint c) l - | WithComponentsConstraint (s,nitems) -> - let newItems = nitems |> List.map(fun ni -> namedItemConstraint s ni (ni.Contraint |> Option.map loopRecursiveConstraint)) + | WithComponentsConstraint (s,nitems) -> + let newItems = nitems |> List.map(fun ni -> namedItemConstraint s ni (ni.Constraint |> Option.map loopRecursiveConstraint)) withComponentsConstraint s newItems - | UnionConstraint(s,c1,c2,b) -> - let nc1 = loopRecursiveConstraint c1 - let nc2 = loopRecursiveConstraint c2 + | UnionConstraint(s,c1,c2,b) -> + let nc1 = loopRecursiveConstraint c1 + let nc2 = loopRecursiveConstraint c2 unionFunc s nc1 nc2 b - | IntersectionConstraint(s,c1,c2) -> - let nc1 = loopRecursiveConstraint c1 - let nc2 = loopRecursiveConstraint c2 - intersectionFunc s nc1 nc2 - | AllExceptConstraint(s,c1) -> - let nc1 = loopRecursiveConstraint c1 - allExceptFunc s nc1 - | ExceptConstraint(s,c1,c2) -> - let nc1 = loopRecursiveConstraint c1 - let nc2 = loopRecursiveConstraint c2 - exceptFunc s nc1 nc2 - | RootConstraint(s,c1) -> - let nc1 = loopRecursiveConstraint c1 - rootFunc s nc1 - | RootConstraint2(s,c1,c2) -> - let nc1 = loopRecursiveConstraint c1 - let nc2 = loopRecursiveConstraint c2 + | IntersectionConstraint(s,c1,c2) -> + let nc1 = loopRecursiveConstraint c1 + let nc2 = loopRecursiveConstraint c2 + intersectionFunc s nc1 nc2 + | AllExceptConstraint(s,c1) -> + let nc1 = loopRecursiveConstraint c1 + allExceptFunc s nc1 + | ExceptConstraint(s,c1,c2) -> + let nc1 = loopRecursiveConstraint c1 + let nc2 = loopRecursiveConstraint c2 + exceptFunc s nc1 nc2 + | RootConstraint(s,c1) -> + let nc1 = loopRecursiveConstraint c1 + rootFunc s nc1 + | RootConstraint2(s,c1,c2) -> + let nc1 = loopRecursiveConstraint c1 + let nc2 = loopRecursiveConstraint c2 rootFunc2 s nc1 nc2 - loopRecursiveConstraint c + loopRecursiveConstraint c diff --git a/FrontEndAst/Asn1Fold.fs b/FrontEndAst/Asn1Fold.fs index 618327e6c..348372b40 100644 --- a/FrontEndAst/Asn1Fold.fs +++ b/FrontEndAst/Asn1Fold.fs @@ -6,19 +6,19 @@ open Asn1AcnAstUtilFunctions let rec foldMap func state lst = match lst with | [] -> [],state - | h::tail -> + | h::tail -> let procItem, newState = func state h let restList, finalState = tail |> foldMap func newState procItem::restList, finalState *) -//let foldMap = RemoveParamterizedTypes.foldMap +//let foldMap = RemoveParameterizedTypes.foldMap let foldMap func state lst = let rec loop acc func state lst = match lst with | [] -> acc |> List.rev , state - | h::tail -> + | h::tail -> let procItem, newState = func state h //let restList, finalState = tail |> loop func newState //procItem::restList, finalState @@ -26,30 +26,30 @@ let foldMap func state lst = loop [] func state lst -let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - (c:GenericConstraint<'v>) +let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + (c:GenericConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:GenericConstraint<'v>) (s0:'UserState) = match c with - | UnionConstraint(s, c1,c2,b) -> + | UnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | IntersectionConstraint(s, c1,c2) -> + | IntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | AllExceptConstraint(s, c1) -> + | AllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | ExceptConstraint(s, c1,c2) -> + | ExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | RootConstraint(s, c1) -> + | RootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | RootConstraint2(s, c1,c2) -> + | RootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 @@ -57,200 +57,200 @@ let foldGenericConstraint unionFunc intersectionFunc allExceptFunc exceptFunc ro loopRecursiveConstraint c s -let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc rangeFunc range_val_max_func range_min_val_func - (c:RangeTypeConstraint<'v,'vr>) + (c:RangeTypeConstraint<'v,'vr>) (s:'UserState) = let rec loopRecursiveConstraint (c:RangeTypeConstraint<'v,'vr>) (s0:'UserState) = match c with - | RangeUnionConstraint(s, c1,c2,b) -> + | RangeUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | RangeIntersectionConstraint(s, c1,c2) -> + | RangeIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | RangeAllExceptConstraint(s, c1) -> + | RangeAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | RangeExceptConstraint(s, c1,c2) -> + | RangeExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | RangeRootConstraint(s, c1) -> + | RangeRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | RangeRootConstraint2(s, c1,c2) -> + | RangeRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | RangeSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | RangeContraint(a, (v1), (v2), b1,b2) -> rangeFunc a v1 v2 b1 b2 s - | RangeContraint_val_MAX (a, (v), b) -> range_val_max_func a v b s - | RangeContraint_MIN_val (a, (v), b) -> range_min_val_func a v b s + | RangeConstraint(a, (v1), (v2), b1,b2) -> rangeFunc a v1 v2 b1 b2 s + | RangeConstraint_val_MAX (a, (v), b) -> range_val_max_func a v b s + | RangeConstraint_MIN_val (a, (v), b) -> range_min_val_func a v b s loopRecursiveConstraint c s -let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc +let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func - (c:SizableTypeConstraint<'v>) + (c:SizableTypeConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SizableTypeConstraint<'v>) (s0:'UserState) = match c with - | SizeUnionConstraint(asn1, c1,c2,b) -> + | SizeUnionConstraint(asn1, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc asn1 nc1 nc2 b s2 - | SizeIntersectionConstraint(asn1, c1,c2) -> + | SizeIntersectionConstraint(asn1, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc asn1 nc1 nc2 s2 - | SizeAllExceptConstraint(asn1, c1) -> + | SizeAllExceptConstraint(asn1, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc asn1 nc1 s1 - | SizeExceptConstraint(asn1, c1,c2) -> + | SizeExceptConstraint(asn1, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc asn1 nc1 nc2 s2 - | SizeRootConstraint(asn1, c1) -> + | SizeRootConstraint(asn1, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc asn1 nc1 s1 - | SizeRootConstraint2(asn1, c1,c2) -> + | SizeRootConstraint2(asn1, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 asn1 nc1 nc2 s2 | SizeSingleValueConstraint (asn1, v) -> singleValueFunc asn1 v s0 - | SizeContraint (asn1, intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s0 + | SizeConstraint (asn1, intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s0 loopRecursiveConstraint c s -let foldSizableTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldSizableTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc foldRangeTypeConstraint - (c:SizableTypeConstraint<'v>) + (c:SizableTypeConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SizableTypeConstraint<'v>) (s0:'UserState) = match c with - | SizeUnionConstraint(s, c1,c2,b) -> + | SizeUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | SizeIntersectionConstraint(s, c1,c2) -> + | SizeIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | SizeAllExceptConstraint(s, c1) -> + | SizeAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | SizeExceptConstraint(s, c1,c2) -> + | SizeExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | SizeRootConstraint(s, c1) -> + | SizeRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | SizeRootConstraint2(s, c1,c2) -> + | SizeRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | SizeSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | SizeContraint (s,intCon) -> foldRangeTypeConstraint s intCon s0 + | SizeConstraint (s,intCon) -> foldRangeTypeConstraint s intCon s0 loopRecursiveConstraint c s -let foldStringTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldStringTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func - aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func - (c:IA5StringConstraint) + aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func + (c:IA5StringConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:IA5StringConstraint) (s0:'UserState) = match c with - | StrUnionConstraint(s, c1,c2,b) -> + | StrUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | StrIntersectionConstraint(s, c1,c2) -> + | StrIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | StrAllExceptConstraint(s, c1) -> + | StrAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | StrExceptConstraint(s, c1,c2) -> + | StrExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | StrRootConstraint(s, c1) -> + | StrRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | StrRootConstraint2(s, c1,c2) -> + | StrRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | StrSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | StrSizeContraint (s,intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s0 - | AlphabetContraint (s,alphaCon) -> foldRangeTypeConstraint aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func alphaCon s0 + | StrSizeConstraint (s,intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s0 + | AlphabetConstraint (s,alphaCon) -> foldRangeTypeConstraint aunionFunc aintersectionFunc aallExceptFunc aexceptFunc arootFunc arootFunc2 asingleValueFunc arangeFunc arange_val_max_func arange_min_val_func alphaCon s0 loopRecursiveConstraint c s -let foldStringTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldStringTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc foldRangeSizeConstraint foldRangeAlphaConstraint - (c:IA5StringConstraint) + (c:IA5StringConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:IA5StringConstraint) (s0:'UserState) = match c with - | StrUnionConstraint(s, c1,c2,b) -> + | StrUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | StrIntersectionConstraint(s, c1,c2) -> + | StrIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | StrAllExceptConstraint(s, c1) -> + | StrAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | StrExceptConstraint(s, c1,c2) -> + | StrExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | StrRootConstraint(s, c1) -> + | StrRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | StrRootConstraint2(s, c1,c2) -> + | StrRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | StrSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | StrSizeContraint (s,intCon) -> foldRangeSizeConstraint s intCon s0 - | AlphabetContraint (s, alphaCon) -> foldRangeAlphaConstraint s alphaCon s0 + | StrSizeConstraint (s,intCon) -> foldRangeSizeConstraint s intCon s0 + | AlphabetConstraint (s, alphaCon) -> foldRangeAlphaConstraint s alphaCon s0 loopRecursiveConstraint c s let foldSeqOrChConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc withComponentsFunc - (c:SeqOrChoiceConstraint<'v>) + (c:SeqOrChoiceConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SeqOrChoiceConstraint<'v>) (s0:'UserState) = match c with - | SeqOrChUnionConstraint(s,c1,c2,b) -> + | SeqOrChUnionConstraint(s,c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | SeqOrChIntersectionConstraint(s, c1,c2) -> + | SeqOrChIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | SeqOrChAllExceptConstraint(s, c1) -> + | SeqOrChAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | SeqOrChExceptConstraint(s, c1,c2) -> + | SeqOrChExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | SeqOrChRootConstraint(s, c1) -> + | SeqOrChRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | SeqOrChRootConstraint2(s, c1,c2) -> + | SeqOrChRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 @@ -260,82 +260,82 @@ let foldSeqOrChConstraint unionFunc intersectionFunc allExceptFunc exceptFunc ro let foldSeqConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc withComponentsFunc - (c:SeqConstraint) + (c:SeqConstraint) (s:'UserState) = foldSeqOrChConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc withComponentsFunc c s let foldChoiceConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc withComponentsFunc - (c:ChoiceConstraint) + (c:ChoiceConstraint) (s:'UserState) = foldSeqOrChConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc withComponentsFunc c s -let foldSequenceOfTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc +let foldSequenceOfTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func withComponentFunc - (c:SequenceOfConstraint) + (c:SequenceOfConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:SequenceOfConstraint) (s0:'UserState) = match c with - | SeqOfSizeUnionConstraint(s, c1,c2,b) -> + | SeqOfSizeUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | SeqOfSizeIntersectionConstraint(s, c1,c2) -> + | SeqOfSizeIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | SeqOfSizeAllExceptConstraint(s, c1) -> + | SeqOfSizeAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | SeqOfSizeExceptConstraint(s, c1,c2) -> + | SeqOfSizeExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | SeqOfSizeRootConstraint(s, c1) -> + | SeqOfSizeRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | SeqOfSizeRootConstraint2(s, c1,c2) -> + | SeqOfSizeRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | SeqOfSizeSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | SeqOfSizeContraint (_, intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s + | SeqOfSizeConstraint (_, intCon) -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s | SeqOfSeqWithComponentConstraint (s, c,l) -> withComponentFunc s c l s0 loopRecursiveConstraint c s -let foldSequenceOfTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldSequenceOfTypeConstraint2 unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc foldRangeTypeConstraint withComponentFunc - (c:SequenceOfConstraint) + (c:SequenceOfConstraint) (s:'UserState) = let rec loopRecursiveConstraint (c:SequenceOfConstraint) (s0:'UserState) = match c with - | SeqOfSizeUnionConstraint(s, c1,c2,b) -> + | SeqOfSizeUnionConstraint(s, c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc s nc1 nc2 b s2 - | SeqOfSizeIntersectionConstraint(s, c1,c2) -> + | SeqOfSizeIntersectionConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc s nc1 nc2 s2 - | SeqOfSizeAllExceptConstraint(s, c1) -> + | SeqOfSizeAllExceptConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc s nc1 s1 - | SeqOfSizeExceptConstraint(s, c1,c2) -> + | SeqOfSizeExceptConstraint(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc s nc1 nc2 s2 - | SeqOfSizeRootConstraint(s, c1) -> + | SeqOfSizeRootConstraint(s, c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc s nc1 s1 - | SeqOfSizeRootConstraint2(s, c1,c2) -> + | SeqOfSizeRootConstraint2(s, c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 s nc1 nc2 s2 | SeqOfSizeSingleValueConstraint (s, v) -> singleValueFunc s v s0 - | SeqOfSizeContraint (s,intCon) -> foldRangeTypeConstraint s intCon s0 + | SeqOfSizeConstraint (s,intCon) -> foldRangeTypeConstraint s intCon s0 | SeqOfSeqWithComponentConstraint (s, c,l) -> withComponentFunc s c l s0 loopRecursiveConstraint c s @@ -343,25 +343,25 @@ let foldSequenceOfTypeConstraint2 unionFunc intersectionFunc allExceptFunc excep let foldType intFunc realFunc - ia5StringFunc - numStringFunc - octStringFunc + ia5StringFunc + numStringFunc + octStringFunc timeFunc nullTypeFunc bitStringFunc boolFunc - enumFunc + enumFunc objectIdFunc seqOfFunc seqFunc seqAsn1ChildFunc seqAcnChildFunc - choiceFunc + choiceFunc chChildFunc - refType + refType typeFunc - (t:Asn1Type) - (us:'UserState) + (t:Asn1Type) + (us:'UserState) = let rec loopType (t:Asn1Type) (us:'UserState) = let newKind, newState = @@ -377,28 +377,28 @@ let foldType | Boolean ti -> boolFunc ti us | Enumerated ti -> enumFunc ti us | ObjectIdentifier ti -> objectIdFunc ti us - | SequenceOf ti -> + | SequenceOf ti -> let newChild, newState = loopType ti.child us seqOfFunc ti newChild newState - | Sequence ti -> - let newChildren, newState = - ti.children |> - foldMap (fun curState ch -> + | Sequence ti -> + let newChildren, newState = + ti.children |> + foldMap (fun curState ch -> match ch with - | Asn1Child asn1Chlld -> - let newChildType, newState = loopType asn1Chlld.Type curState - seqAsn1ChildFunc asn1Chlld newChildType newState - | AcnChild acnChild -> + | Asn1Child asn1Child -> + let newChildType, newState = loopType asn1Child.Type curState + seqAsn1ChildFunc asn1Child newChildType newState + | AcnChild acnChild -> seqAcnChildFunc acnChild curState) us seqFunc ti newChildren newState - | Choice ti -> - let newChildren, newState = - ti.children |> - foldMap (fun curState ch -> + | Choice ti -> + let newChildren, newState = + ti.children |> + foldMap (fun curState ch -> let newChildType, newState = loopType ch.Type curState chChildFunc ch newChildType newState) us choiceFunc ti newChildren newState - | ReferenceType ti -> + | ReferenceType ti -> let newBaseType, newState = loopType ti.resolvedType us refType ti newBaseType newState typeFunc t newKind newState @@ -411,11 +411,11 @@ type ParentInfo<'T> = { /// the name of the component or alternative this type exists name : string option /// Information obtained by the preSeqOfFunc, preSeqFunc and preChoiceFunc - /// which are called before visting the children + /// which are called before visiting the children parentData : 'T } -let dummy a = +let dummy a = let parId = "PUS.SpacePacket" let c1 = "PUS.SpacePacket.header.packet-length" let c2 = "PUS.SpacePacket.payload" @@ -429,42 +429,42 @@ let getSeqChildrenWithPriority (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (t let id = t.id.AsString let getChildNameFromId (childId:string) = childId.Substring(id.Length + 1).Split('.').[0] - let childrenWithPriority = - deps.acnDependencies |> - List.choose(fun d -> + let childrenWithPriority = + deps.acnDependencies |> + List.choose(fun d -> match d.dependencyKind with - | AcnDepSizeDeterminant_bit_oct_str_containt _ when d.asn1Type.AsString.StartsWith (id) && d.determinant.id.AsString.StartsWith (id) && (getChildNameFromId d.asn1Type.AsString) <> (getChildNameFromId d.determinant.id.AsString) -> Some (getChildNameFromId d.asn1Type.AsString ) + | AcnDepSizeDeterminant_bit_oct_str_contain _ when d.asn1Type.AsString.StartsWith (id) && d.determinant.id.AsString.StartsWith (id) && (getChildNameFromId d.asn1Type.AsString) <> (getChildNameFromId d.determinant.id.AsString) -> Some (getChildNameFromId d.asn1Type.AsString ) | _ -> None ) childrenWithPriority let foldType2 - intFunc - realFunc - ia5StringFunc - numStringFunc - octStringFunc - timeFunc - nullTypeFunc - bitStringFunc - boolFunc - enumFunc - objectIdFunc - seqOfFunc - seqFunc - seqAsn1ChildFunc - seqAcnChildFunc - choiceFunc - chChildFunc - refType - typeFunc - preSeqOfFunc - preSeqFunc - preChoiceFunc + (intFunc: ParentInfo<'T> option -> Asn1Type -> Integer -> 'UserState -> 'a) + (realFunc: ParentInfo<'T> option -> Asn1Type -> Real -> 'UserState -> 'a) + (ia5StringFunc: ParentInfo<'T> option -> Asn1Type -> StringType -> 'UserState -> 'a) + (numStringFunc: ParentInfo<'T> option -> Asn1Type -> StringType -> 'UserState -> 'a) + (octStringFunc: ParentInfo<'T> option -> Asn1Type -> OctetString -> 'UserState -> 'a) + (timeFunc: ParentInfo<'T> option -> Asn1Type -> TimeType -> 'UserState -> 'a) + (nullTypeFunc: ParentInfo<'T> option -> Asn1Type -> NullType -> 'UserState -> 'a) + (bitStringFunc: ParentInfo<'T> option -> Asn1Type -> BitString -> 'UserState -> 'a) + (boolFunc: ParentInfo<'T> option -> Asn1Type -> Boolean -> 'UserState -> 'a) + (enumFunc: ParentInfo<'T> option -> Asn1Type -> Enumerated -> 'UserState -> 'a) + (objectIdFunc: ParentInfo<'T> option -> Asn1Type -> ObjectIdentifier -> 'UserState -> 'a) + (seqOfFunc: ParentInfo<'T> option -> Asn1Type -> SequenceOf -> 'b -> 'a) + (seqFunc: ParentInfo<'T> option -> Asn1Type -> Sequence -> 'c list * 'UserState -> 'a) + (seqAsn1ChildFunc: Asn1Child -> 'b -> 'c * 'UserState) + (seqAcnChildFunc: AcnChild -> 'UserState -> 'c * 'UserState) + (choiceFunc: ParentInfo<'T> option -> Asn1Type -> Choice -> 'd list * 'UserState -> 'a) + (chChildFunc: ChChildInfo -> 'b -> 'd * 'UserState) + (refType: ParentInfo<'T> option -> Asn1Type -> ReferenceType -> 'b -> 'a) + (typeFunc: ParentInfo<'T> option -> Asn1Type -> 'a -> 'b) + (preSeqOfFunc: ParentInfo<'T> option -> Asn1Type -> SequenceOf -> 'UserState -> 'T * 'UserState) + (preSeqFunc: ParentInfo<'T> option -> Asn1Type -> Sequence -> 'UserState -> 'T * 'UserState) + (preChoiceFunc: ParentInfo<'T> option -> Asn1Type -> Choice -> 'UserState -> 'T * 'UserState) (deps:Asn1AcnAst.AcnInsertedFieldDependencies) (parentInfo : ParentInfo<'T> option) - (t:Asn1Type) - (us:'UserState) + (t:Asn1Type) + (us:'UserState) : 'b = let rec loopType (pi : ParentInfo<'T> option) (t:Asn1Type) (us:'UserState) = let newKind= @@ -480,39 +480,38 @@ let foldType2 | Boolean ti -> boolFunc pi t ti us | Enumerated ti -> enumFunc pi t ti us | ObjectIdentifier ti -> objectIdFunc pi t ti us - | SequenceOf ti -> + | SequenceOf ti -> let (parentData:'T, ns:'UserState) = preSeqOfFunc pi t ti us - seqOfFunc pi t ti (loopType (Some {ParentInfo.parent = t ; name=None; parentData=parentData}) ti.child ns) - | Sequence ti -> + let newChild = loopType (Some {ParentInfo.parent = t ; name=None; parentData=parentData}) ti.child ns + seqOfFunc pi t ti newChild + | Sequence ti -> let (parentData:'T, ns:'UserState) = preSeqFunc pi t ti us let priorities = getSeqChildrenWithPriority deps t |> Set.ofList //first process asn1 children and then asn.1 children. let initialOrder = ti.children |> List.mapi(fun i c -> match c with Asn1Child x -> (x.Name.Value, i) | AcnChild x -> (x.Name.Value, i) ) |> Map.ofList - let newChildren, ns = - ti.children |> - //List.mapi(fun i c -> match c with Asn1Child _ -> ((i+1), c) | AcnChild _ -> ((i+1)*1000000, c)) |> + let newChildren, ns = + ti.children |> List.mapi(fun i c -> match priorities.Contains c.Name.Value with true -> ((i+1), c) | false -> ((i+1)*1000000, c)) |> - List.sortBy fst |> + List.sortBy fst |> List.map snd |> - foldMap (fun curState ch -> + foldMap (fun curState ch -> match ch with - | Asn1Child asn1Chlld -> - let newChild, ns = seqAsn1ChildFunc asn1Chlld (loopType (Some {ParentInfo.parent = t ; name=Some asn1Chlld.Name.Value; parentData=parentData}) asn1Chlld.Type curState) - (asn1Chlld.Name.Value, newChild), ns - | AcnChild acnChild -> + | Asn1Child asn1Child -> + let newChild, ns = seqAsn1ChildFunc asn1Child (loopType (Some {ParentInfo.parent = t ; name=Some asn1Child.Name.Value; parentData=parentData}) asn1Child.Type curState) + (asn1Child.Name.Value, newChild), ns + | AcnChild acnChild -> let newChild, ns = seqAcnChildFunc acnChild curState (acnChild.Name.Value, newChild), ns) ns - //restore the correct order let newChildren = newChildren |> List.sortBy(fun (nm, _) -> initialOrder[nm]) |> List.map snd - seqFunc pi t ti (newChildren, ns) - | Choice ti -> + seqFunc pi t ti (newChildren, ns) + | Choice ti -> let (parentData:'T, ns:'UserState) = preChoiceFunc pi t ti us let newChildren = ti.children |> foldMap (fun curState ch -> chChildFunc ch (loopType (Some {ParentInfo.parent = t ; name=Some ch.Name.Value; parentData=parentData}) ch.Type curState)) ns - choiceFunc pi t ti newChildren - | ReferenceType ti -> + choiceFunc pi t ti newChildren + | ReferenceType ti -> refType pi t ti (loopType pi ti.resolvedType us) typeFunc pi t newKind loopType parentInfo t us @@ -536,15 +535,15 @@ let isValidValueGeneric allCons eqFunc value = let evalRangeCon (c:RangeTypeConstraint<'v1,'v1>) value = - let check_v1 v1 minIsIn = + let check_v1 v1 minIsIn = match minIsIn with | true -> v1 <= value | false -> v1 < value - let check_v2 v2 maxIsIn = + let check_v2 v2 maxIsIn = match maxIsIn with | true -> value <= v2 | false -> value < v2 - foldRangeTypeConstraint + foldRangeTypeConstraint (fun _ e1 e2 b s -> e1 || e2, s) //union (fun _ e1 e2 s -> e1 && e2, s) //Intersection (fun _ e s -> not e, s) //AllExcept @@ -552,10 +551,10 @@ let evalRangeCon (c:RangeTypeConstraint<'v1,'v1>) value = (fun _ e s -> e, s) //RootConstraint (fun _ e1 e2 s -> e1 || e2, s) //RootConstraint2 (fun _ v s -> v = value ,s) // SingleValueConstraint - (fun _ v1 v2 minIsIn maxIsIn (s:int) -> //RangeContraint + (fun _ v1 v2 minIsIn maxIsIn (s:int) -> //RangeConstraint (check_v1 v1 minIsIn) && (check_v2 v2 maxIsIn), s) - (fun _ v1 minIsIn s -> (check_v1 v1 minIsIn), s) //Contraint_val_MAX - (fun _ v2 maxIsIn s -> (check_v2 v2 maxIsIn), s) //Contraint_MIN_val + (fun _ v1 minIsIn s -> (check_v1 v1 minIsIn), s) //Constraint_val_MAX + (fun _ v2 maxIsIn s -> (check_v2 v2 maxIsIn), s) //Constraint_MIN_val c 0 |> fst diff --git a/FrontEndAst/Asn1Schema.xsd b/FrontEndAst/Asn1Schema.xsd index ddeafdefc..fd14ef9a5 100644 --- a/FrontEndAst/Asn1Schema.xsd +++ b/FrontEndAst/Asn1Schema.xsd @@ -21,9 +21,9 @@ - - + + @@ -31,14 +31,14 @@ - + - + @@ -51,7 +51,7 @@ - + @@ -99,7 +99,7 @@ - + @@ -115,8 +115,8 @@ - - + + @@ -151,7 +151,7 @@ - + @@ -177,7 +177,7 @@ - + @@ -201,7 +201,7 @@ - + @@ -216,7 +216,7 @@ - + @@ -243,7 +243,7 @@ - + @@ -253,8 +253,8 @@ - - + + @@ -280,7 +280,7 @@ - + @@ -288,7 +288,7 @@ - + @@ -312,7 +312,7 @@ - + @@ -446,9 +446,9 @@ - + + - @@ -508,7 +508,7 @@ - + @@ -519,7 +519,7 @@ - + @@ -561,7 +561,7 @@ - + @@ -572,7 +572,7 @@ - + @@ -601,7 +601,7 @@ - + @@ -611,8 +611,8 @@ - - + + @@ -642,7 +642,7 @@ - + @@ -665,15 +665,15 @@ - + - + - + @@ -688,11 +688,11 @@ - + - + @@ -714,14 +714,14 @@ - + - + @@ -734,12 +734,12 @@ - + - + @@ -765,8 +765,8 @@ - - + + @@ -785,13 +785,13 @@ - + - + @@ -817,7 +817,7 @@ - + @@ -828,15 +828,15 @@ - + - - + + @@ -849,7 +849,7 @@ - + @@ -867,7 +867,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -908,7 +908,7 @@ - + @@ -931,8 +931,8 @@ - - + + @@ -953,7 +953,7 @@ - + @@ -989,8 +989,8 @@ - - + + @@ -1025,8 +1025,8 @@ - - + + @@ -1061,8 +1061,8 @@ - - + + @@ -1086,10 +1086,10 @@ - + - + @@ -1126,7 +1126,7 @@ - + @@ -1138,7 +1138,7 @@ - + @@ -1150,7 +1150,7 @@ - + @@ -1167,18 +1167,18 @@ - + - + - + - + @@ -1198,7 +1198,7 @@ - + @@ -1233,12 +1233,12 @@ - + - + \ No newline at end of file diff --git a/FrontEndAst/CheckAsn1.fs b/FrontEndAst/CheckAsn1.fs index 134af96d5..e30351137 100644 --- a/FrontEndAst/CheckAsn1.fs +++ b/FrontEndAst/CheckAsn1.fs @@ -16,9 +16,9 @@ open Asn1Ast open FsUtils open CommonTypes -let c_keywords = CommonTypes.c_keyworkds -let scala_keywords = CommonTypes.scala_keyworkds -let ada_keywords = CommonTypes.ada_keyworkds +let c_keywords = CommonTypes.c_keywords +let scala_keywords = CommonTypes.scala_keywords +let ada_keywords = CommonTypes.ada_keywords // TODO: Scala let all_keywords = @@ -38,12 +38,12 @@ let checkAgainstKeywords (strLc : StringLoc) = match checkForAdaKeywords () with | false -> () | true ->raise (SemanticError (strLc.Location, errMsg)) - - - -///chekcs whether the input values is int or not + + + +///checks whether the input values is int or not let rec IsValueInt (v:Asn1Value) ast = match v.Kind with | IntegerValue(_) -> true @@ -60,12 +60,12 @@ let rec TypeValueMatch (t:Asn1Type) (typeNames:(StringLoc*StringLoc)list) (v:Asn | ReferenceType ref -> [(ref.modName,ref.tasName)] | _ -> [] let isNumeric s = true - let typesMatch = + let typesMatch = match typeNames, valueTypeNames with | [], [] -> true | _::_, [] -> true | [], _::_ -> true - | (t_mdName,tasName)::_, (v_mdName,v_tasName)::_ -> + | (t_mdName,tasName)::_, (v_mdName,v_tasName)::_ -> match t_mdName = v_mdName && tasName = v_tasName with | true -> true | false -> raise(SemanticError(v.Location, sprintf "Expecting value of type '%s.%s' but a value of type '%s.%s' was provided" t_mdName.Value tasName.Value v_mdName.Value v_tasName.Value)) @@ -87,16 +87,16 @@ let rec TypeValueMatch (t:Asn1Type) (typeNames:(StringLoc*StringLoc)list) (v:Asn | OctetString, BitStringValue(bitVal) -> true | ObjectIdentifier, ObjOrRelObjIdValue _ -> true | RelativeObjectIdentifier, ObjOrRelObjIdValue _ -> true - | Enumerated(enItems), RefValue(modName,vasName) -> - if enItems |> Seq.exists(fun en -> en.Name = vasName) then + | Enumerated(enItems), RefValue(modName,vasName) -> + if enItems |> Seq.exists(fun en -> en.Name = vasName) then true else let basType = getRefValueBaseTypes modName vasName TypeValueMatch t typeNames (GetBaseValue modName vasName ast) (basType@valueTypeNames) ast - | SequenceOf(child), SeqOfValue(chValues) -> + | SequenceOf(child), SeqOfValue(chValues) -> chValues |> Seq.forall(fun chv -> TypeValueMatch child [] chv [] ast) - | Sequence(children), SeqValue(chValues) -> - let checkChild (ch:ChildInfo) = + | Sequence(children), SeqValue(chValues) -> + let checkChild (ch:ChildInfo) = let chValue = chValues |> Seq.tryFind(fun v -> ch.Name = (fst v)) match chValue with | Some(_,actVal) -> TypeValueMatch ch.Type [] actVal [] ast @@ -113,7 +113,7 @@ let rec TypeValueMatch (t:Asn1Type) (typeNames:(StringLoc*StringLoc)list) (v:Asn match ch with | None -> false | Some(child) -> TypeValueMatch child.Type [] chVal [] ast - | _, RefValue(modName,vasName) -> + | _, RefValue(modName,vasName) -> let vas = GetBaseValue modName vasName ast let basType = getRefValueBaseTypes modName vasName TypeValueMatch t typeNames vas (basType@valueTypeNames) ast @@ -141,7 +141,7 @@ let rec AreAsn1ValuesEqual (v1:Asn1Value) (v2:Asn1Value) (isOfEnumType:bool) ast | RefValue(modName,vasName), _ when not isOfEnumType -> AreAsn1ValuesEqual (GetBaseValue modName vasName ast) v2 isOfEnumType ast | _, RefValue(modName,vasName) when not isOfEnumType -> AreAsn1ValuesEqual v1 (GetBaseValue modName vasName ast) isOfEnumType ast |_,_ -> false - + let rec CompareAsn1Value (v1:Asn1Value) (v2:Asn1Value) ast = let comparePrimitiveValues a1 a2 = @@ -162,7 +162,7 @@ type TYPE_BIT_OR_OCT_STR = | TP_OCT_STR | TP_BIT_STR -let CreateDummyValueByKind moduleName valKind = +let CreateDummyValueByKind moduleName valKind = { Asn1Value.Kind = valKind Location = {SrcLoc.srcFilename="";srcLine=0; charPos=0} @@ -173,49 +173,49 @@ let CreateDummyValueByKind moduleName valKind = let rec IsValueAllowed (c:Asn1Constraint) (v:Asn1Value) (isOfEnumType:bool) (bitOrOctSrt:TYPE_BIT_OR_OCT_STR option) (ast:AstRoot) = let CreateDummyValueByKind = CreateDummyValueByKind v.moduleName match c with - | SingleValueContraint(_, v1) -> AreAsn1ValuesEqual v1 v isOfEnumType ast - | RangeContraint(_, v1, v2, minInclusi, maxInclusive) -> - match minInclusi, maxInclusive with + | SingleValueConstraint(_, v1) -> AreAsn1ValuesEqual v1 v isOfEnumType ast + | RangeConstraint(_, v1, v2, minInclusive, maxInclusive) -> + match minInclusive, maxInclusive with | true, true ->CompareAsn1Value v1 v ast <=0 && CompareAsn1Value v v2 ast <= 0 | true, false ->CompareAsn1Value v1 v ast <=0 && CompareAsn1Value v v2 ast < 0 | false,true ->CompareAsn1Value v1 v ast <0 && CompareAsn1Value v v2 ast <= 0 | false,false ->CompareAsn1Value v1 v ast <0 && CompareAsn1Value v v2 ast < 0 - | RangeContraint_val_MAX(_, v1, minInclusi) -> - match minInclusi with + | RangeConstraint_val_MAX(_, v1, minInclusive) -> + match minInclusive with | true -> CompareAsn1Value v1 v ast <=0 | false -> CompareAsn1Value v1 v ast <0 - | RangeContraint_MIN_val(_, v2, maxInclusive) -> + | RangeConstraint_MIN_val(_, v2, maxInclusive) -> match maxInclusive with | true -> CompareAsn1Value v v2 ast <= 0 | false -> CompareAsn1Value v v2 ast < 0 - | RangeContraint_MIN_MAX -> true - | SizeContraint(_, sc) -> - let rec IsSizeContraintOK (v:Asn1Value) (sc:Asn1Constraint) = + | RangeConstraint_MIN_MAX -> true + | SizeConstraint(_, sc) -> + let rec IsSizeConstraintOK (v:Asn1Value) (sc:Asn1Constraint) = match v.Kind with - | StringValue(s, l) -> + | StringValue(s, l) -> let mergedStr = StringValue2String s IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger mergedStr.Length))) ) isOfEnumType bitOrOctSrt ast - | BitStringValue(s) -> + | BitStringValue(s) -> match bitOrOctSrt with | Some TP_BIT_STR -> IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger s.Value.Length))) ) isOfEnumType bitOrOctSrt ast | Some TP_OCT_STR when s.Value.Length%8 = 0 -> IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger (s.Value.Length/8)))) ) isOfEnumType bitOrOctSrt ast | _ -> false - | OctetStringValue(a) -> + | OctetStringValue(a) -> match bitOrOctSrt with | Some TP_BIT_STR -> IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger (a.Length*8)))) ) isOfEnumType bitOrOctSrt ast | Some TP_OCT_STR -> IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger (a.Length*1)))) ) isOfEnumType bitOrOctSrt ast | None -> false | SeqOfValue(a) -> IsValueAllowed sc (CreateDummyValueByKind (IntegerValue(IntLoc.ByValue (BigInteger (Seq.length a)))) ) isOfEnumType bitOrOctSrt ast - | RefValue(modName,vasName) -> IsSizeContraintOK (GetBaseValue modName vasName ast) sc + | RefValue(modName,vasName) -> IsSizeConstraintOK (GetBaseValue modName vasName ast) sc | _ -> raise (BugErrorException("")) - IsSizeContraintOK v sc - | AlphabetContraint(_, ac) -> + IsSizeConstraintOK v sc + | AlphabetConstraint(_, ac) -> let rec IsAlphabetConstraintOK (v:Asn1Value) (ac:Asn1Constraint) = match v.Kind with - | StringValue(s, l) -> + | StringValue(s, l) -> let sValue = StringValue2String s match ac with - | SingleValueContraint (_, setVal) -> + | SingleValueConstraint (_, setVal) -> match setVal.Kind with | StringValue (setvaluesstr,l2) -> let setvaluesstrValue = StringValue2String setvaluesstr @@ -224,17 +224,17 @@ let rec IsValueAllowed (c:Asn1Constraint) (v:Asn1Value) (isOfEnumType:bool) (bit | _ -> false | _ -> let sDummyVal (c:SingleStringValue) = CreateDummyValueByKind (StringValue([c], emptyLocation ) ) - sValue.ToCharArray() |> + sValue.ToCharArray() |> Seq.map char2SingleStringValue |> - Seq.forall(fun c -> + Seq.forall(fun c -> let ret = IsValueAllowed ac (sDummyVal c) isOfEnumType bitOrOctSrt ast ret ) | RefValue(modName,vasName) -> IsAlphabetConstraintOK (GetBaseValue modName vasName ast) ac | _ -> raise (BugErrorException("")) - IsAlphabetConstraintOK v ac - | UnionConstraint(_, c1,c2,_) -> - let ret1 = IsValueAllowed c1 v isOfEnumType bitOrOctSrt ast + IsAlphabetConstraintOK v ac + | UnionConstraint(_, c1,c2,_) -> + let ret1 = IsValueAllowed c1 v isOfEnumType bitOrOctSrt ast let ret2 = IsValueAllowed c2 v isOfEnumType bitOrOctSrt ast ret1 || ret2 | IntersectionConstraint(_, c1,c2) -> IsValueAllowed c1 v isOfEnumType bitOrOctSrt ast && IsValueAllowed c2 v isOfEnumType bitOrOctSrt ast @@ -259,7 +259,7 @@ let rec IsValueAllowed (c:Asn1Constraint) (v:Asn1Value) (isOfEnumType:bool) (bit | SeqValue(children) -> let IsNamedConstraintOK (nc:NamedConstraint) = let ch = children |> Seq.tryFind(fun (nm, chV) -> nm=nc.Name ) - match nc.Mark, ch, nc.Contraint with + match nc.Mark, ch, nc.Constraint with | NoMark, None, _ -> true | NoMark, Some(_,chv), Some(ic) -> IsValueAllowed ic chv isOfEnumType bitOrOctSrt ast | NoMark, Some(_,chv), None -> true @@ -278,24 +278,24 @@ let rec IsValueAllowed (c:Asn1Constraint) (v:Asn1Value) (isOfEnumType:bool) (bit match nc with | None -> true | Some(rnc) -> - match rnc.Mark, rnc.Contraint with + match rnc.Mark, rnc.Constraint with | MarkAbsent, _ -> false - | _, Some(ic) -> IsValueAllowed ic inVal isOfEnumType bitOrOctSrt ast + | _, Some(ic) -> IsValueAllowed ic inVal isOfEnumType bitOrOctSrt ast | _, None -> true - | RefValue(modName,vasName) -> IsWithComponentsConstraintOK (GetBaseValue modName vasName ast) + | RefValue(modName,vasName) -> IsWithComponentsConstraintOK (GetBaseValue modName vasName ast) | _ -> raise (BugErrorException("")) IsWithComponentsConstraintOK v - - + + let rec CheckIfVariableViolatesTypeConstraints (t:Asn1Type) (v:Asn1Value) ast = match v.Kind, t.Kind with |_,ReferenceType rf -> let baseType = Asn1Ast.GetBaseTypeConsIncluded t ast CheckIfVariableViolatesTypeConstraints baseType v ast - |RefValue(modName,vasName), Enumerated(items) -> + |RefValue(modName,vasName), Enumerated(items) -> let bIsEnumItem = items |> Seq.exists(fun x -> x.Name.Value = vasName.Value) t.Constraints |> Seq.forall(fun c -> IsValueAllowed c v bIsEnumItem None ast ) - | _ -> + | _ -> let bitOrOctSrt = match (Asn1Ast.GetActualType t ast).Kind with | OctetString -> Some TP_OCT_STR @@ -304,36 +304,36 @@ let rec CheckIfVariableViolatesTypeConstraints (t:Asn1Type) (v:Asn1Value) ast = let ret = t.Constraints |> Seq.forall(fun c -> IsValueAllowed c v false bitOrOctSrt ast ) match v.Kind, t.Kind with | SeqOfValue chvs, SequenceOf ch -> ret && (chvs |> Seq.forall(fun cv -> CheckIfVariableViolatesTypeConstraints ch cv ast)) - | SeqValue chvs, Sequence chldn -> + | SeqValue chvs, Sequence chldn -> let chRet = - chvs |> - Seq.forall(fun (cn,cv) -> + chvs |> + Seq.forall(fun (cn,cv) -> match chldn |> Seq.tryFind(fun c -> c.Name.Value = cn.Value) with | Some ch -> CheckIfVariableViolatesTypeConstraints ch.Type cv ast | None -> false) ret && chRet - | ChValue (nm,chv), Choice chldn -> + | ChValue (nm,chv), Choice chldn -> let chRet = match chldn |> Seq.tryFind(fun c -> c.Name.Value = nm.Value) with | Some ch -> CheckIfVariableViolatesTypeConstraints ch.Type chv ast | None -> false ret && chRet - | _ -> ret + | _ -> ret let rec getEnumeratedAllowedEnumerations ast (m:Asn1Module) (t:Asn1Type) = match t.Kind with |ReferenceType rf -> let baseType = Asn1Ast.GetBaseTypeConsIncluded t ast - getEnumeratedAllowedEnumerations ast m baseType - |Enumerated(items) -> + getEnumeratedAllowedEnumerations ast m baseType + |Enumerated(items) -> items |> - List.choose(fun itm -> - let v = {Asn1Value.Location = itm.Name.Location; Kind = RefValue(m.Name, itm.Name); id = ReferenceToValue([],[]); moduleName = t.moduleName} + List.choose(fun itm -> + let v = {Asn1Value.Location = itm.Name.Location; Kind = RefValue(m.Name, itm.Name); id = ReferenceToValue([],[]); moduleName = t.moduleName} match t.Constraints |> Seq.forall(fun c -> IsValueAllowed c v true None ast ) with | true -> Some itm | false-> None) | _ -> raise (BugErrorException("getEnumItemTypeAllowedEnums can be called only for Enumerated types")) - + ///checks if the input type t matches with input value v (by calling TypeValueMatch) and raises a user exception if not @@ -348,8 +348,8 @@ let CheckValueType (ot:Asn1Type) (v:Asn1Value) ast= | None -> raise(SemanticError(v.Location, (sprintf "Invalid id:%s" altName.Value) )) | Some(child) -> CheckValueType child.Type chVal ast - | Sequence(children), SeqValue(chValues) -> - let checkChild (ch:ChildInfo) = + | Sequence(children), SeqValue(chValues) -> + let checkChild (ch:ChildInfo) = let chValue = chValues |> Seq.tryFind(fun v -> ch.Name = (fst v)) match chValue with | Some(_,actVal) -> CheckValueType ch.Type actVal ast @@ -357,7 +357,7 @@ let CheckValueType (ot:Asn1Type) (v:Asn1Value) ast= | Some(Optional(_)) -> () | Some(AlwaysAbsent) -> () | _ -> raise(SemanticError(v.Location, sprintf "missing value for component: %s" ch.Name.Value )) - + let childrenStatus = children |> Seq.iter checkChild chValues |> Seq.iter(fun v -> if not (children |> Seq.exists(fun c -> c.Name = (fst v))) then let unknownName = (fst v) @@ -365,7 +365,7 @@ let CheckValueType (ot:Asn1Type) (v:Asn1Value) ast= raise (SemanticError(loc, (sprintf "Invalid id: %s" nm)) ) ) | ReferenceType(_),_ -> CheckValueType (GetActualType t ast) v ast - | _ -> + | _ -> let typeName = match ot.Kind with | ReferenceType rf -> sprintf "%s.%s" rf.modName.Value rf.tasName.Value @@ -379,44 +379,44 @@ let rec AreTypesCompatible (t1:Asn1Type) (t2:Asn1Type) ast = match t1.Kind, t2.Kind with | ReferenceType(_), _ -> AreTypesCompatible (GetActualType t1 ast) t2 ast | _, ReferenceType(_) -> AreTypesCompatible t1 (GetActualType t2 ast) ast - | Sequence(c1), Sequence(c2) | Choice(c1), Choice(c2) -> + | Sequence(c1), Sequence(c2) | Choice(c1), Choice(c2) -> let sameSize = Seq.length c1 = Seq.length c2 let names1 = c1 |> Seq.map(fun x -> x.Name.Value, x.Optionality) |> Seq.toList let names2 = c2 |> Seq.map(fun x -> x.Name.Value, x.Optionality) |> Seq.toList let sameNames = c1 = c2 let zipped = Seq.zip (c1 |> Seq.map(fun x-> x.Type)) (c2 |> Seq.map(fun x-> x.Type)) - sameSize && sameNames && zipped |> Seq.forall(fun (a1,a2)-> AreTypesCompatible a1 a2 ast) + sameSize && sameNames && zipped |> Seq.forall(fun (a1,a2)-> AreTypesCompatible a1 a2 ast) | SequenceOf(child1), SequenceOf(child2) -> AreTypesCompatible child1 child2 ast - | Enumerated(items1), Enumerated(items2) -> + | Enumerated(items1), Enumerated(items2) -> let sameSize = Seq.length items1 = Seq.length items2 let names1 = items1 |> Seq.map(fun x -> x.Name.Value) |> Seq.toList let names2 = items1 |> Seq.map(fun x -> x.Name.Value) |> Seq.toList sameSize && names1=names2 | _ ,_ -> t1.Kind.ToString() = t2.Kind.ToString() - -/// it checks if the input type t can have the constraint c + +/// it checks if the input type t can have the constraint c /// returns true/false let rec isConstraintValid (t:Asn1Type) (c:Asn1Constraint) ast = - let rec CanHaveRangeContraint (t:Asn1Type) = + let rec CanHaveRangeConstraint (t:Asn1Type) = match t.Kind with | Integer | Real | IA5String | NumericString -> true | ObjectIdentifier | RelativeObjectIdentifier -> false | NullType | Boolean | Enumerated(_) | Sequence(_) | Choice(_) -> false | OctetString | BitString(_) | SequenceOf(_) | TimeType _ -> false - | ReferenceType(_) -> CanHaveRangeContraint (GetActualType t ast) + | ReferenceType(_) -> CanHaveRangeConstraint (GetActualType t ast) - let rec CanHaveSizeContraint (t:Asn1Type) = + let rec CanHaveSizeConstraint (t:Asn1Type) = match t.Kind with | Integer | Real | NullType | Boolean | Enumerated(_) | Sequence(_) | Choice(_) -> false | ObjectIdentifier | RelativeObjectIdentifier | TimeType _ -> false | IA5String | NumericString | OctetString | BitString(_) | SequenceOf(_) -> true - | ReferenceType(_) -> CanHaveSizeContraint (GetActualType t ast) - let rec CanHaveFromContraint (t:Asn1Type) = + | ReferenceType(_) -> CanHaveSizeConstraint (GetActualType t ast) + let rec CanHaveFromConstraint (t:Asn1Type) = match t.Kind with | Integer | Real | NullType | Boolean | Enumerated(_) | Sequence(_) | Choice(_) | OctetString | BitString(_) | SequenceOf(_) -> false | ObjectIdentifier | RelativeObjectIdentifier | TimeType _ -> false | IA5String | NumericString -> true - | ReferenceType(_) -> CanHaveFromContraint (GetActualType t ast) + | ReferenceType(_) -> CanHaveFromConstraint (GetActualType t ast) let rec CanHaveWithComponentConstraint (t:Asn1Type) = match t.Kind with | Integer | Real | NullType | Boolean | Enumerated(_) | Choice(_) | Sequence(_) -> None @@ -432,58 +432,58 @@ let rec isConstraintValid (t:Asn1Type) (c:Asn1Constraint) ast = | Sequence(children) | Choice(children) -> Some(children) | ReferenceType(_) -> CanHaveWithComponentsConstraint (GetActualType t ast) match c with - | SingleValueContraint(_, v1) -> CheckValueType t v1 ast - | RangeContraint(_, v1,v2,_,_) -> - if not(CanHaveRangeContraint t) then + | SingleValueConstraint(_, v1) -> CheckValueType t v1 ast + | RangeConstraint(_, v1,v2,_,_) -> + if not(CanHaveRangeConstraint t) then raise(SemanticError(t.Location, "Type does not support range constraints")) CheckValueType t v1 ast CheckValueType t v2 ast - | RangeContraint_val_MAX(_, v1,_) - | RangeContraint_MIN_val(_, v1,_) -> - if not(CanHaveRangeContraint t) then + | RangeConstraint_val_MAX(_, v1,_) + | RangeConstraint_MIN_val(_, v1,_) -> + if not(CanHaveRangeConstraint t) then raise(SemanticError(t.Location, "Type does not support range constraints")) CheckValueType t v1 ast - | RangeContraint_MIN_MAX -> - if not(CanHaveRangeContraint t) then + | RangeConstraint_MIN_MAX -> + if not(CanHaveRangeConstraint t) then raise(SemanticError(t.Location, "Type does not support range constraints")) - | SizeContraint(_, c1) -> - if not(CanHaveSizeContraint t) then + | SizeConstraint(_, c1) -> + if not(CanHaveSizeConstraint t) then raise(SemanticError(t.Location, "Type does not support size constraints")) isConstraintValid { t with Kind=Integer; Constraints=[] } c1 ast - | AlphabetContraint(_, c1) -> - if not(CanHaveFromContraint t) then + | AlphabetConstraint(_, c1) -> + if not(CanHaveFromConstraint t) then raise(SemanticError(t.Location, "Type does not support alphabet constraints")) isConstraintValid t c1 ast | UnionConstraint(_, c1,c2,_) | IntersectionConstraint(_, c1,c2) | ExceptConstraint(_, c1,c2) | RootConstraint2(_, c1,c2) -> isConstraintValid t c1 ast isConstraintValid t c2 ast | AllExceptConstraint(_, c1) | RootConstraint(_, c1) -> isConstraintValid t c1 ast - | TypeInclusionConstraint(_, mdName, refName) -> + | TypeInclusionConstraint(_, mdName, refName) -> let typeInclusion = GetActualTypeByName mdName refName ast let actType = GetActualType t ast if not(AreTypesCompatible typeInclusion actType ast) then raise (SemanticError(t.Location, "Incompatible types used in type inclusion constraint")) - | WithComponentConstraint(_, c1, loc) -> + | WithComponentConstraint(_, c1, loc) -> match CanHaveWithComponentConstraint t with | None -> raise (SemanticError(loc, "Type does not support WITH COMPONENT constraints")) | Some(ch) -> isConstraintValid ch c1 ast - | WithComponentsConstraint(_, namedCons) -> + | WithComponentsConstraint(_, namedCons) -> match CanHaveWithComponentsConstraint t with | None -> raise (SemanticError(t.Location, "Type does not support WITH COMPONENTS constraints")) - | Some(children) -> + | Some(children) -> namedCons |> List.map(fun z -> z.Name) |> CheckForDuplicates - let checkNamedConstraint (nc:NamedConstraint) = + let checkNamedConstraint (nc:NamedConstraint) = let (conName, loc) = nc.Name.AsTupple match children |> Seq.tryFind(fun c -> c.Name.Value = conName) with | None -> raise (SemanticError(loc, sprintf "Invalid id: %s" conName)) - | Some(child) -> + | Some(child) -> let isChoice = match (GetActualType t ast).Kind with Choice(_) -> true | _ -> false - match nc.Contraint with - | Some(newC) -> isConstraintValid child.Type newC ast + match nc.Constraint with + | Some(newC) -> isConstraintValid child.Type newC ast | _ -> () match child.Optionality, nc.Mark, isChoice with | Some(Optional opt), MarkAbsent,false when opt.defaultValue.IsSome-> raise(SemanticError (loc, sprintf "Component %s has default value and therefore it cannot be constraint to ABSENT" conName)) - | None, MarkAbsent,false + | None, MarkAbsent,false | None, MarkPresent,false -> raise(SemanticError (loc, sprintf "Component %s is not optional. So, it cannot be constraint to ABSENT or PRESENT" conName)) | _, MarkPresent, true | _, MarkOptional, true -> raise(SemanticError (loc, sprintf "Choice alternative %s cannot be constraint to PRESENT or OPTIONAL" conName)) @@ -497,19 +497,19 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = let CheckSeqChoiceChildren bChoice (children:seq) = let childrenNames = children |> Seq.map(fun c -> c.Name) |> Seq.toList match bChoice with - | true -> childrenNames |> CheckForDuplicatesCaseCaseInsensitive + | true -> childrenNames |> CheckForDuplicatesCaseCaseInsensitive | false -> childrenNames |> CheckForDuplicates - + match ast.args.fieldPrefix with | None -> childrenNames |> Seq.iter checkAgainstKeywords | Some _ -> () - + //check that component name does not conflict with a type assignment - children |> + children |> Seq.map(fun c -> c.Name) |> Seq.iter(fun c -> match ast.Modules |> Seq.tryFind(fun m -> m.Name.Value.ToLower() = ToC (c.Value.ToLower())) with - | Some m -> + | Some m -> let errMsg = sprintf "component name '%s' conflicts with module '%s'. May cause compilation errors in case insensitive languages.\nTo overcome this problem use --field-prefix argument." c.Value m.Name.Value match ast.args.fieldPrefix with | None -> raise(SemanticError(c.Location, errMsg)) @@ -517,7 +517,7 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = | None -> match m.TypeAssignments |> Seq.tryFind(fun tas -> ToC ((ast.args.TypePrefix + tas.Name.Value).ToLower()) = ToC (c.Value.ToLower()) ) with - | Some tas -> + | Some tas -> let errMsg = sprintf "component name '%s' conflicts with type assignment '%s'. May cause compilation errors in case insensitive languages.\nTo overcome this problem use the -typePrefix argument to add a prefix to all generated types or\nuse --field-prefix argument." c.Value tas.Name.Value match checkForAdaKeywords () with | false -> () @@ -525,32 +525,32 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = match ast.args.fieldPrefix with | None -> raise(SemanticError(c.Location, errMsg)) | Some _ -> () - + | None -> ()) - + children |> Seq.map(fun c -> c.Type) |> Seq.iter (fun x -> CheckType x m ast) - children |> - Seq.choose(fun c -> - match c.Optionality with - | Some(Optional opt) -> + children |> + Seq.choose(fun c -> + match c.Optionality with + | Some(Optional opt) -> match opt.defaultValue with - | Some v -> Some (c.Type, v) + | Some v -> Some (c.Type, v) | None -> None - |_->None) - |> Seq.iter (fun (t,v) -> + |_->None) + |> Seq.iter (fun (t,v) -> CheckValueType t v ast let ret = CheckIfVariableViolatesTypeConstraints t v ast match ret with - | false -> + | false -> let msg = sprintf "Value does not conform to its type constraints" raise(SemanticError(v.Location,msg)) | true -> () ) let CheckNamedItem (children:seq) = - children |> Seq.map(fun c -> c.Name) |> CheckForDuplicates - children |> + children |> Seq.map(fun c -> c.Name) |> CheckForDuplicates + children |> Seq.iter(fun c -> match c._value with - |Some (intVal) -> + |Some (intVal) -> if IsValueInt intVal ast then () else raise(SemanticError(intVal.Location,"Expecting integer value")) |None -> ()) @@ -558,11 +558,11 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = | Sequence(children) -> CheckSeqChoiceChildren false children | Choice(children) -> CheckSeqChoiceChildren true children | SequenceOf(child) -> CheckType child m ast - | Enumerated(children) -> + | Enumerated(children) -> let getVal vKind = { Asn1Value.Kind = vKind; Location = emptyLocation; id = ReferenceToValue([],[]); moduleName = t.moduleName } - CheckNamedItem children - children |> Seq.filter(fun x -> x._value.IsSome) |> Seq.map(fun c -> {IntLoc.Value=GetValueAsInt c._value.Value ast; Location=c._value.Value.Location}) |> CheckForDuplicates - match children |> Seq.tryFind (fun itm -> + CheckNamedItem children + children |> Seq.filter(fun x -> x._value.IsSome) |> Seq.map(fun c -> {IntLoc.Value=GetValueAsInt c._value.Value ast; Location=c._value.Value.Location}) |> CheckForDuplicates + match children |> Seq.tryFind (fun itm -> let checkCon c = IsValueAllowed c (getVal (RefValue (m.Name, itm.Name) )) true None ast t.Constraints |> List.fold(fun state cn -> state && (checkCon cn)) true) with | Some itm -> () @@ -585,7 +585,7 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = | NumericString -> () | NullType -> () | OctetString -> () - | ReferenceType impRef -> + | ReferenceType impRef -> let impMod = ast.GetModuleByName impRef.modName match impMod.ExportedTypes |> Seq.tryFind ( (=) impRef.tasName.Value) with | Some _ -> () @@ -596,33 +596,33 @@ let rec CheckType(t:Asn1Type) (m:Asn1Module) ast = /// semantically check module let CheckModule (m:Asn1Module) ast (pass :int)= //check for duplicate type assignments - let typeAssNames = m.TypeAssignments |> List.map(fun t -> t.Name) - typeAssNames |> CheckForDuplicates + let typeAssNames = m.TypeAssignments |> List.map(fun t -> t.Name) + typeAssNames |> CheckForDuplicates typeAssNames |> CheckForDuplicatesCI "Type Assignment" - + //typeAssNames |> Seq.iter(fun z -> checkAgainstKeywords ({z with Value = ast.args.TypePrefix + z.Value})) - + //check for duplicate imported types let importedTypeAssNames = m.Imports |> Seq.collect(fun imp -> imp.Types) |> Seq.toList - importedTypeAssNames |> CheckForDuplicates + importedTypeAssNames |> CheckForDuplicates //check for duplicate in type assignments AND imported types - Seq.concat [typeAssNames; importedTypeAssNames] |> CheckForDuplicates + Seq.concat [typeAssNames; importedTypeAssNames] |> CheckForDuplicates //check for duplicate value assignments - let valAssNames = m.ValueAssignments |> Seq.map(fun t -> t.Name) - valAssNames |> CheckForDuplicates + let valAssNames = m.ValueAssignments |> Seq.map(fun t -> t.Name) + valAssNames |> CheckForDuplicates valAssNames |> CheckForDuplicatesCI "Value Assignment" valAssNames |> Seq.iter checkAgainstKeywords //check for duplicate imported values - let importedValAssNames = m.Imports |> Seq.collect(fun imp -> imp.Values) - importedValAssNames |> CheckForDuplicates + let importedValAssNames = m.Imports |> Seq.collect(fun imp -> imp.Values) + importedValAssNames |> CheckForDuplicates //check for duplicate value assignments AND imported values - Seq.concat [valAssNames; importedValAssNames] |> CheckForDuplicates + Seq.concat [valAssNames; importedValAssNames] |> CheckForDuplicates // Check Types m.TypeAssignments |> Seq.map(fun x -> x.Type) |> Seq.iter (fun x -> CheckType x m ast) @@ -632,26 +632,26 @@ let CheckModule (m:Asn1Module) ast (pass :int)= m.ValueAssignments |> Seq.iter(fun vas -> CheckValueType vas.Type vas.Value ast) if (pass = 0) then - m.ValueAssignments |> Seq.iter(fun vas -> + m.ValueAssignments |> Seq.iter(fun vas -> let fname = System.IO.Path.GetFileName vas.Name.Location.srcFilename - if not(CheckIfVariableViolatesTypeConstraints vas.Type vas.Value ast) + if not(CheckIfVariableViolatesTypeConstraints vas.Type vas.Value ast) then System.Console.Error.WriteLine("Warning: Value {0} defined in File:{1}, Line:{2} does not conform to its type constraints.", vas.Name.Value, fname, vas.Name.Location.srcLine)) let checkImport (imp: Asn1Ast.ImportedModule) = //check that imported module does exists match ast.Modules |> Seq.tryFind(fun x -> x.Name.Value = imp.Name.Value) with | None -> raise (SemanticError(imp.Name.Location, sprintf "No module with name %s exists" imp.Name.Value)) - | Some(im) -> + | Some(im) -> let checkTasName tasName = match im.TypeAssignments |> Seq.tryFind(fun x-> x.Name.Value = tasName.Value ) with - | Some(_) -> + | Some(_) -> match im.ExportedTypes |> Seq.tryFind((=) tasName.Value ) with | Some (_) -> () | None -> raise(SemanticError(tasName.Location, sprintf "Type assignment '%s' is privately defined in module '%s'. Use EXPORT keyword to make it visible to other modules." tasName.Value imp.Name.Value)) | None -> raise(SemanticError(tasName.Location, sprintf "No type assignment with name %s exists in module %s" tasName.Value imp.Name.Value)) let checkVasName vasName = match im.ValueAssignments |> Seq.tryFind(fun x-> x.Name.Value = vasName.Value ) with - | Some(_) -> + | Some(_) -> match im.ExportedVars |> Seq.tryFind( (=) vasName.Value ) with | Some (_) -> () | None -> raise(SemanticError(vasName.Location, sprintf "Value assignment %s is privately defined in module '%s'. Use EXPORT keyword to make it visible to other modules" vasName.Value imp.Name.Value)) @@ -660,23 +660,23 @@ let CheckModule (m:Asn1Module) ast (pass :int)= imp.Values |> Seq.iter checkVasName m.Imports |> Seq.iter checkImport - + let checkForCyclicModules ( ast:AstRoot) = let allModules = ast.Modules |> List.map(fun z -> z.Name) let independentModules = ast.Modules |> List.filter(fun m -> List.isEmpty m.Imports) |> List.map(fun m -> m.Name) let dependentModules = ast.Modules |> List.filter(fun m -> not (List.isEmpty m.Imports)) |> List.map(fun m -> (m.Name, m.Imports |> List.map(fun imp -> imp.Name) )) - let sortedModules = - DoTopologicalSort independentModules dependentModules - (fun cyclicModules -> + let sortedModules = + DoTopologicalSort independentModules dependentModules + (fun cyclicModules -> match cyclicModules with | [] -> BugErrorException "Impossible" | (m1,deps) ::_ -> - let printModule (md:StringLoc, deps: StringLoc list) = + let printModule (md:StringLoc, deps: StringLoc list) = sprintf "Module '%s' depends on modules: %s" md.Value (deps |> List.map(fun z -> "'" + z.Value + "'") |> Seq.StrJoin ", ") let cycMods = cyclicModules |> List.map printModule |> Seq.StrJoin "\n\tand\n" SemanticError - (m1.Location, - sprintf + (m1.Location, + sprintf "Cyclic modules detected:\n%s\n" cycMods)) sortedModules @@ -684,10 +684,10 @@ let CheckFiles( ast:AstRoot) (pass :int) = checkForCyclicModules ast |> ignore let modules = ast.Files |> Seq.collect(fun f -> f.Modules ) |> Seq.toList // check for multiple module definitions - modules |> Seq.map(fun m-> m.Name) |> CheckForDuplicates + modules |> Seq.map(fun m-> m.Name) |> CheckForDuplicates // check each file modules |> Seq.iter (fun x -> CheckModule x ast pass) - - + + diff --git a/FrontEndAst/CheckLongReferences.fs b/FrontEndAst/CheckLongReferences.fs index e9d8eb1f9..5acaa077c 100644 --- a/FrontEndAst/CheckLongReferences.fs +++ b/FrontEndAst/CheckLongReferences.fs @@ -17,18 +17,18 @@ let private addParameter (cur:AcnInsertedFieldDependencies) (asn1Type:Asn1Type) {cur with acnDependencies = {AcnDependency.asn1Type = asn1Type.id; determinant = (AcnParameterDeterminant p); dependencyKind = d}::cur.acnDependencies } let private addAcnChild (tasPositions:Map) (cur:AcnInsertedFieldDependencies) (asn1Type:Asn1Type) (acnChild:AcnChild) (d:AcnDependencyKind) = - let determinantPos = + let determinantPos = match tasPositions.ContainsKey acnChild.id with | true -> tasPositions.[acnChild.id] - | false -> - let errMsg = sprintf "ACN determinant field '%s' not found in the dictionary" acnChild.id.AsString + | false -> + let errMsg = sprintf "ACN determinant field '%s' not found in the dictionary" acnChild.id.AsString raise(SemanticError(acnChild.Name.Location, errMsg)) - let asn1TypePos = + let asn1TypePos = match tasPositions.ContainsKey asn1Type.id with | true -> tasPositions.[asn1Type.id] | false -> - let errMsg = sprintf "ASN.1 TYPE '%s' not found in the dictionary" asn1Type.id.AsString + let errMsg = sprintf "ASN.1 TYPE '%s' not found in the dictionary" asn1Type.id.AsString raise(SemanticError(acnChild.Name.Location, errMsg)) if asn1TypePos < determinantPos then let errMsg = sprintf "ACN determinant field '%s' must appear before ASN.1 type '%s'" acnChild.id.AsString asn1Type.id.AsString @@ -40,11 +40,11 @@ let private checkRelativePath (tasPositions:Map) (curState: | [] -> raise (BugErrorException("Invalid Argument")) | x1::_ -> match visibleParameters |> Seq.tryFind(fun (ref, p) -> p.name = x1.Value) with - | Some (rf,p) -> + | Some (rf,p) -> //x1 is a parameter let d = checkParameter p addParameter curState asn1TypeWithDependency p d - | None -> + | None -> (* //x1 is silbing child match parents |> List.rev with @@ -53,53 +53,53 @@ let private checkRelativePath (tasPositions:Map) (curState: match parent.Kind with | Sequence seq -> match seq.children |> Seq.tryFind(fun (c:SeqChildInfo) -> c.Name = x1) with - | Some ch -> + | Some ch -> match ch with | Asn1Child ch -> raise(SemanticError(x1.Location, (sprintf "ASN.1 fields cannot act as encoding determinants. Remove field '%s' from the ASN.1 grammar and introduce it in the ACN grammar" x1.Value))) - | AcnChild ch -> + | AcnChild ch -> let d = checkAcnType ch addAcnChild tasPositions curState asn1TypeWithDependency ch d | None -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" x1.Value))) | _ -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" x1.Value))) *) -// | x1::_ -> +// | x1::_ -> //x1 may be a silbing child or a child to one of my parents // so, find the first parent that has a child x1 - let parSeq = + let parSeq = let rec findSeq p = match p.Kind with - | Sequence seq -> seq.children |> Seq.exists(fun c -> c.Name = x1) + | Sequence seq -> seq.children |> Seq.exists(fun c -> c.Name = x1) | ReferenceType ref ->findSeq ref.resolvedType | _ -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (path |> Seq.StrJoin ".")))) - parents |> - List.rev |> - List.filter(fun z -> + parents |> + List.rev |> + List.filter(fun z -> match z.Kind with | Sequence _ -> true - | ReferenceType r -> + | ReferenceType r -> match r.resolvedType.Kind with | Sequence _ -> true | _ -> false | _ -> false ) |> Seq.tryFind findSeq - let rec checkSeqWithPath (seq:Asn1Type) (path : StringLoc list)= + let rec checkSeqWithPath (seq:Asn1Type) (path : StringLoc list)= match seq.Kind with - | Sequence seq -> + | Sequence seq -> match path with | [] -> raise(BugErrorException "111") | x1::[] -> match seq.children |> Seq.tryFind(fun c -> c.Name = x1) with | None -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (path |> Seq.StrJoin ".")))) - | Some ch -> + | Some ch -> match ch with | Asn1Child ch -> raise(SemanticError(x1.Location, (sprintf "ASN.1 fields cannot act as encoding determinants. Remove field '%s' from the ASN.1 grammar and introduce it in the ACN grammar" x1.Value))) - | AcnChild ch -> + | AcnChild ch -> let d = checkAcnType ch addAcnChild tasPositions curState asn1TypeWithDependency ch d | x1::xs -> match seq.children |> Seq.tryFind(fun c -> c.Name = x1) with | None -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (path |> Seq.StrJoin ".")))) - | Some ch -> + | Some ch -> match ch with | Asn1Child ch -> checkSeqWithPath ch.Type xs | _ -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (path |> Seq.StrJoin ".")))) @@ -108,7 +108,7 @@ let private checkRelativePath (tasPositions:Map) (curState: match parSeq with | None -> raise(SemanticError(x1.Location, (sprintf "Invalid reference '%s'" (path |> Seq.StrJoin ".")))) - | Some p -> + | Some p -> checkSeqWithPath p path @@ -119,36 +119,36 @@ let checkParamIsActuallyInteger (r:AstRoot) (prmMod0:StringLoc) (tasName0:String | Some md -> match md.TypeAssignments |> Seq.tryFind(fun z -> z.Name.Value = tasName.Value) with | None -> raise(SemanticError (tasName.Location, (sprintf "No type assignment defined with name '%s' in module '%s'" tasName.Value prmMod.Value))) - | Some ts -> + | Some ts -> match ts.Type.Kind with | Integer intInfo -> intInfo | ReferenceType refInfo -> checkParamIsActuallyInteger_aux r refInfo.modName refInfo.tasName - | _ -> + | _ -> raise(SemanticError (tasName.Location, (sprintf "Type assignment '%s' defined in module '%s' does not resolve to an Integer" tasName.Value prmMod.Value))) checkParamIsActuallyInteger_aux r prmMod0 tasName0 let sizeReference (r:AstRoot) (tasPositions:Map) (curState:AcnInsertedFieldDependencies) (parents: Asn1Type list) (t:Asn1Type) (sizeMin:BigInteger) (sizeMax:BigInteger) (visibleParameters:(ReferenceToType*AcnParameter) list) (rp :RelativePath option) (d:AcnDependencyKind) = match rp with | None -> curState - | Some (RelativePath path) -> + | Some (RelativePath path) -> let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type with - | AcnPrmInteger acnInt -> + | AcnPrmInteger acnInt -> d - | AcnPrmRefType (mdName,tsName) -> + | AcnPrmRefType (mdName,tsName) -> let intInfo = checkParamIsActuallyInteger r mdName tsName d | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting INTEGER got %s " (p.asn1Type.ToString())))) let checkAcnType (c:AcnChild) = match c.Type with - | AcnInteger ai -> + | AcnInteger ai -> ai.checkIntHasEnoughSpace sizeMin sizeMax d | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting INTEGER got %s " (c.Type.AsString)))) - + // first check the sizeable type is a fixed size type (i.e. sizeMin = sizeMax). In this case emit a user error // match sizeMin = sizeMax with // | true -> raise(SemanticError(loc, (sprintf "size acn property cannot be assigned to fixed size types. To fix this error remove 'size %s'." (path |> Seq.StrJoin ".")))) @@ -158,12 +158,12 @@ let sizeReference (r:AstRoot) (tasPositions:Map) (curState: let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) (curState:AcnInsertedFieldDependencies) (parents: Asn1Type list) (t:Asn1Type) (ch:Choice) (visibleParameters:(ReferenceToType*AcnParameter) list) = match ch.acnProperties.enumDeterminant with - | Some _ -> + | Some _ -> //1 check that there is no child with present-when property match ch.children |> List.collect(fun z -> z.acnPresentWhenConditions) with | c1::_ -> raise(SemanticError(c1.location, (sprintf "‘present-when’ attribute cannot appear when ‘determinant’ is present in the parent choice type" ))) | [] -> curState - | None -> + | None -> let childrenConditions = ch.children |> List.filter(fun z -> z.acnPresentWhenConditions.Length > 0) |> List.map(fun z -> z.acnPresentWhenConditions |> List.map(fun pc -> (pc.kind, pc.relativePath.AsString, pc.valueAsString)) |> List.sortBy (fun (_,p,_) -> p) |> Seq.toList) let duplicateCondtions = childrenConditions |> Seq.groupBy id |> Seq.map(fun (key, vals) -> Seq.length vals) |> Seq.filter(fun z -> z > 1) |> Seq.length match duplicateCondtions > 0 with @@ -177,12 +177,12 @@ let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) ( | [] -> curState | c1::cs -> let firstChildPresentWhenAttr = c1.acnPresentWhenConditions |> List.sortBy(fun z -> z.relativePath.AsString) |> List.map(fun z -> (z.kind, z.relativePath)) - cs |> + cs |> Seq.iter(fun c -> let curChildPresentWhenAttr = c.acnPresentWhenConditions |> List.sortBy(fun z -> z.relativePath.AsString) |> List.map(fun z -> (z.kind, z.relativePath)) match curChildPresentWhenAttr = firstChildPresentWhenAttr with | true -> () - | false -> + | false -> match curChildPresentWhenAttr, firstChildPresentWhenAttr with | [], [] -> () | [], (_,z)::_ -> raise(SemanticError(z.location, (sprintf "‘present-when’ attributes must appear in all alternatives" ))) @@ -191,17 +191,17 @@ let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) ( let checkAcnPresentWhenConditionChoiceChild (curState:AcnInsertedFieldDependencies) (a:AcnPresentWhenConditionChoiceChild) = match a with - | PresenceInt ((RelativePath path),intVal) -> + | PresenceInt ((RelativePath path),intVal) -> let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type with | AcnPrmInteger _ -> AcnDepPresence ((RelativePath path), ch) | AcnPrmRefType (prmMod, prmTas) -> let intInfo = checkParamIsActuallyInteger r prmMod prmTas - let isWithinRange = + let isWithinRange = match intInfo.uperRange with - | Concrete (a,b) -> a <= intVal.Value && intVal.Value <= b - | NegInf b -> intVal.Value <= b + | Concrete (a,b) -> a <= intVal.Value && intVal.Value <= b + | NegInf b -> intVal.Value <= b | PosInf a -> a <= intVal.Value | Full -> true match isWithinRange with @@ -211,11 +211,11 @@ let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) ( | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting INTEGER got %s " (p.asn1Type.ToString())))) let rec checkAcnType (c:AcnChild) = match c.Type with - | AcnInteger intInfo -> - let isWithinRange = + | AcnInteger intInfo -> + let isWithinRange = match intInfo.uperRange with - | Concrete (a,b) -> a <= intVal.Value && intVal.Value <= b - | NegInf b -> intVal.Value <= b + | Concrete (a,b) -> a <= intVal.Value && intVal.Value <= b + | NegInf b -> intVal.Value <= b | PosInf a -> a <= intVal.Value | Full -> true match isWithinRange with @@ -224,14 +224,14 @@ let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) ( AcnDepPresence ((RelativePath path), ch) | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting INTEGER got %s " (c.Type.AsString)))) checkRelativePath tasPositions curState parents t visibleParameters (RelativePath path) checkParameter checkAcnType - | PresenceStr ((RelativePath path), strVal)-> + | PresenceStr ((RelativePath path), strVal)-> let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type with - | AcnPrmRefType (md,ts) -> - let actType = GetActualTypeByName r md ts + | AcnPrmRefType (md,ts) -> + let actType = GetActualTypeByName r md ts match actType.Kind with - | IA5String str -> + | IA5String str -> match str.minSize.acn <= strVal.Value.Length.AsBigInt && strVal.Value.Length.AsBigInt <= str.maxSize.acn with | true -> AcnDepPresenceStr ((RelativePath path), ch, str) | false -> raise(SemanticError(strVal.Location, (sprintf "Length of value '%s' is not within the expected range: i.e. %d not in (%A .. %A)" strVal.Value strVal.Value.Length str.minSize str.maxSize))) @@ -240,19 +240,19 @@ let checkChoicePresentWhen (r:AstRoot) (tasPositions:Map) ( | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting STRING got %s " (p.asn1Type.ToString())))) let rec checkAcnType (c:AcnChild) = match c.Type with - | AcnReferenceToIA5String str -> + | AcnReferenceToIA5String str -> match str.str.minSize.acn <= strVal.Value.Length.AsBigInt && strVal.Value.Length.AsBigInt <= str.str.maxSize.acn with | true -> AcnDepPresenceStr ((RelativePath path), ch, str.str) | false -> raise(SemanticError(strVal.Location, (sprintf "Length of value '%s' is not within the expected range: i.e. %d not in (%A .. %A)" strVal.Value strVal.Value.Length str.str.minSize str.str.maxSize))) | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting STRING got %s " (c.Type.AsString)))) checkRelativePath tasPositions curState parents t visibleParameters (RelativePath path) checkParameter checkAcnType - + c1.acnPresentWhenConditions |> List.fold(fun ns pc -> checkAcnPresentWhenConditionChoiceChild ns pc ) curState - - + + let choiceEnumReference (r:AstRoot) (tasPositions:Map) (curState:AcnInsertedFieldDependencies) (parents: Asn1Type list) (t:Asn1Type) (ch:Choice) (visibleParameters:(ReferenceToType*AcnParameter) list) (rp :RelativePath option) = let children = ch.children let checkEnumNamesConsistency loc (nmItems:NamedItem list) = @@ -266,30 +266,30 @@ let choiceEnumReference (r:AstRoot) (tasPositions:Map) (cur match rp with | None -> curState - | Some (RelativePath path) -> + | Some (RelativePath path) -> let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type with - | AcnPrmRefType (md,ts) -> - let actType = GetActualTypeByName r md ts + | AcnPrmRefType (md,ts) -> + let actType = GetActualTypeByName r md ts match actType.Kind with - | Enumerated enm -> + | Enumerated enm -> checkEnumNamesConsistency ts.Location enm.items - AcnDepChoiceDeteterminant ({ReferenceToEnumerated.modName = md.Value; tasName = ts.Value; enm = enm} ,ch) + AcnDepChoiceDeterminant ({ReferenceToEnumerated.modName = md.Value; tasName = ts.Value; enm = enm} ,ch, t.id.lastItemIsOptional) | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting ENUMERATED got %s " (p.asn1Type.ToString())))) | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting ENUMERATED got %s " (p.asn1Type.ToString())))) let checkAcnType (c:AcnChild) = match c.Type with - | AcnReferenceToEnumerated enm -> + | AcnReferenceToEnumerated enm -> checkEnumNamesConsistency c.Name.Location enm.enumerated.items - AcnDepChoiceDeteterminant ({ReferenceToEnumerated.modName = enm.modName.Value; tasName = enm.tasName.Value; enm = enm.enumerated},ch) + AcnDepChoiceDeterminant ({ReferenceToEnumerated.modName = enm.modName.Value; tasName = enm.tasName.Value; enm = enm.enumerated}, ch, t.id.lastItemIsOptional) | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting ENUMERATED got %s " (c.Type.AsString)))) checkRelativePath tasPositions curState parents t visibleParameters (RelativePath path) checkParameter checkAcnType -let rec private checkType (r:AstRoot) (tasPositions:Map) (parents: Asn1Type list) (curentPath : ScopeNode list) (t:Asn1Type) (curState:AcnInsertedFieldDependencies) = - //the visible parameters of a type are this type parameters if type has parameters or the +let rec private checkType (r:AstRoot) (tasPositions:Map) (parents: Asn1Type list) (curentPath : ScopeNode list) (t:Asn1Type) (curState:AcnInsertedFieldDependencies) = + //the visible parameters of a type are this type parameters if type has parameters or the //next parent with parameters - let visibleParameters = + let visibleParameters = match parents@[t] |> List.rev |> List.filter(fun x -> not x.acnParameters.IsEmpty) with | [] -> [] | p1::_ -> p1.acnParameters |> List.map(fun p -> (p1.id, p)) @@ -307,23 +307,23 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p | Some (StrExternalField relPath) -> sizeReference r tasPositions curState parents t a.minSize.acn a.maxSize.acn visibleParameters (Some relPath) (AcnDepIA5StringSizeDeterminant (a.minSize, a.maxSize, a.acnProperties)) | _ -> curState - | OctetString a -> - let rp = - match a.acnProperties.sizeProp with + | OctetString a -> + let rp = + match a.acnProperties.sizeProp with | None -> None | Some (SzExternalField ef) -> Some ef | Some (SzNullTerminated _) -> None sizeReference r tasPositions curState parents t a.minSize.acn a.maxSize.acn visibleParameters rp (AcnDepSizeDeterminant (a.minSize, a.maxSize, a.acnProperties)) - | BitString a -> - let rp = - match a.acnProperties.sizeProp with + | BitString a -> + let rp = + match a.acnProperties.sizeProp with | None -> None | Some (SzExternalField ef) -> Some ef | Some (SzNullTerminated _) -> None sizeReference r tasPositions curState parents t a.minSize.acn a.maxSize.acn visibleParameters rp (AcnDepSizeDeterminant (a.minSize, a.maxSize, a.acnProperties)) | SequenceOf seqOf -> - let rp = - match seqOf.acnProperties.sizeProp with + let rp = + match seqOf.acnProperties.sizeProp with | None -> None | Some (SzExternalField ef) -> Some ef | Some (SzNullTerminated _) -> None @@ -333,15 +333,15 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p | Sequence seq -> seq.children |> List.choose (fun c -> match c with Asn1Child ac -> Some ac | AcnChild _ -> None) |> - List.fold (fun ns ac -> - let ns1 = + List.fold (fun ns ac -> + let ns1 = match ac.Optionality with - | Some (Optional opt) -> + | Some (Optional opt) -> match opt.acnPresentWhen with | None -> ns | Some (PresenceWhenBool (RelativePath path)) -> let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type with | AcnPrmBoolean _ -> AcnDepPresenceBool | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting BOOLEAN got %s " (p.asn1Type.ToString())))) @@ -349,19 +349,19 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p match c.Type with | AcnBoolean _ -> AcnDepPresenceBool | _ -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting BOOLEAN got %s " (c.Type.AsString)))) - checkRelativePath tasPositions ns (parents@[t]) ac.Type visibleParameters (RelativePath path) checkParameter checkAcnType - | Some (PresenceWhenBoolExpression exp) -> + checkRelativePath tasPositions ns (parents@[t]) ac.Type visibleParameters (RelativePath path) checkParameter checkAcnType + | Some (PresenceWhenBoolExpression exp) -> let rec getChildResult (seq:Sequence) (RelativePath lp) = match lp with | [] -> raise(BugErrorException "empty relative path") | x1::xs -> match seq.children |> Seq.tryFind(fun c -> c.Name = x1) with - | None -> + | None -> ValResultError(x1.Location, (sprintf "Invalid reference '%s'" (lp |> Seq.StrJoin "."))) - | Some ch -> + | Some ch -> match ch with | AcnChild ch -> ValResultError(x1.Location, (sprintf "Invalid reference '%s'. Expecting an ASN.1 child" (lp |> Seq.StrJoin "."))) - | Asn1Child ch -> + | Asn1Child ch -> match ch.Optionality with | None -> match ch.Type.ActualType.Kind with @@ -371,20 +371,20 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p | Sequence s when xs.Length > 1 -> getChildResult s (RelativePath xs) | _ -> ValResultError(x1.Location, (sprintf "Invalid reference '%s'" (lp |> Seq.StrJoin "."))) | Some _ -> ValResultError(x1.Location, (sprintf "Optional component '%s' cannot be used in ACN present-when expressions" (lp |> Seq.StrJoin "."))) - + let valResult = AcnGenericTypes.validateAcnExpression (fun lf -> getChildResult seq lf) exp match valResult with | ValResultOK expType -> ns | ValResultError (l,errMsg) -> raise(SemanticError(l, errMsg)) | _ -> ns - checkType r tasPositions (parents@[t]) (curentPath@[SEQ_CHILD ac.Name.Value]) ac.Type ns1 + checkType r tasPositions (parents@[t]) (curentPath@[SEQ_CHILD (ac.Name.Value, ac.Optionality.IsSome)]) ac.Type ns1 ) curState | Choice ch -> - let ns0 = checkChoicePresentWhen r tasPositions curState (parents) t ch visibleParameters + let ns0 = checkChoicePresentWhen r tasPositions curState (parents) t ch visibleParameters let ns1 = choiceEnumReference r tasPositions ns0 (parents) t ch visibleParameters ch.acnProperties.enumDeterminant ch.children|> - List.fold (fun ns ac -> checkType r tasPositions (parents@[t]) (curentPath@[SEQ_CHILD ac.Name.Value]) ac.Type ns ) ns1 - | ReferenceType ref -> + List.fold (fun ns ac -> checkType r tasPositions (parents@[t]) (curentPath@[SEQ_CHILD (ac.Name.Value, ac.Optionality.IsSome)]) ac.Type ns ) ns1 + | ReferenceType ref -> let dummy = ref.tasName let aaa = t.id.AsString @@ -392,18 +392,18 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p match ref.encodingOptions with | None -> curState | Some props -> - - let rp = + + let rp = match props.acnEncodingClass with - | SZ_EC_FIXED_SIZE + | SZ_EC_FIXED_SIZE | SZ_EC_LENGTH_EMBEDDED _ -> None | SZ_EC_ExternalField ef -> Some ef | SZ_EC_TerminationPattern _ -> None - sizeReference r tasPositions curState parents t props.minSize.acn props.maxSize.acn visibleParameters rp (AcnDepSizeDeterminant_bit_oct_str_containt ref) + sizeReference r tasPositions curState parents t props.minSize.acn props.maxSize.acn visibleParameters rp (AcnDepSizeDeterminant_bit_oct_str_contain ref) let checkArgument (curState:AcnInsertedFieldDependencies) ((RelativePath path : RelativePath), (prm:AcnParameter)) = let loc = path.Head.Location - let checkParameter (p:AcnParameter) = + let checkParameter (p:AcnParameter) = match p.asn1Type = prm.asn1Type with | true -> AcnDepRefTypeArgument prm | false -> raise(SemanticError(loc, (sprintf "Invalid argument type. Expecting %s got %s " (prm.asn1Type.ToString()) (p.asn1Type.ToString())))) @@ -423,7 +423,7 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p match ref.acnArguments.Length = ref.resolvedType.acnParameters.Length with | true -> () - | false -> + | false -> let errMgs = sprintf "Expecting %d ACN arguments, provide %d" ref.resolvedType.acnParameters.Length ref.acnArguments.Length raise(SemanticError(acnLoc, errMgs)) let ziped = List.zip ref.acnArguments ref.resolvedType.acnParameters @@ -432,36 +432,36 @@ let rec private checkType (r:AstRoot) (tasPositions:Map) (p let checkAst (r:AstRoot) = - let rec GetReferences (t:Asn1Type) : ReferenceToType list = + let rec GetReferences (t:Asn1Type) : ReferenceToType list = seq { yield t.id match t.ActualType.Kind with | SequenceOf(conType) -> yield! GetReferences conType.child | Sequence seq -> - for ch in seq.children do + for ch in seq.children do match ch with | Asn1Child a -> yield! GetReferences a.Type | AcnChild a -> yield a.id - - | Choice(ch)-> - for ch in ch.children do + + | Choice(ch)-> + for ch in ch.children do yield! GetReferences ch.Type - |_ -> () + |_ -> () } |> Seq.toList - let allTasses = + let allTasses = r.Files |> List.collect (fun f -> f.Modules) |> List.map (fun m -> m.TypeAssignments |> List.map(fun tas -> (m,tas)) ) |> List.collect id - let positions = allTasses + let positions = allTasses let emptyState = {AcnInsertedFieldDependencies.acnDependencies=[]} - let result = + let result = allTasses |> - List.fold (fun ns (m,tas) -> + List.fold (fun ns (m,tas) -> let tasPositions = GetReferences tas.Type |> List.mapi(fun i ref -> (ref,i)) |> Map.ofList checkType r tasPositions [] [MD m.Name.Value; TA tas.Name.Value] tas.Type ns) emptyState diff --git a/FrontEndAst/CloneTree.fs b/FrontEndAst/CloneTree.fs index 27fdf206a..5c1bc8529 100644 --- a/FrontEndAst/CloneTree.fs +++ b/FrontEndAst/CloneTree.fs @@ -17,12 +17,12 @@ open Asn1Ast let rec foldMap func state lst = match lst with | [] -> [],state - | h::tail -> + | h::tail -> let procItem, newState = func state h let restList, finalState = tail |> foldMap func newState procItem::restList, finalState *) -let foldMap = RemoveParamterizedTypes.foldMap +let foldMap = RemoveParameterizedTypes.foldMap type Constructors<'state> = { createFile : AstRoot-> Asn1File -> Constructors<'state> -> 'state -> Asn1File*'state @@ -40,17 +40,17 @@ and CloneAsn1File (old:AstRoot) (f:Asn1File) cons state = let newMods, newState = f.Modules |> foldMap (fun s m-> cons.createModule old m cons s) state { f with Modules = newMods}, newState -let CloneModule (oldRoot:AstRoot) (old:Asn1Module) cons state = +let CloneModule (oldRoot:AstRoot) (old:Asn1Module) cons state = let newTas, s0 = old.TypeAssignments |> foldMap (fun s t -> cons.cloneTypeAssignment t old cons s) state let newVas, s1 = old.ValueAssignments |> foldMap (fun s v -> cons.cloneValueAssignment v old cons s) s0 { Asn1Module.Name = old.Name; TypeAssignments = newTas ValueAssignments = newVas - Imports = old.Imports + Imports = old.Imports Exports = old.Exports Comments = old.Comments - postion = old.postion + position = old.position }, s1 @@ -71,7 +71,7 @@ let CloneValueAssignment (old:ValueAssignment) (m:Asn1Module) cons state= { ValueAssignment.Name = old.Name Type = newType - Value = old.Value + Value = old.Value c_name = old.c_name scala_name = old.scala_name ada_name = old.ada_name @@ -81,19 +81,19 @@ let CloneType (old:Asn1Type) m key cons state = let CloneChild s (ch:ChildInfo) = let t,ns = cons.cloneType ch.Type m (key@[ch.Name.Value]) cons s {ch with Type = t},ns - let newKind, newState = + let newKind, newState = match old.Kind with - | Sequence(children) -> + | Sequence(children) -> let newChildren, finalState = children |> foldMap CloneChild state Sequence(newChildren), finalState - | Choice(children) -> + | Choice(children) -> let newChildren, finalState = children |> foldMap CloneChild state Choice(newChildren), finalState - | SequenceOf(child) -> + | SequenceOf(child) -> let nch,ns = cons.cloneType child m (key@["#"]) cons state SequenceOf(nch),ns | _ -> old.Kind, state - + { Kind = newKind Constraints = old.Constraints @@ -105,7 +105,7 @@ let CloneType (old:Asn1Type) m key cons state = }, newState - + let defaultConstructors = { createFile = CloneAsn1File createModule = CloneModule diff --git a/FrontEndAst/ConstraintsMapping.fs b/FrontEndAst/ConstraintsMapping.fs index ed68b8287..9beed90aa 100644 --- a/FrontEndAst/ConstraintsMapping.fs +++ b/FrontEndAst/ConstraintsMapping.fs @@ -5,44 +5,44 @@ open FsUtils open Asn1AcnAst -let rec getBaseValue (v: Asn1Value) = +let rec getBaseValue (v: Asn1Value) = match v.kind with | RefValue (_, rv) -> getBaseValue rv | _ -> v -let foldBConstraint - singleValueContraintFunc - rangeContraintFunc - rangeContraint_val_MAXFunc - rangeContraint_MIN_valFunc - sizeContraintFunc - alphabetContraintFunc - unionConstraintFunc +let foldBConstraint + singleValueConstraintFunc + rangeConstraintFunc + rangeConstraint_val_MAXFunc + rangeConstraint_MIN_valFunc + sizeConstraintFunc + alphabetConstraintFunc + unionConstraintFunc intersectionConstraintFunc - allExceptConstraintFunc - exceptConstraintFunc - rootConstraintFunc - rootConstraint2Func - withComponentConstraintFunc - withComponentsConstraintFunc + allExceptConstraintFunc + exceptConstraintFunc + rootConstraintFunc + rootConstraint2Func + withComponentConstraintFunc + withComponentsConstraintFunc (c:Asn1Ast.Asn1Constraint) = match c with - | Asn1Ast.SingleValueContraint (s, rv) -> singleValueContraintFunc s rv - | Asn1Ast.RangeContraint (s, rv1,rv2,b1,b2) -> rangeContraintFunc s rv1 rv2 b1 b2 - | Asn1Ast.RangeContraint_val_MAX (s, rv,b) -> rangeContraint_val_MAXFunc s rv b - | Asn1Ast.RangeContraint_MIN_val (s, rv,b) -> rangeContraint_MIN_valFunc s rv b - | Asn1Ast.SizeContraint (s, c) -> sizeContraintFunc s c - | Asn1Ast.AlphabetContraint (s, c) -> alphabetContraintFunc s c - | Asn1Ast.UnionConstraint (s, c1,c2,b) -> unionConstraintFunc s c1 c2 b - | Asn1Ast.IntersectionConstraint (s, c1,c2) -> intersectionConstraintFunc s c1 c2 - | Asn1Ast.AllExceptConstraint (s, c) -> allExceptConstraintFunc s c - | Asn1Ast.ExceptConstraint (s, c1,c2) -> exceptConstraintFunc s c1 c2 - | Asn1Ast.RootConstraint (s, c1) -> rootConstraintFunc s c1 - | Asn1Ast.RootConstraint2 (s, c1,c2) -> rootConstraint2Func s c1 c2 - | Asn1Ast.RangeContraint_MIN_MAX _ -> raise(BugErrorException "Unexpected constraint type") - | Asn1Ast.TypeInclusionConstraint _ -> raise(BugErrorException "Unexpected constraint type") + | Asn1Ast.SingleValueConstraint (s, rv) -> singleValueConstraintFunc s rv + | Asn1Ast.RangeConstraint (s, rv1,rv2,b1,b2) -> rangeConstraintFunc s rv1 rv2 b1 b2 + | Asn1Ast.RangeConstraint_val_MAX (s, rv,b) -> rangeConstraint_val_MAXFunc s rv b + | Asn1Ast.RangeConstraint_MIN_val (s, rv,b) -> rangeConstraint_MIN_valFunc s rv b + | Asn1Ast.SizeConstraint (s, c) -> sizeConstraintFunc s c + | Asn1Ast.AlphabetConstraint (s, c) -> alphabetConstraintFunc s c + | Asn1Ast.UnionConstraint (s, c1,c2,b) -> unionConstraintFunc s c1 c2 b + | Asn1Ast.IntersectionConstraint (s, c1,c2) -> intersectionConstraintFunc s c1 c2 + | Asn1Ast.AllExceptConstraint (s, c) -> allExceptConstraintFunc s c + | Asn1Ast.ExceptConstraint (s, c1,c2) -> exceptConstraintFunc s c1 c2 + | Asn1Ast.RootConstraint (s, c1) -> rootConstraintFunc s c1 + | Asn1Ast.RootConstraint2 (s, c1,c2) -> rootConstraint2Func s c1 c2 + | Asn1Ast.RangeConstraint_MIN_MAX -> raise(BugErrorException "Unexpected constraint type") + | Asn1Ast.TypeInclusionConstraint _ -> raise(BugErrorException "Unexpected constraint type") | Asn1Ast.WithComponentConstraint (s, c,l) -> withComponentConstraintFunc s c l //raise(BugErrorException "Unexpected constraint type") | Asn1Ast.WithComponentsConstraint (s, ncs) -> withComponentsConstraintFunc s ncs //raise(BugErrorException "Unexpected constraint type") @@ -62,7 +62,7 @@ let private getValueAsDouble (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast | _ -> raise(BugErrorException "Value is not of expected type") let private posIntValGetter (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = - let sizeIntegerType = + let sizeIntegerType = { Asn1Ast.Asn1Type.Kind = Asn1Ast.Integer Asn1Ast.Asn1Type.Constraints = [] @@ -79,7 +79,7 @@ let private posIntValGetter (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = | _ -> raise(SemanticError(v.Location, "Value is not of expected type")) let private charGetter (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = - let charType = + let charType = { Asn1Ast.Asn1Type.Kind = Asn1Ast.IA5String Asn1Ast.Asn1Type.Constraints = [] @@ -95,7 +95,7 @@ let private charGetter (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = | _ -> raise(SemanticError (v.Location, "Expecting a string with just one character")) let private strGetter (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = - let charType = + let charType = { Asn1Ast.Asn1Type.Kind = Asn1Ast.IA5String Asn1Ast.Asn1Type.Constraints = [] @@ -119,7 +119,7 @@ let private strValueGetter (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast.A let private octGetter (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast.Asn1Value) = let newValue = ValuesMapping.mapValue r t v match (getBaseValue newValue).kind with - |OctetStringValue vl -> (vl, (v.id, v.Location)) + |OctetStringValue vl -> (vl, (v.id, v.Location)) | _ -> raise(BugErrorException "Value is not of expected type") let private bitGetter (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast.Asn1Value) = @@ -173,147 +173,147 @@ let private chValueGetter (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast.As let rec private getRecursiveTypeConstraint valueGetter (c:Asn1Ast.Asn1Constraint) = foldBConstraint - (fun s rv -> SingleValueConstraint (s, valueGetter rv )) + (fun s rv -> SingleValueConstraint (s, valueGetter rv )) (fun s rv1 rv2 b1 b2 -> raise(BugErrorException "range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "range constraint is not expected here")) - (fun s c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun s c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun s c1 c2 b -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - UnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - IntersectionConstraint (s, c1,c2)) - (fun s c -> - let c = getRecursiveTypeConstraint valueGetter c - AllExceptConstraint (s, c)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - ExceptConstraint (s, c1,c2)) - (fun s c -> - let c = getRecursiveTypeConstraint valueGetter c - RootConstraint (s,c)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeConstraint valueGetter c1 - let c2 = getRecursiveTypeConstraint valueGetter c2 - RootConstraint2 (s, c1,c2)) - (fun s c -> raise(BugErrorException "Unexpected constraint type")) - (fun s c -> raise(BugErrorException "Unexpected constraint type")) + (fun s c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun s c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun s c1 c2 b -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + UnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + IntersectionConstraint (s, c1,c2)) + (fun s c -> + let c = getRecursiveTypeConstraint valueGetter c + AllExceptConstraint (s, c)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + ExceptConstraint (s, c1,c2)) + (fun s c -> + let c = getRecursiveTypeConstraint valueGetter c + RootConstraint (s,c)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeConstraint valueGetter c1 + let c2 = getRecursiveTypeConstraint valueGetter c2 + RootConstraint2 (s, c1,c2)) + (fun s c -> raise(BugErrorException "Unexpected constraint type")) + (fun s c -> raise(BugErrorException "Unexpected constraint type")) c let rec private getRangeTypeConstraint valueGetter valueGetter2 (c:Asn1Ast.Asn1Constraint) = - foldBConstraint - (fun s rv -> RangeSingleValueConstraint (s, valueGetter2 rv )) - (fun s rv1 rv2 b1 b2 -> RangeContraint (s, valueGetter rv1 ,valueGetter rv2, b1,b2) ) - (fun s rv b -> RangeContraint_val_MAX (s, valueGetter rv, b)) - (fun s rv b -> RangeContraint_MIN_val (s, valueGetter rv, b)) - (fun s c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun s c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun s c1 c2 b -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeUnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeIntersectionConstraint (s, c1,c2)) - (fun s c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c - RangeAllExceptConstraint (s,c)) - (fun s c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + foldBConstraint + (fun s rv -> RangeSingleValueConstraint (s, valueGetter2 rv )) + (fun s rv1 rv2 b1 b2 -> RangeConstraint (s, valueGetter rv1 ,valueGetter rv2, b1,b2) ) + (fun s rv b -> RangeConstraint_val_MAX (s, valueGetter rv, b)) + (fun s rv b -> RangeConstraint_MIN_val (s, valueGetter rv, b)) + (fun s c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun s c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun s c1 c2 b -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeUnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeIntersectionConstraint (s, c1,c2)) + (fun s c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c + RangeAllExceptConstraint (s,c)) + (fun s c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 RangeExceptConstraint (s, c1,c2)) - (fun s c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c + (fun s c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c RangeRootConstraint (s,c)) - (fun s c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeRootConstraint2 (s, c1,c2)) - (fun s c -> raise(BugErrorException "Unexpected constraint type")) - (fun s c -> raise(BugErrorException "Unexpected constraint type")) + (fun s c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeRootConstraint2 (s, c1,c2)) + (fun s c -> raise(BugErrorException "Unexpected constraint type")) + (fun s c -> raise(BugErrorException "Unexpected constraint type")) c let rec private getSizeTypeConstraint (r:Asn1Ast.AstRoot) valueGetter (c:Asn1Ast.Asn1Constraint) = - foldBConstraint - (fun s rv -> SizeSingleValueConstraint (s, valueGetter rv)) + foldBConstraint + (fun s rv -> SizeSingleValueConstraint (s, valueGetter rv)) (fun s rv1 rv2 b1 b2 -> raise(BugErrorException "Range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "Range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "Range constraint is not expected here")) - (fun s c -> + (fun s c -> let posIntCon = getRangeTypeConstraint (posIntValGetter r) (posIntValGetter r) c - SizeContraint (s, posIntCon)) - (fun s c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun s c1 c2 b -> + SizeConstraint (s, posIntCon)) + (fun s c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun s c1 c2 b -> let c1 = getSizeTypeConstraint r valueGetter c1 - let c2 = getSizeTypeConstraint r valueGetter c2 - SizeUnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> + let c2 = getSizeTypeConstraint r valueGetter c2 + SizeUnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SizeIntersectionConstraint (s, c1,c2)) - (fun s c -> - let c = getSizeTypeConstraint r valueGetter c - SizeAllExceptConstraint (s, c)) - (fun s c1 c2 -> + SizeIntersectionConstraint (s, c1,c2)) + (fun s c -> + let c = getSizeTypeConstraint r valueGetter c + SizeAllExceptConstraint (s, c)) + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 SizeExceptConstraint (s, c1,c2)) - (fun s c -> - let c = getSizeTypeConstraint r valueGetter c + (fun s c -> + let c = getSizeTypeConstraint r valueGetter c SizeRootConstraint (s, c)) - (fun s c1 c2 -> + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SizeRootConstraint2 (s, c1,c2)) - (fun _ -> raise(BugErrorException "Unexpected constraint type")) - (fun _ -> raise(BugErrorException "Unexpected constraint type")) + SizeRootConstraint2 (s, c1,c2)) + (fun _ -> raise(BugErrorException "Unexpected constraint type")) + (fun _ -> raise(BugErrorException "Unexpected constraint type")) c let rec private getStringTypeConstraint (r:Asn1Ast.AstRoot) valueGetter (c:Asn1Ast.Asn1Constraint) = - foldBConstraint - (fun s rv -> StrSingleValueConstraint (s, valueGetter rv)) + foldBConstraint + (fun s rv -> StrSingleValueConstraint (s, valueGetter rv)) (fun s rv1 rv2 b1 b2 -> raise(SemanticError(rv1.Location, "Range constraint is not expected here in string types"))) (fun s rv b -> raise(SemanticError(rv.Location, "Range constraint is not expected here in string types"))) (fun s rv b -> raise(SemanticError(rv.Location, "Range constraint is not expected here in string types"))) - (fun s c -> + (fun s c -> let posIntCon = getRangeTypeConstraint (posIntValGetter r) (posIntValGetter r) c - StrSizeContraint (s, posIntCon)) - (fun s c -> + StrSizeConstraint (s, posIntCon)) + (fun s c -> let charCons = getRangeTypeConstraint (charGetter r) (strGetter r) c - AlphabetContraint (s, charCons)) - (fun s c1 c2 b -> + AlphabetConstraint (s, charCons)) + (fun s c1 c2 b -> let c1 = getStringTypeConstraint r valueGetter c1 let c2 = getStringTypeConstraint r valueGetter c2 - StrUnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> + StrUnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> let c1 = getStringTypeConstraint r valueGetter c1 let c2 = getStringTypeConstraint r valueGetter c2 - StrIntersectionConstraint (s, c1,c2)) - (fun s c -> + StrIntersectionConstraint (s, c1,c2)) + (fun s c -> let c = getStringTypeConstraint r valueGetter c - StrAllExceptConstraint (s, c)) - (fun s c1 c2 -> + StrAllExceptConstraint (s, c)) + (fun s c1 c2 -> let c1 = getStringTypeConstraint r valueGetter c1 let c2 = getStringTypeConstraint r valueGetter c2 StrExceptConstraint (s, c1,c2)) - (fun s c -> + (fun s c -> let c = getStringTypeConstraint r valueGetter c StrRootConstraint (s, c)) - (fun s c1 c2 -> + (fun s c1 c2 -> let c1 = getStringTypeConstraint r valueGetter c1 let c2 = getStringTypeConstraint r valueGetter c2 - StrRootConstraint2 (s, c1,c2)) - (fun _ -> raise(BugErrorException "Unexpected constraint type")) - (fun _ -> raise(BugErrorException "Unexpected constraint type")) + StrRootConstraint2 (s, c1,c2)) + (fun _ -> raise(BugErrorException "Unexpected constraint type")) + (fun _ -> raise(BugErrorException "Unexpected constraint type")) c @@ -351,39 +351,39 @@ let rec getAnyConstraint (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (c:Asn1Ast.Asn and getSequenceOfConstraint (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (child : Asn1Ast.Asn1Type) = let rec getSizeTypeConstraint (r:Asn1Ast.AstRoot) valueGetter (c:Asn1Ast.Asn1Constraint) = - foldBConstraint - (fun s rv -> SeqOfSizeSingleValueConstraint (s, valueGetter rv)) + foldBConstraint + (fun s rv -> SeqOfSizeSingleValueConstraint (s, valueGetter rv)) (fun s rv1 rv2 b1 b2 -> raise(BugErrorException "Range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "Range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "Range constraint is not expected here")) - (fun s c -> + (fun s c -> let posIntCon = getRangeTypeConstraint (posIntValGetter r) (posIntValGetter r) c - SeqOfSizeContraint (s,posIntCon)) - (fun s c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun s c1 c2 b -> + SeqOfSizeConstraint (s,posIntCon)) + (fun s c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun s c1 c2 b -> let c1 = getSizeTypeConstraint r valueGetter c1 - let c2 = getSizeTypeConstraint r valueGetter c2 - SeqOfSizeUnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> + let c2 = getSizeTypeConstraint r valueGetter c2 + SeqOfSizeUnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SeqOfSizeIntersectionConstraint (s, c1,c2)) - (fun s c -> - let c = getSizeTypeConstraint r valueGetter c - SeqOfSizeAllExceptConstraint (s, c)) - (fun s c1 c2 -> + SeqOfSizeIntersectionConstraint (s, c1,c2)) + (fun s c -> + let c = getSizeTypeConstraint r valueGetter c + SeqOfSizeAllExceptConstraint (s, c)) + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 SeqOfSizeExceptConstraint (s, c1,c2)) - (fun s c -> - let c = getSizeTypeConstraint r valueGetter c + (fun s c -> + let c = getSizeTypeConstraint r valueGetter c SeqOfSizeRootConstraint (s, c)) - (fun s c1 c2 -> + (fun s c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SeqOfSizeRootConstraint2 (s, c1,c2)) - (fun s c l -> SeqOfSeqWithComponentConstraint(s, (getAnyConstraint r child c),l) ) - (fun _ -> raise(BugErrorException "Unexpected constraint type")) + SeqOfSizeRootConstraint2 (s, c1,c2)) + (fun s c l -> SeqOfSeqWithComponentConstraint(s, (getAnyConstraint r child c),l) ) + (fun _ -> raise(BugErrorException "Unexpected constraint type")) c getSizeTypeConstraint r (seqOfValueGetter r t) @@ -392,43 +392,43 @@ and getSequenceOfConstraint (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (child : A and getRecursiveTypeSeqOrConstraint (r:Asn1Ast.AstRoot) valueGetter (children:Asn1Ast.ChildInfo list) (c:Asn1Ast.Asn1Constraint) = foldBConstraint - (fun s rv -> SeqOrChSingleValueConstraint (s, valueGetter rv )) + (fun s rv -> SeqOrChSingleValueConstraint (s, valueGetter rv )) (fun s rv1 rv2 b1 b2 -> raise(BugErrorException "range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "range constraint is not expected here")) (fun s rv b -> raise(BugErrorException "range constraint is not expected here")) - (fun s c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun s c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun s c1 c2 b -> - let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 - let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 - SeqOrChUnionConstraint (s, c1,c2,b)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 - let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 - SeqOrChIntersectionConstraint (s, c1,c2)) - (fun s c -> - let c = getRecursiveTypeSeqOrConstraint r valueGetter children c - SeqOrChAllExceptConstraint (s, c)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 - let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 - SeqOrChExceptConstraint (s, c1,c2)) - (fun s c -> - let c = getRecursiveTypeSeqOrConstraint r valueGetter children c - SeqOrChRootConstraint (s, c)) - (fun s c1 c2 -> - let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 - let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 - SeqOrChRootConstraint2 (s, c1,c2)) - (fun s c -> raise(BugErrorException "Unexpected constraint type")) - (fun s ncs -> - let newItems = - ncs |> - List.map(fun nc -> + (fun s c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun s c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun s c1 c2 b -> + let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 + let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 + SeqOrChUnionConstraint (s, c1,c2,b)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 + let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 + SeqOrChIntersectionConstraint (s, c1,c2)) + (fun s c -> + let c = getRecursiveTypeSeqOrConstraint r valueGetter children c + SeqOrChAllExceptConstraint (s, c)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 + let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 + SeqOrChExceptConstraint (s, c1,c2)) + (fun s c -> + let c = getRecursiveTypeSeqOrConstraint r valueGetter children c + SeqOrChRootConstraint (s, c)) + (fun s c1 c2 -> + let c1 = getRecursiveTypeSeqOrConstraint r valueGetter children c1 + let c2 = getRecursiveTypeSeqOrConstraint r valueGetter children c2 + SeqOrChRootConstraint2 (s, c1,c2)) + (fun s c -> raise(BugErrorException "Unexpected constraint type")) + (fun s ncs -> + let newItems = + ncs |> + List.map(fun nc -> let ch = children |> Seq.find(fun x -> x.Name.Value = nc.Name.Value) - let newCon = nc.Contraint |> Option.map (getAnyConstraint r ch.Type) - {NamedConstraint.Name = nc.Name; Mark = nc.Mark; Contraint = newCon}) - SeqOrChWithComponentsConstraint (s, newItems) ) + let newCon = nc.Constraint |> Option.map (getAnyConstraint r ch.Type) + {NamedConstraint.Name = nc.Name; Mark = nc.Mark; Constraint = newCon}) + SeqOrChWithComponentsConstraint (s, newItems) ) c and getSeqConstraint (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (children:Asn1Ast.ChildInfo list) = diff --git a/FrontEndAst/CreateAsn1AstFromAntlrTree.fs b/FrontEndAst/CreateAsn1AstFromAntlrTree.fs index f86266a6c..3452186a3 100644 --- a/FrontEndAst/CreateAsn1AstFromAntlrTree.fs +++ b/FrontEndAst/CreateAsn1AstFromAntlrTree.fs @@ -28,8 +28,8 @@ let TimeClassMap = ("Basic=Date Date=YMD Year=Basic" , Asn1Date ) ("Basic=Date-Time Date=YMD Year=Basic Time=HMS Local-or-UTC=L" , Asn1Date_LocalTime 0 ) ("Basic=Date-Time Date=YMD Year=Basic Time=HMS Local-or-UTC=Z" , Asn1Date_UtcTime 0 ) - ("Basic=Date-Time Date=YMD Year=Basic Time=HMS Local-or-UTC=LD" , Asn1Date_LocalTimeWithTimeZone 0 ) ] |> - List.collect (fun (str, cl) -> + ("Basic=Date-Time Date=YMD Year=Basic Time=HMS Local-or-UTC=LD" , Asn1Date_LocalTimeWithTimeZone 0 ) ] |> + List.collect (fun (str, cl) -> let arr = str.Split ' ' let combs = combinations arr |> List.map (fun l -> l.StrJoin "") |> List.map (fun s -> (s,cl)) combs) |> Map.ofList @@ -37,9 +37,9 @@ let TimeClassMap = -let CreateRefTypeContent (tree:ITree) = +let CreateRefTypeContent (tree:ITree) = match getTreeChildren(tree) |> List.filter(fun x -> x.Type<> asn1Parser.ACTUAL_PARAM_LIST) with - | refTypeName::[] -> + | refTypeName::[] -> let mdTree = tree.GetAncestor(asn1Parser.MODULE_DEF) let mdName = mdTree.GetChild(0).TextL let imports = mdTree.GetChildrenByType(asn1Parser.IMPORTS_FROM_MODULE) @@ -47,9 +47,9 @@ let CreateRefTypeContent (tree:ITree) = match importedFromModule with |Some(imp) -> Ok ( imp.GetChild(0).TextL, refTypeName.TextL) |None -> Ok ( tree.GetAncestor(asn1Parser.MODULE_DEF).GetChild(0).TextL, refTypeName.TextL) - + | modName::refTypeName::[] -> Ok ( modName.TextL, refTypeName.TextL) - | _ -> Error (Bug_Error("Bug in CrateType(refType)")) + | _ -> Error (Bug_Error("Bug in CrateType(refType)")) type RegisterObjIDKeyword = @@ -78,38 +78,38 @@ let rec isRegisterObjIDKeyword (curLevelKeywords: RegisterObjIDKeyword list) (pa | [] -> Error(Bug_Error "expecting non empty list") | x1::xs -> let curLevelKeyword = - curLevelKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) x1) ) + curLevelKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) x1) ) match xs with | [] -> Ok (curLevelKeyword|> Option.map(fun (LEAF(_,nVal, _)) -> nVal)) - | _ -> + | _ -> match curLevelKeyword with | None -> Ok None | Some (LEAF(_,_,nextLevelKeywords)) -> isRegisterObjIDKeyword nextLevelKeywords xs let rec isRegisterObjIDKeyword2 (parentKeyword: RegisterObjIDKeyword option) (curName:string) = match parentKeyword with - | None -> - registeredObjectIdentifierKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) curName) ) + | None -> + registeredObjectIdentifierKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) curName) ) | Some (LEAF(_,_,curLevelKeywords)) -> - curLevelKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) curName) ) + curLevelKeywords |> List.tryFind(fun (LEAF(names,nVal, _)) -> names |> Seq.exists ((=) curName) ) let createDefaultConstraintsForEnumeratedTypes (tree:ITree) (namedItems:NamedItem list) = let mdTree = tree.GetAncestor(asn1Parser.MODULE_DEF) let mdName = mdTree.GetChild(0).TextL let createSingleValueConstraintFromNamedItem (ni:NamedItem) = let v = {Asn1Value.Kind = (RefValue ({StringLoc.Value = mdName.Value; Location=ni.Name.Location}, ni.Name)); Location = ni.Name.Location; moduleName=mdName.Value } - SingleValueContraint (ni.Name.Value, v) + SingleValueConstraint (ni.Name.Value, v) match namedItems with | x::xs -> let initialCon = createSingleValueConstraintFromNamedItem x let asn1Cons = namedItems |> List.map(fun z -> z.Name.Value) |> Seq.StrJoin " | " - let ret = - xs |> List.fold(fun accConst ni -> + let ret = + xs |> List.fold(fun accConst ni -> let curCon = createSingleValueConstraintFromNamedItem ni UnionConstraint (asn1Cons, accConst, curCon, true) ) initialCon Ok ret - | [] -> + | [] -> Error (Semantic_Error (tree.Location, "Enumerated type has no enumerants")) @@ -119,7 +119,7 @@ let singleReference2DoubleReference (tree:ITree) = let modName = modl.GetChild(0).TextL let imports = modl.GetChildrenByType(asn1Parser.IMPORTS_FROM_MODULE) let importedFromModule = imports |> List.tryFind(fun imp-> imp.GetChildrenByType(asn1Parser.LID) |> Seq.exists(fun impTypeName -> impTypeName.Text = strVal.Value )) - let valToReturn = + let valToReturn = match importedFromModule with |Some(imp) -> ( imp.GetChild(0).TextL, strVal) |None -> ( modName, strVal) @@ -130,7 +130,7 @@ let singleReference2DoubleReference (tree:ITree) = let rec foldResult f total ns = match ns with | [] -> Ok (total) - | n :: tail -> + | n :: tail -> result { let! ns = f total n //let! retVal = foldResult f ns tail @@ -145,27 +145,27 @@ let rec foldResult f total ns = let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Result= result { - let GetActualString (str:string) = + let GetActualString (str:string) = let strVal = str.Substring(1) strVal.Remove(strVal.Length-2).Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "") let mdTree = tree.GetAncestor(asn1Parser.MODULE_DEF) let mdName = mdTree.GetChild(0).Text - let! asn1ValueKind = + let! asn1ValueKind = match tree.Type with | asn1Parser.INT -> Ok (IntegerValue(tree.BigIntL integerSizeInBytes)) | asn1Parser.FloatingPointLiteral -> Ok (RealValue(tree.DoubleL)) | asn1Parser.NUMERIC_VALUE2 -> result { let mantissa = double (tree.GetChild(0).BigInt integerSizeInBytes) - let! bas = + let! bas = result { - if tree.GetChild(1).BigInt integerSizeInBytes = 2I then + if tree.GetChild(1).BigInt integerSizeInBytes = 2I then return 2.0 - elif tree.GetChild(1).BigInt integerSizeInBytes = 10I then + elif tree.GetChild(1).BigInt integerSizeInBytes = 10I then return 10.0 - else + else let! e = Error (Semantic_Error(tree.GetChild(1).Location, "Only 2 or 10 values are allowed")) return e } @@ -177,7 +177,7 @@ let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Res | asn1Parser.MINUS_INFINITY -> Ok (RealValue(tree.GetValueL Double.NegativeInfinity)) | asn1Parser.TRUE -> Ok (BooleanValue(tree.GetValueL true)) | asn1Parser.FALSE -> Ok (BooleanValue(tree.GetValueL false)) - | asn1Parser.StringLiteral -> + | asn1Parser.StringLiteral -> let text = tree.Text.Substring(1, tree.Text.Length-2) Ok (StringValue({ StringLoc.Value = text; Location = tree.Location})) | asn1Parser.NULL -> Ok NullValue @@ -186,19 +186,19 @@ let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Res | asn1Parser.OBJECT_ID_VALUE -> let handleObjectIdComponent (rootComponent:bool) (parentKeyword: RegisterObjIDKeyword option) (tree:ITree ) = match tree.Type with - | asn1Parser.OBJ_LST_ITEM2 -> - let nVal = (tree.GetChild(0).BigIntL integerSizeInBytes).Value + | asn1Parser.OBJ_LST_ITEM2 -> + let nVal = (tree.GetChild(0).BigIntL integerSizeInBytes).Value match nVal >= 0I with | true -> Ok (ObjInteger (tree.GetChild(0).BigIntL integerSizeInBytes ) , None) | false -> Error (Semantic_Error(tree.GetChild(0).Location, "Negative values are not permitted in OJECT-IDENTIFIER")) - | asn1Parser.OBJ_LST_ITEM1 -> + | asn1Parser.OBJ_LST_ITEM1 -> let name = tree.GetChild(0).TextL match tree.ChildCount with | 2 -> let secChild = tree.GetChild(1) match secChild.Type with - | asn1Parser.INT -> + | asn1Parser.INT -> match (secChild.BigIntL integerSizeInBytes ).Value >= 0I with | true -> Ok (ObjNamedIntValue (name, secChild.BigIntL integerSizeInBytes ), None) | false -> Error (Semantic_Error(secChild.Location, "Negative values are not permitted in OJECT-IDENTIFIER")) @@ -209,7 +209,7 @@ let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Res | _ -> Error (Bug_Error("Bug in CreateValue asn1Parser.OBJECT_ID_VALUE 1")) | _ -> Error (Bug_Error("Bug in CreateValue asn1Parser.OBJECT_ID_VALUE 2")) | 1 -> - let regKeyWord = + let regKeyWord = match rootComponent with | true -> isRegisterObjIDKeyword2 parentKeyword name.Value | false -> @@ -225,41 +225,41 @@ let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Res | _ -> Error (Bug_Error("Bug in CreateValue asn1Parser.OBJECT_ID_VALUE 4")) result { - let! _,components,_ = - tree.Children |> - foldResult (fun (rootComponent, curComponents, parentKeyword) curTree -> + let! _,components,_ = + tree.Children |> + foldResult (fun (rootComponent, curComponents, parentKeyword) curTree -> result { let! compent, regKeyword = handleObjectIdComponent rootComponent parentKeyword curTree - return (false, curComponents@[compent], regKeyword) - }) (true, [],None) + return (false, curComponents@[compent], regKeyword) + }) (true, [],None) return (ObjOrRelObjIdValue components) } - | asn1Parser.VALUE_LIST -> + | asn1Parser.VALUE_LIST -> result { let! childVals = getTreeChildren(tree)|> List.traverseResultM (fun x -> CreateValue integerSizeInBytes astRoot (x) ) return (SeqOfValue(childVals)) } - | asn1Parser.NAMED_VALUE_LIST -> + | asn1Parser.NAMED_VALUE_LIST -> let HandleChild (childTree:ITree) = result { let chName = childTree.GetChild(0).TextL - let! value = CreateValue integerSizeInBytes astRoot (childTree.GetChild(1)) + let! value = CreateValue integerSizeInBytes astRoot (childTree.GetChild(1)) return (chName, value) } result { let! childVals = getTreeChildren(tree)|> List.traverseResultM HandleChild return SeqValue(childVals) } - | asn1Parser.CHOICE_VALUE -> + | asn1Parser.CHOICE_VALUE -> result { let chName = tree.GetChild(0).TextL - let! value = CreateValue integerSizeInBytes astRoot (tree.GetChild(1)) + let! value = CreateValue integerSizeInBytes astRoot (tree.GetChild(1)) return (ChValue(chName, value)) } - | asn1Parser.OctectStringLiteral -> + | asn1Parser.OctectStringLiteral -> let strVal = GetActualString(tree.Text) - let chars = strVal.ToCharArray() - let bytes = getAsTupples chars '0' |> List.map (fun (x1,x2)-> tree.GetValueL (System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier))) + let chars = strVal.ToCharArray() + let bytes = getAsTupples chars '0' |> List.map (fun (x1,x2)-> tree.GetValueL (System.Byte.Parse(x1.ToString()+x2.ToString(), System.Globalization.NumberStyles.AllowHexSpecifier))) Ok (OctetStringValue(bytes)) | asn1Parser.EMPTY_LIST -> Ok EmptyList | _ -> Error (Bug_Error("Bug in CreateValue " + (sprintf "%d" tree.Type))) @@ -275,111 +275,111 @@ let rec CreateValue integerSizeInBytes (astRoot:list) (tree:ITree ) : Res let rec CreateConstraint (integerSizeInBytes: BigInteger) (astRoot:list) (fileTokens:array) (tree:ITree) : Result= result { - let asn1Str = + let asn1Str = fileTokens.[tree.TokenStartIndex .. tree.TokenStopIndex] |> Seq.map(fun s -> s.Text) |> Seq.StrJoin "" //printfn "%s" asn1Str match tree.Type with - |asn1Parser.UnionMark -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) - let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) + |asn1Parser.UnionMark -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) match c1, c2 with |Some(k1),Some(k2) -> return (Some(UnionConstraint(asn1Str, k1 , k2, false ))) |Some(k1),None -> return None |None, Some(_) -> return None |None, None -> return None - |asn1Parser.IntersectionMark -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) - let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) + |asn1Parser.IntersectionMark -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) match c1, c2 with |Some(k1),Some(k2) -> return (Some(IntersectionConstraint(asn1Str, k1 , k2 ))) |Some(k1),None -> return (Some k1) |None, Some(k2) -> return (Some k2) |None, None -> return None - |asn1Parser.SIZE_EXPR -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + |asn1Parser.SIZE_EXPR -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) match c1 with - |Some(k1) -> return (Some(SizeContraint (asn1Str, k1))) + |Some(k1) -> return (Some(SizeConstraint (asn1Str, k1))) |None -> return None - |asn1Parser.SUBTYPE_EXPR -> + |asn1Parser.SUBTYPE_EXPR -> let! (a,b) = CreateRefTypeContent(tree.GetChild(0)) return (Some(TypeInclusionConstraint(asn1Str,a,b) )) - |asn1Parser.PERMITTED_ALPHABET_EXPR -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + |asn1Parser.PERMITTED_ALPHABET_EXPR -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) match c1 with - |Some(k1) -> return (Some(AlphabetContraint (asn1Str, k1))) + |Some(k1) -> return (Some(AlphabetConstraint (asn1Str, k1))) |None -> return None - |asn1Parser.ALL_EXCEPT -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + |asn1Parser.ALL_EXCEPT -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) match c1 with |Some(k1) -> return (Some(AllExceptConstraint (asn1Str, k1))) - |None -> + |None -> let! e = Error (Semantic_Error(tree.Location, "Invalid constraints definition")) return e - |asn1Parser.EXCEPT -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) - let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) + |asn1Parser.EXCEPT -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) match c1, c2 with |Some(k1),Some(k2) -> return (Some(ExceptConstraint(asn1Str, k1 , k2 ))) - |Some(k1),None -> + |Some(k1),None -> let! e = Error(Semantic_Error(tree.Location, "Invalid constraints definition")) return e |None, Some(k2) -> return (Some(AllExceptConstraint (asn1Str, k2))) - |None, None -> + |None, None -> let! e = Error(Semantic_Error(tree.Location, "Invalid constraints definition")) return e |asn1Parser.EXT_MARK -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) - if tree.ChildCount = 1 then + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + if tree.ChildCount = 1 then match c1 with | Some k1 -> return (Some( RootConstraint(asn1Str, k1))) | None -> return None - else - let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) + else + let! c2 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(1)) match c1, c2 with |Some(k1),Some(k2) -> return (Some(RootConstraint2(asn1Str, k1 , k2 ))) |Some(k1),None -> return (Some( RootConstraint(asn1Str, k1))) - |None, Some(k2) -> + |None, Some(k2) -> let! e = Error(Semantic_Error(tree.Location, "Invalid constraints definition")) return e - |None, None -> + |None, None -> let! e = Error(Semantic_Error(tree.Location, "Invalid constraints definition")) return e - |asn1Parser.WITH_COMPONENT_CONSTR -> - let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) + |asn1Parser.WITH_COMPONENT_CONSTR -> + let! c1 = CreateConstraint integerSizeInBytes astRoot fileTokens (tree.GetChild(0)) match c1 with | Some k1 -> return (Some(WithComponentConstraint(asn1Str, k1, tree.Location))) | None -> return None - |asn1Parser.WITH_COMPONENTS_CONSTR -> + |asn1Parser.WITH_COMPONENTS_CONSTR -> let CreateNamedConstraint(tree:ITree) = result { - let mark = getOptionalChildByType(tree, asn1Parser.EXT_MARK) + let mark = getOptionalChildByType(tree, asn1Parser.EXT_MARK) let nm = tree.GetChild(0).TextL - let! contraint = + let! cstrt = match getOptionalChildByType(tree, asn1Parser.INNER_CONSTRAINT) with | None -> Ok None - | Some(con) -> CreateConstraint integerSizeInBytes astRoot fileTokens (con.GetChild(0)) + | Some(con) -> CreateConstraint integerSizeInBytes astRoot fileTokens (con.GetChild(0)) - let! mark = + let! mark = match getOptionalChildByType(tree, asn1Parser.EXT_MARK) with | None -> Ok NoMark - | Some(markNode) -> + | Some(markNode) -> match markNode.GetChild(0).Type with | asn1Parser.PRESENT -> Ok MarkPresent | asn1Parser.ABSENT -> Ok MarkAbsent | asn1Parser.OPTIONAL -> Ok MarkOptional | _ -> Error (Bug_Error("Bug in CreateConstraint.CreateNamedConstraint")) return - { + { NamedConstraint.Name=nm Mark = mark - Contraint = contraint + Constraint = cstrt } } let! cs = tree.GetChildrenByType(asn1Parser.NAME_CONSTRAINT_EXPR) |> List.traverseResultM CreateNamedConstraint return (Some(WithComponentsConstraint (asn1Str, cs))) |asn1Parser.VALUE_RANGE_EXPR -> - + let maxValIncl = getOptionalChildByType(tree, asn1Parser.MAX_VAL_PRESENT) let minValIsIncluded= match getOptionalChildByType(tree, asn1Parser.MIN_VAL_INCLUDED) with | Some _ -> false @@ -387,33 +387,33 @@ let rec CreateConstraint (integerSizeInBytes: BigInteger) (astRoot:list) let maxValIsIncluded = match getOptionalChildByType(tree, asn1Parser.MAX_VAL_INCLUDED) with | Some _ -> false | None -> true - + match maxValIncl with - | None -> + | None -> let! v = CreateValue integerSizeInBytes astRoot (tree.GetChild(0)) - return (Some(SingleValueContraint(asn1Str, v))) - | Some(v) -> + return (Some(SingleValueConstraint(asn1Str, v))) + | Some(v) -> let a = tree.GetChild(0) let b = v.GetChild(0) match a.Type, b.Type with - | asn1Parser.MIN, asn1Parser.MAX -> return None //RangeContraint_MIN_MAX - | asn1Parser.MIN, _ -> + | asn1Parser.MIN, asn1Parser.MAX -> return None //RangeConstraint_MIN_MAX + | asn1Parser.MIN, _ -> let! v = CreateValue integerSizeInBytes astRoot b - return (Some(RangeContraint_MIN_val(asn1Str, v, maxValIsIncluded))) - | _, asn1Parser.MAX -> + return (Some(RangeConstraint_MIN_val(asn1Str, v, maxValIsIncluded))) + | _, asn1Parser.MAX -> let! v = CreateValue integerSizeInBytes astRoot a - return (Some(RangeContraint_val_MAX(asn1Str, v, minValIsIncluded ))) - | _, _ -> + return (Some(RangeConstraint_val_MAX(asn1Str, v, minValIsIncluded ))) + | _, _ -> let! v1 = CreateValue integerSizeInBytes astRoot a let! v2 = CreateValue integerSizeInBytes astRoot b - return (Some(RangeContraint(asn1Str, v1 , v2, minValIsIncluded, maxValIsIncluded ))) - | _ -> + return (Some(RangeConstraint(asn1Str, v1 , v2, minValIsIncluded, maxValIsIncluded ))) + | _ -> return! Error (Bug_Error("Bug in CreateConstraint")) - + } -let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) (acnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result= +let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) (acnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result= let createReferenceType (typeNode:ITree) refEnc : Result = result { @@ -422,11 +422,11 @@ let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) ( match typeNode.GetOptChild asn1Parser.ACTUAL_PARAM_LIST with | None -> Ok [] | Some(argList) -> - argList.Children |> - List.traverseResultM(fun x -> + argList.Children |> + List.traverseResultM(fun x -> result { match x.Type with - | asn1Parser.ACTUAL_TYPE_PARAM -> + | asn1Parser.ACTUAL_TYPE_PARAM -> let argTypeTree = x.GetChild(0) let children = getTreeChildren(argTypeTree) let typeNodes = children |> List.filter(fun x -> (not (ConstraintNodes |> List.exists(fun y -> y=x.Type) ) ) && (x.Type <> asn1Parser.TYPE_TAG) ) @@ -436,17 +436,17 @@ let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) ( let! (md,ts) = CreateRefTypeContent(typeNode) match tasParameters |> Seq.tryFind (fun tp -> match tp with TypeParameter prmName | ValueParameter (_,prmName) -> prmName.Value = ts.Value) with | Some _ -> return (TemplateParameter ts) - | None -> + | None -> let! t = CreateType integerSizeInBytes tasParameters None astRoot (x.GetChild(0)) fileTokens alreadyTakenComments return (ArgType t) - | _ -> + | _ -> let! t = CreateType integerSizeInBytes tasParameters None astRoot (x.GetChild(0)) fileTokens alreadyTakenComments return (ArgType t) - | asn1Parser.ACTUAL_VALUE_PARAM -> + | asn1Parser.ACTUAL_VALUE_PARAM -> let! v = CreateValue integerSizeInBytes astRoot (x.GetChild(0)) - return (ArgValue v ) - | _ -> - let! e = Error (Bug_Error("Bug in CrateType(refType)")) + return (ArgValue v ) + | _ -> + let! e = Error (Bug_Error("Bug in CrateType(refType)")) return e }) @@ -460,68 +460,68 @@ let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) ( let typeNodes = children |> List.filter(fun x -> (not (ConstraintNodes |> List.exists(fun y -> y=x.Type) ) ) && (x.Type <> asn1Parser.TYPE_TAG) ) let typeNode = List.head(typeNodes) - let children_cons = if typeNode.Type=asn1Parser.SEQUENCE_OF_TYPE || typeNode.Type=asn1Parser.SET_OF_TYPE then getTreeChildren(typeNode) + let children_cons = if typeNode.Type=asn1Parser.SEQUENCE_OF_TYPE || typeNode.Type=asn1Parser.SET_OF_TYPE then getTreeChildren(typeNode) else children - let units = + let units = match children_cons |> List.filter(fun x -> x.Type = asn1Parser.UNITS) |> List.map(fun z -> z.Text) with | [] -> None - | x1::_ -> + | x1::_ -> let ret = x1.Replace("--{","").Replace("}--","") Some ret - let contraintNodes = children_cons |> List.filter(fun x -> ConstraintNodes |> List.exists(fun y -> y=x.Type) ) + let constraintNodes = children_cons |> List.filter(fun x -> ConstraintNodes |> List.exists(fun y -> y=x.Type) ) let! asn1Kind = match typeNode.Type with | asn1Parser.INTEGER_TYPE -> Ok Integer | asn1Parser.REAL -> Ok Real | asn1Parser.BOOLEAN -> Ok Boolean - | asn1Parser.CHOICE_TYPE -> + | asn1Parser.CHOICE_TYPE -> result { let! ch = CreateChoiceChild integerSizeInBytes tasParameters acnTypeEncodingSpec astRoot typeNode fileTokens alreadyTakenComments return (Choice ch ) } - | asn1Parser.SET_TYPE - | asn1Parser.SEQUENCE_TYPE -> + | asn1Parser.SET_TYPE + | asn1Parser.SEQUENCE_TYPE -> result { let! ch = CreateSequenceChild integerSizeInBytes tasParameters acnTypeEncodingSpec astRoot typeNode fileTokens alreadyTakenComments return (Sequence ch) } - | asn1Parser.ENUMERATED_TYPE -> + | asn1Parser.ENUMERATED_TYPE -> result { let! items = CreateNamedItems integerSizeInBytes astRoot typeNode fileTokens alreadyTakenComments return (Enumerated items) } - | asn1Parser.BIT_STRING_TYPE -> + | asn1Parser.BIT_STRING_TYPE -> result { let! items = CreateNamedBitList integerSizeInBytes astRoot typeNode fileTokens alreadyTakenComments return (BitString items) } - | asn1Parser.OCTECT_STING -> Ok OctetString + | asn1Parser.OCTET_STRING -> Ok OctetString | asn1Parser.IA5String -> Ok IA5String | asn1Parser.NumericString -> Ok NumericString | asn1Parser.OBJECT_TYPE -> Ok ObjectIdentifier | asn1Parser.RELATIVE_OID -> Ok RelativeObjectIdentifier - | asn1Parser.TIME_TYPE -> + | asn1Parser.TIME_TYPE -> result { let! timeClass = CreateTimeClass astRoot typeNode fileTokens alreadyTakenComments return TimeType timeClass } - | asn1Parser.VisibleString -> + | asn1Parser.VisibleString -> Error (Semantic_Error (tree.Location, "VisibleString is not supported - please use IA5String")) - | asn1Parser.PrintableString -> + | asn1Parser.PrintableString -> Error (Semantic_Error (tree.Location, "PrintableString is not supported - please use IA5String")) | asn1Parser.NULL -> Ok NullType - | asn1Parser.REFERENCED_TYPE + | asn1Parser.REFERENCED_TYPE | asn1Parser.PREFERENCED_TYPE -> createReferenceType typeNode None | asn1Parser.OCT_STR_CONTAINING -> createReferenceType (typeNode.GetChild(0)) (Some ContainedInOctString) | asn1Parser.BIT_STR_CONTAINING -> createReferenceType (typeNode.GetChild(0)) (Some ContainedInBitString) - | asn1Parser.SET_OF_TYPE - | asn1Parser.SEQUENCE_OF_TYPE -> + | asn1Parser.SET_OF_TYPE + | asn1Parser.SEQUENCE_OF_TYPE -> result { - let childAcnEncodingSpec = + let childAcnEncodingSpec = match acnTypeEncodingSpec with | None -> None - | Some sqe -> + | Some sqe -> match sqe.children with | [] -> None | z::_ -> Some z.childEncodingSpec @@ -539,29 +539,29 @@ let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) ( | asn1Parser.GeneralizedTime -> Error (Semantic_Error (tree.Location, "GeneralizedTime type is not supported")) | _ -> Error (Bug_Error("Bug in CreateType")) - let! constraints = + let! constraints = result { - let! userConstraints0 = - contraintNodes |> List.traverseResultM(fun x-> CreateConstraint integerSizeInBytes astRoot fileTokens x ) + let! userConstraints0 = + constraintNodes |> List.traverseResultM(fun x-> CreateConstraint integerSizeInBytes astRoot fileTokens x ) let userConstraints = userConstraints0 |> List.choose(fun x -> x) match asn1Kind with - | Enumerated(itms) -> + | Enumerated(itms) -> match userConstraints with | _::_ -> return userConstraints - | [] -> + | [] -> let! dc = createDefaultConstraintsForEnumeratedTypes tree itms return [dc] | _ -> return userConstraints } - let ret = + let ret = { Asn1Type.Kind = asn1Kind Constraints= constraints Location = tree.Location parameterizedTypeInstance = false - acnInfo = acnTypeEncodingSpec + acnInfo = acnTypeEncodingSpec unitsOfMeasure = units moduleName = mdName } @@ -569,22 +569,22 @@ let rec CreateType integerSizeInBytes (tasParameters : TemplateParameter list) ( } -and CreateChoiceChild integerSizeInBytes (tasParameters : TemplateParameter list) (chAcnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result= - getChildrenByType(tree, asn1Parser.CHOICE_ITEM) |> +and CreateChoiceChild integerSizeInBytes (tasParameters : TemplateParameter list) (chAcnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result= + getChildrenByType(tree, asn1Parser.CHOICE_ITEM) |> List.traverseResultM(fun x -> result { match getTreeChildren(x) with - | first::sec::tail -> - let childAcnEncodingSpec = + | first::sec::tail -> + let childAcnEncodingSpec = match chAcnTypeEncodingSpec with | None -> None | Some sqe -> sqe.children |> Seq.tryFind(fun z -> z.name.Value = first.Text) |> Option.map(fun z -> z.childEncodingSpec) - let! tt = CreateType integerSizeInBytes tasParameters childAcnEncodingSpec astRoot sec fileTokens alreadyTakenComments ; + let! tt = CreateType integerSizeInBytes tasParameters childAcnEncodingSpec astRoot sec fileTokens alreadyTakenComments ; return - { - ChildInfo.Name = first.TextL; + { + ChildInfo.Name = first.TextL; Type = tt - Optionality=None; + Optionality=None; AcnInsertedField=false Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[x.TokenStopIndex].Line, x.TokenStartIndex - 1, x.TokenStopIndex + 2) } @@ -592,8 +592,8 @@ and CreateChoiceChild integerSizeInBytes (tasParameters : TemplateParameter list } ) -and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter list) (seqAcnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result, Asn1ParseError> = - let CreateChild(x:ITree) = +and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter list) (seqAcnTypeEncodingSpec : AcnTypeEncodingSpec option) (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result, Asn1ParseError> = + let CreateChild(x:ITree) = result { match x.Type with | asn1Parser.SEQUENCE_ITEM -> @@ -601,22 +601,22 @@ and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter l let typeDef = getChildByType(x, asn1Parser.TYPE_DEF) let optionalVal = getOptionalChildByType(x, asn1Parser.OPTIONAL) let defVal = getOptionalChildByType(x, asn1Parser.DEFAULT_VALUE) - let! chType = - let childAcnEncodingSpec = + let! chType = + let childAcnEncodingSpec = match seqAcnTypeEncodingSpec with | None -> None | Some sqe -> sqe.children |> Seq.tryFind(fun z -> z.name.Value = lid.Text) |> Option.map(fun z -> z.childEncodingSpec) CreateType integerSizeInBytes tasParameters childAcnEncodingSpec astRoot typeDef fileTokens alreadyTakenComments let! optVal = match (optionalVal,defVal) with - | (None, Some(v)) -> + | (None, Some(v)) -> result { let! dv = CreateValue integerSizeInBytes astRoot (v.GetChild(0)) return Some(Default(dv )) } | (Some(_), None) -> Ok (Some Optional) | (None, None) -> Ok None - | _ -> Error (Bug_Error("Bug in CreateSequenceChild")) + | _ -> Error (Bug_Error("Bug in CreateSequenceChild")) let comments = @@ -624,20 +624,20 @@ and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter l | true -> Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[x.TokenStopIndex].Line, x.TokenStartIndex - 1, x.TokenStopIndex + 2) | false -> [||] let chInfo = - { - ChildInfo.Name = lid.TextL; + { + ChildInfo.Name = lid.TextL; Type = chType; Optionality = optVal AcnInsertedField=false Comments = comments } return ChildInfo chInfo - | asn1Parser.COMPONENTS_OF -> + | asn1Parser.COMPONENTS_OF -> let! (md,ts) = CreateRefTypeContent(x.GetChild(0)) return ComponentsOf(md,ts) | asn1Parser.SEQUENCE_EXT_BODY | asn1Parser.SEQUENCE_EXT_GROUP - | asn1Parser.CHOICE_EXT_BODY -> + | asn1Parser.CHOICE_EXT_BODY -> return! Error(Semantic_Error(x.Location, "Unsupported ASN.1 feature (extensions)\n\nASN1SCC targets the S/W of space vehicles (it has been built and it is being\n\ maintained under European Space Agency's supervision). This means that\n\ we target ASN.1 grammars where the maximum message representation can be\n\ @@ -650,7 +650,7 @@ and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter l future versions of the protocols) with additional information. That however\n\ means that we can't statically compute the maximum size of these messages,\n\ which is, in effect, infinite.\n")) - | _ -> return! Error (Bug_Error("Unexpected input in CreateSequenceChild")) + | _ -> return! Error (Bug_Error("Unexpected input in CreateSequenceChild")) } let asn1Children = match getOptionChildByType(tree, asn1Parser.SEQUENCE_BODY) with @@ -661,7 +661,7 @@ and CreateSequenceChild integerSizeInBytes (tasParameters : TemplateParameter l | Some es -> match es.children with | [] -> asn1Children - | acnChildren -> + | acnChildren -> //let invalidAcnChildren = acnChildren |> List.filter(fun acnChild -> not (asn1Children |> List.choose(fun z -> match z with ChildInfo z -> Some z | ComponentsOf _ -> None ) |> List.exists (fun asn1Child -> acnChild.name.Value = asn1Child.Name.Value)) ) asn1Children @@ -672,12 +672,12 @@ and CreateNamedItems integerSizeInBytes (astRoot:list) (tree:ITree) (fil result { let itemChildren = getTreeChildren(itemItree) match itemChildren with - | name::value::_ -> - let! value = CreateValue integerSizeInBytes astRoot (value) + | name::value::_ -> + let! value = CreateValue integerSizeInBytes astRoot (value) return {NamedItem.Name=name.TextL; _value=Some value; Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[itemItree.TokenStopIndex].Line, itemItree.TokenStartIndex - 1, itemItree.TokenStopIndex + 2)} - | name::[] -> + | name::[] -> return {NamedItem.Name=name.TextL; _value= None; Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[itemItree.TokenStopIndex].Line, itemItree.TokenStartIndex - 1, itemItree.TokenStopIndex + 2)} - | _ -> return! Error (Bug_Error("Bug in CreateNamedItems.CreateItem")) + | _ -> return! Error (Bug_Error("Bug in CreateNamedItems.CreateItem")) } let enumItes = getChildrenByType(tree, asn1Parser.NUMBER_LST_ITEM) enumItes |> List.traverseResultM CreateItem @@ -687,11 +687,11 @@ and CreateNamedBitList integerSizeInBytes (astRoot:list) (tree:ITree) (f result { let itemChildren = getTreeChildren(itemItree) match itemChildren with - | name::vlue::_ -> + | name::vlue::_ -> let! value = result { match vlue.Type with - | asn1Parser.INT -> + | asn1Parser.INT -> match (vlue.BigIntL integerSizeInBytes ).Value >= 0I with | true -> return (IDV_IntegerValue(vlue.BigIntL integerSizeInBytes )) | false -> return! Error (Semantic_Error(vlue.Location, "Negative values are not permitted")) @@ -703,8 +703,8 @@ and CreateNamedBitList integerSizeInBytes (astRoot:list) (tree:ITree) (f | _ -> return! Error (Bug_Error("Bug in CreateValue CreateNamedBit 2")) } return {NamedBit0.Name=name.TextL; _value=value; Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[itemItree.TokenStopIndex].Line, itemItree.TokenStartIndex - 1, itemItree.TokenStopIndex + 2)} - | _ -> - return! Error (Bug_Error("Bug in CreateNamedBitList.CreateItem")) + | _ -> + return! Error (Bug_Error("Bug in CreateNamedBitList.CreateItem")) } let namedBits = getChildrenByType(tree, asn1Parser.NUMBER_LST_ITEM) namedBits |> List.traverseResultM CreateNamedBit @@ -721,7 +721,7 @@ and CreateTimeClass (astRoot:list) (tree:ITree) (fileTokens:array let text = strItem.Text.Substring(1, strItem.Text.Length-2) - let text_no_space_around_eq = removeSpaceArountEqual text + let text_no_space_around_eq = removeSpaceArountEqual text let text_no_space_around_eq, Fraction = let keyWord = "Time=HMSF" let i = text_no_space_around_eq.IndexOf(keyWord) @@ -734,7 +734,7 @@ and CreateTimeClass (astRoot:list) (tree:ITree) (fileTokens:array text_no_space_around_eq, 0 let text_no_space = text_no_space_around_eq.Replace(" ", "") match TimeClassMap.TryFind text_no_space with - | Some cl -> + | Some cl -> match cl with |Asn1LocalTime _ -> Ok (Asn1LocalTime Fraction) |Asn1UtcTime _ -> Ok (Asn1UtcTime Fraction) @@ -742,7 +742,7 @@ and CreateTimeClass (astRoot:list) (tree:ITree) (fileTokens:array |Asn1Date -> Ok (Asn1Date) |Asn1Date_LocalTime _ -> Ok (Asn1Date_LocalTime Fraction) |Asn1Date_UtcTime _ -> Ok (Asn1Date_UtcTime Fraction) - |Asn1Date_LocalTimeWithTimeZone _ -> Ok (Asn1Date_LocalTimeWithTimeZone Fraction) + |Asn1Date_LocalTimeWithTimeZone _ -> Ok (Asn1Date_LocalTimeWithTimeZone Fraction) | None -> Error (Semantic_Error(tree.Location, (sprintf "Invalid SETTINGS definition '%s'" text))) @@ -750,50 +750,50 @@ and CreateTimeClass (astRoot:list) (tree:ITree) (fileTokens:array let CreateTemplateParameter integerSizeInBytes (astRoot:list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List)= match tree.Type with |asn1Parser.TYPE_PARAM -> Ok (TypeParameter(tree.GetChild(0).TextL)) - |asn1Parser.VALUE_PARAM -> + |asn1Parser.VALUE_PARAM -> result { - let! newType = CreateType integerSizeInBytes [] None astRoot (tree.GetChild(0)) fileTokens alreadyTakenComments; + let! newType = CreateType integerSizeInBytes [] None astRoot (tree.GetChild(0)) fileTokens alreadyTakenComments; return (ValueParameter (newType, tree.GetChild(1).TextL)) } | _ -> Error (Bug_Error("Bug in CreateConstraint")) -let CreateTypeAssignment integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (acnModule : AcnModule option) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result = +let CreateTypeAssignment integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (acnModule : AcnModule option) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result = result { - let! parameters = + let! parameters = match tree.GetOptChild asn1Parser.PARAM_LIST with - | Some(prmList) -> + | Some(prmList) -> prmList.Children |> List.traverseResultM(fun x -> CreateTemplateParameter integerSizeInBytes astRoot x fileTokens alreadyTakenComments) | None -> Ok [] let tasName = tree.GetChild(0).TextL - let acnTypeAssignment = + let acnTypeAssignment = match acnModule with | None -> None | Some acnMod -> acnMod.typeAssignments |> Seq.tryFind(fun acnTas -> acnTas.name.Value = tasName.Value) let acnTypeEncodingSpec = - match acnTypeAssignment with + match acnTypeAssignment with | None -> None | Some a -> Some a.typeEncodingSpec - let! tp = CreateType integerSizeInBytes parameters acnTypeEncodingSpec astRoot (tree.GetChild(1)) fileTokens alreadyTakenComments; + let! tp = CreateType integerSizeInBytes parameters acnTypeEncodingSpec astRoot (tree.GetChild(1)) fileTokens alreadyTakenComments; return { TypeAssignment.Name = tasName - Type = tp + Type = tp Parameters = parameters Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[tree.TokenStopIndex].Line, tree.TokenStartIndex - 1, tree.TokenStopIndex + 1) - acnInfo = - match acnTypeAssignment with - | None -> None + acnInfo = + match acnTypeAssignment with + | None -> None | Some a -> Some ({AcnTypeAssignmentExtraInfo.loc = a.name.Location; acnParameters = a.acnParameters; comments = a.comments}) } } -let CreateValueAssignment integerSizeInBytes (astRoot:list) (tree:ITree) : Result= +let CreateValueAssignment integerSizeInBytes (astRoot:list) (tree:ITree) : Result= result { let alreadyTakenComments = System.Collections.Generic.List() let name = tree.GetChild(0).TextL; let! typ = CreateType integerSizeInBytes [] None astRoot (tree.GetChild(1)) [||] alreadyTakenComments - let! vl = CreateValue integerSizeInBytes astRoot (tree.GetChild(2)) + let! vl = CreateValue integerSizeInBytes astRoot (tree.GetChild(2)) return { ValueAssignment.Name = name @@ -807,8 +807,8 @@ let CreateValueAssignment integerSizeInBytes (astRoot:list) (tree:ITree) } -let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (implicitlyImportedTypes: (string*ImportedModule list) list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result = - let createImport (tree:ITree) = +let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (implicitlyImportedTypes: (string*ImportedModule list) list) (tree:ITree) (fileTokens:array) (alreadyTakenComments:System.Collections.Generic.List) : Result = + let createImport (tree:ITree) = { ImportedModule.Name = tree.GetChild(0).TextL; Types = getChildrenByType(tree, asn1Parser.UID) |> List.tail |> List.map (fun x -> x.TextL) Values = getChildrenByType(tree, asn1Parser.LID) |> List.map (fun x -> x.TextL) @@ -822,15 +822,15 @@ let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (i | None -> Exports.All let handleIntegerValues (tree:ITree) = let mdName = tree.GetChild(0).TextL - tree.AllChildren |> + tree.AllChildren |> List.filter(fun x -> x.Type = asn1Parser.INTEGER_TYPE && not (x.Children.IsEmpty) && x.Parent.Parent.Type = asn1Parser.TYPE_ASSIG) |> - List.collect(fun x -> + List.collect(fun x -> let tas = x.Parent.Parent.GetChild(0).TextL let Type = { Asn1Type.Kind = ReferenceType(mdName, tas, None, []); Constraints= []; Location = tas.Location; parameterizedTypeInstance = false; acnInfo = None;unitsOfMeasure = None; moduleName=mdName.Value } - + let scope = TypeScope(mdName, tas) - let namedItems = + let namedItems = x.Children |> List.filter(fun ni -> ni.Type = asn1Parser.NUMBER_LST_ITEM) |> List.map (fun ni -> @@ -851,34 +851,34 @@ let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (i namedItems) |> List.traverseResultM id result { match tree.Type with - | asn1Parser.MODULE_DEF -> + | asn1Parser.MODULE_DEF -> match getOptionChildByType(tree, asn1Parser.EXTENSIBILITY) with | Some(_) -> return! Error (Semantic_Error(tree.Location, "Unsupported ASN.1 feature: EXTENSIBILIY IMPLED. Extensibility is incompatible with embedded systems")) | None -> let modName = getChildByType(tree, asn1Parser.UID).TextL - let acnModule = - acnAst.files |> - List.collect(fun f -> f.modules) |> + let acnModule = + acnAst.files |> + List.collect(fun f -> f.modules) |> Seq.tryFind(fun am -> am.name.Value = modName.Value) - let! typeAssignments= + let! typeAssignments= getChildrenByType(tree, asn1Parser.TYPE_ASSIG) |> List.traverseResultM(fun x -> CreateTypeAssignment integerSizeInBytes astRoot acnAst acnModule x fileTokens alreadyTakenComments) - let! globalValueAssignments = + let! globalValueAssignments = getChildrenByType(tree, asn1Parser.VAL_ASSIG) |> List.traverseResultM(fun x -> CreateValueAssignment integerSizeInBytes astRoot x) let! typeScopedValueAssignments = handleIntegerValues tree - - let ret = - { + + let ret = + { Name= modName TypeAssignments= typeAssignments ValueAssignments = globalValueAssignments@typeScopedValueAssignments - Imports = + Imports = let explicitImports = getChildrenByType(tree, asn1Parser.IMPORTS_FROM_MODULE) |> List.map createImport let implicitlyImports = implicitlyImportedTypes |> List.filter(fun (m,_) -> m = modName.Value) |> List.collect snd let mergedImports = - implicitlyImports |> - List.fold (fun (curImps:ImportedModule list) iimp -> + implicitlyImports |> + List.fold (fun (curImps:ImportedModule list) iimp -> match curImps |> List.tryFind (fun z -> z.Name.Value = iimp.Name.Value) with - | Some eimp -> + | Some eimp -> let rest = curImps |> List.filter (fun z -> z.Name.Value <> eimp.Name.Value) let mergedImport = {eimp with Types = (eimp.Types @ iimp.Types) |> List.distinctBy(fun z -> z.Value) } mergedImport::rest @@ -886,7 +886,7 @@ let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (i mergedImports Exports = HandleExports() Comments = Antlr.Comment.GetComments(fileTokens, alreadyTakenComments, fileTokens.[tree.TokenStopIndex].Line, tree.TokenStartIndex - 1, tree.TokenStopIndex + 2) - postion = + position = let modEnd = getChildByType(tree, asn1Parser.END) modName.Location, modEnd.Location } @@ -896,7 +896,7 @@ let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (i let orphanAcnTasses = acnMod.typeAssignments |> List.filter(fun acnTas -> not (typeAssignments |> Seq.exists(fun asn1Tas -> asn1Tas.Name.Value = acnTas.name.Value) ) ) match orphanAcnTasses with | [] -> return ret - | _ -> + | _ -> let orphanAcnTassesStr = orphanAcnTasses |> Seq.map(fun z -> z.name.Value) |> Seq.StrJoin (", ") let errMsg = sprintf "The ACN module '%s' contains type assignments that do not exist in the corresponding ASN.1 module. For example, assignments '%s' are not defined in the ASN.1 module." acnMod.name.Value orphanAcnTassesStr Console.Error.WriteLine(AntlrParse.formatSemanticWarning acnMod.name.Location errMsg) @@ -906,15 +906,15 @@ let CreateAsn1Module integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (i } -let CreateAsn1File integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (implicitlyImportedTypes: (string*ImportedModule list) list) (tree:ITree, file, tokens) = +let CreateAsn1File integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (implicitlyImportedTypes: (string*ImportedModule list) list) (tree:ITree, file, tokens) = match tree.Type with - | asn1Parser.ASN1_FILE -> + | asn1Parser.ASN1_FILE -> result { let alreadyTakenComments = new System.Collections.Generic.List(); - let! modules= getTreeChildren(tree) |> List.traverseResultM(fun t-> CreateAsn1Module integerSizeInBytes astRoot acnAst implicitlyImportedTypes t tokens alreadyTakenComments) + let! modules= getTreeChildren(tree) |> List.traverseResultM(fun t-> CreateAsn1Module integerSizeInBytes astRoot acnAst implicitlyImportedTypes t tokens alreadyTakenComments) return - { - Asn1File.FileName=file; + { + Asn1File.FileName=file; Modules= modules Tokens = tokens } @@ -922,43 +922,43 @@ let CreateAsn1File integerSizeInBytes (astRoot:list) (acnAst:AcnAst) (imp | _ -> Error (Bug_Error("Bug in CreateAsn1File")) -let getReftypeName (tree:ITree) = +let getReftypeName (tree:ITree) = match getTreeChildren(tree) |> List.filter(fun x -> x.Type<> asn1Parser.ACTUAL_PARAM_LIST) with | refTypeName::[] -> Ok refTypeName.TextL | _::refTypeName::[] -> Ok refTypeName.TextL - | _ -> Error (Bug_Error("Bug in CrateType(refType)")) + | _ -> Error (Bug_Error("Bug in CrateType(refType)")) let rootCheckCyclicDeps (astRoot:list) : Result<(string*ImportedModule list) list, Asn1ParseError>= result { - let! allTasses = - astRoot |> - List.collect(fun f -> f.Children) |> - List.collect(fun m -> m.GetChildrenByType(asn1Parser.TYPE_ASSIG) |> List.map(fun t -> m,t )) |> - List.traverseResultM(fun (m,a) -> + let! allTasses = + astRoot |> + List.collect(fun f -> f.Children) |> + List.collect(fun m -> m.GetChildrenByType(asn1Parser.TYPE_ASSIG) |> List.map(fun t -> m,t )) |> + List.traverseResultM(fun (m,a) -> result { let (md,ts) = (m.GetChild(0).TextL, a.GetChild(0).TextL) - let paramsSet = + let paramsSet = a.AllChildren |> List.filter(fun x -> x.Type = asn1Parser.TYPE_PARAM) |> List.map(fun z -> (z.GetChild 0).Text) |> Set.ofList - let! children = - a.AllChildren |> + let! children = + a.AllChildren |> List.filter(fun x -> x.Type = asn1Parser.REFERENCED_TYPE || x.Type = asn1Parser.PREFERENCED_TYPE ) |> List.traverseResultM(fun x -> //Exclude reference to type parameters result { let! refTypeName = getReftypeName x match paramsSet.Contains(refTypeName.Value) with | true -> return None - | false -> - let! a = CreateRefTypeContent x + | false -> + let! a = CreateRefTypeContent x return (Some a) - }) + }) let children = children |> List.choose id return ((md,ts), children) }) let tasses = allTasses |> List.map fst let refTypes = allTasses |> List.collect snd - let orphanRefTypes = - refTypes |> + let orphanRefTypes = + refTypes |> List.choose(fun (rfm, rft) -> match tasses |> List.tryFind( fun (m,t) -> m.Value = rfm.Value && t.Value = rft.Value) with | Some _ -> None @@ -968,19 +968,19 @@ let rootCheckCyclicDeps (astRoot:list) : Result<(string*ImportedModule li | [] -> Ok () | (l,msg)::_-> Error(Semantic_Error(l,msg)) - let implicitlyImportedTypes = - allTasses |> + let implicitlyImportedTypes = + allTasses |> List.map (fun ((md,ts), rfList) -> ((md,ts), rfList |> List.filter(fun (rm, rt) -> rm.Value <> md.Value) ) ) |> List.filter (fun (_, rfList) -> not rfList.IsEmpty) |> List.map(fun ((md,ts), rfList) -> (md, rfList) ) |> List.groupBy (fun (md,list) -> md.Value) |> - List.map(fun (md, grp) -> + List.map(fun (md, grp) -> let impModules = grp |> List.collect snd |> List.groupBy fst |> List.map(fun (rfm, rfTypes) -> {ImportedModule.Name = rfm; Types=rfTypes |> List.map snd |> List.distinctBy (fun a -> a.Value); Values=[]} ) md, impModules) - + let independentNodes = allTasses |> List.filter(fun (_,lst) -> lst.IsEmpty) |> List.map fst - let dependentNodes = allTasses |> List.filter(fun (_,lst) -> not lst.IsEmpty) + let dependentNodes = allTasses |> List.filter(fun (_,lst) -> not lst.IsEmpty) let comparer (m1:StringLoc, t1:StringLoc) (m2:StringLoc, t2:StringLoc) = m1.Value = m2.Value && t1.Value=t2.Value let ret = DoTopologicalSort2_noexc independentNodes dependentNodes comparer @@ -988,24 +988,24 @@ let rootCheckCyclicDeps (astRoot:list) : Result<(string*ImportedModule li | Error lst -> match lst with | [] -> return! Error(Bug_Error("")) - | ((m,t),_)::xs -> - let printTas ((md:StringLoc,ts:StringLoc), deps: (StringLoc*StringLoc) list) = + | ((m,t),_)::xs -> + let printTas ((md:StringLoc,ts:StringLoc), deps: (StringLoc*StringLoc) list) = sprintf "Type assignment '%s.%s' depends on : %s" md.Value ts.Value (deps |> List.map(fun (m,t) -> "'" + m.Value + "." + t.Value + "'") |> Seq.StrJoin ", ") let names = lst |> List.map printTas |> Seq.StrJoin " and " return! Error (Semantic_Error (t.Location, sprintf "Cyclic dependencies detected : %s" names)) - | Ok _ -> + | Ok _ -> return implicitlyImportedTypes } -let CreateAstRoot_no_exc (list:CommonTypes.AntlrParserResult list) (acnAst:AcnAst) (args:CommandLineSettings) = +let CreateAstRoot_no_exc (list:CommonTypes.AntlrParserResult list) (acnAst:AcnAst) (args:CommandLineSettings) = result { let astRoot = list |> List.map (fun r -> r.rootItem) ITree.RegisterFiles(list |> Seq.map (fun x -> (x.rootItem, x.fileName))) let! implicitlyImportedTypes = rootCheckCyclicDeps astRoot - let! files = - list |> - List.traverseResultM(fun x -> + let! files = + list |> + List.traverseResultM(fun x -> CreateAsn1File args.integerSizeInBytes astRoot acnAst implicitlyImportedTypes (x.rootItem,x.fileName, x.tokens)) return { AstRoot.Files = files @@ -1013,7 +1013,7 @@ let CreateAstRoot_no_exc (list:CommonTypes.AntlrParserResult list) (acnAst:AcnAs } } -let CreateAstRoot (list:CommonTypes.AntlrParserResult list) (acnAst:AcnAst) (args:CommandLineSettings) = +let CreateAstRoot (list:CommonTypes.AntlrParserResult list) (acnAst:AcnAst) (args:CommandLineSettings) = match CreateAstRoot_no_exc list acnAst args with | Ok ret -> ret | Error(Semantic_Error(l,m)) -> raise (SemanticError(l,m)) diff --git a/FrontEndAst/DAst.fs b/FrontEndAst/DAst.fs index c4315fb9f..73decf3bd 100644 --- a/FrontEndAst/DAst.fs +++ b/FrontEndAst/DAst.fs @@ -17,7 +17,7 @@ open System.Collections.Generic type CallerScope = { modName : string - arg : FuncParamType + arg : Selection } type AlphaFunc = { @@ -31,12 +31,12 @@ type IcdTypeCol = | IcdPlainType of string (* -let getIcdTypeCol_label l = +let getIcdTypeCol_label l = match l with | IcdRefType (l,_) | IcdPlainType l -> l *) - + type IcdRowType = | FieldRow | ReferenceToCompositeTypeRow @@ -51,8 +51,8 @@ type IcdRow = { sPresent : string sType : IcdTypeCol sConstraint : string option - minLengtInBits : BigInteger - maxLengtInBits : BigInteger + minLengthInBits : BigInteger + maxLengthInBits : BigInteger sUnits : string option rowType : IcdRowType } @@ -67,8 +67,8 @@ type IcdTypeAss = { comments : string list rows : IcdRow list //compositeChildren : IcdTypeAss list - minLengtInBytes : BigInteger - maxLengtInBytes : BigInteger + minLengthInBytes : BigInteger + maxLengthInBytes : BigInteger hash : string } type State = { @@ -106,8 +106,8 @@ and SeqValue = list and ChValue = NamedValue and RefValue = ((string*string)*Asn1Value) and TimeValue = Asn1DateTimeValue -and ObjectIdenfierValue = - | Asn1DefinedObjectIdentifierValue of ((ResolvedObjectIdentifierValueCompoent list)*(ObjectIdentifierValueCompoent list)) +and ObjectIdentifierValue = + | Asn1DefinedObjectIdentifierValue of ((ResolvedObjectIdentifierValueComponent list)*(ObjectIdentifierValueComponent list)) | InternalObjectIdentifierValue of BigInteger list and NamedValue = { @@ -123,31 +123,31 @@ and Asn1Value = { } and Asn1ValueKind = - | IntegerValue of IntegerValue - | RealValue of RealValue - | StringValue of StringValue + | IntegerValue of IntegerValue + | RealValue of RealValue + | StringValue of StringValue | TimeValue of TimeValue - | BooleanValue of BooleanValue - | BitStringValue of BitStringValue + | BooleanValue of BooleanValue + | BitStringValue of BitStringValue | OctetStringValue of OctetStringValue - | EnumValue of EnumValue - | SeqOfValue of SeqOfValue - | SeqValue of SeqValue - | ChValue of ChValue + | EnumValue of EnumValue + | SeqOfValue of SeqOfValue + | SeqValue of SeqValue + | ChValue of ChValue | NullValue of NullValue - | RefValue of RefValue - | ObjOrRelObjIdValue of ObjectIdenfierValue + | RefValue of RefValue + | ObjOrRelObjIdValue of ObjectIdentifierValue //type Asn1GenericValue = Asn1Value - + type ExpOrStatement = - | Expression - | Statement + | Expression + | Statement -type GenericLocalVariable = +type GenericLocalVariable = { name : string varType : string @@ -157,12 +157,12 @@ type GenericLocalVariable = } type LocalVariable = - | SequenceOfIndex of int*int option //i index, initialValue - | IntegerLocalVariable of string*int option //variable name, initialValue - | Asn1SIntLocalVariable of string*int option //variable name, initialValue - | Asn1UIntLocalVariable of string*int option //variable name, initialValue - | FlagLocalVariable of string*int option //variable name, initialValue - | BooleanLocalVariable of string*bool option //variable name, initialValue + | SequenceOfIndex of int*string option //i index, initialValue + | IntegerLocalVariable of string*string option //variable name, initialValue + | Asn1SIntLocalVariable of string*string option //variable name, initialValue + | Asn1UIntLocalVariable of string*string option //variable name, initialValue + | FlagLocalVariable of string*string option //variable name, initialValue + | BooleanLocalVariable of string*string option //variable name, initialValue | AcnInsertedChild of string*string*string //variable name, type, initialValue | GenericLocalVariable of GenericLocalVariable @@ -182,14 +182,11 @@ type ValidationStatement = | ValidationStatement of (string * LocalVariable list) - //Emit_local_variable_SQF_Index(nI, bHasInitalValue)::="I:Integer:=1;" - - type ReferenceToExistingDefinition = { /// the module where this type is defined /// if the value is not present then is the same as the "caller" programUnit : string option - /// The name of the defined type. + /// The name of the defined type. typedefName : string definedInRtl : bool } @@ -199,26 +196,26 @@ type TypeDefinition = { // In C this is None //programUnitName : string option /// The name of the defined type. If type is a type assignment then is the name of the type assignment. - /// if the type is an inner type (i.e. within a SEQUENCE/SEQUENCE OF/CHOICE) then name is created as + /// if the type is an inner type (i.e. within a SEQUENCE/SEQUENCE OF/CHOICE) then name is created as /// parentType.typedefName + "_" + component_name typedefName : string /// the complete definition of the type /// e.g. C : typedef asn1SccSint MyInt4; - /// and Ada: SUBTYPE MyInt4 IS adaasn1rtl.Asn1Int range 0..25; - /// For composite types, typedefBody contains also the definition of any + /// and Ada: SUBTYPE MyInt4 IS adaasn1rtl.Asn1Int range 0..25; + /// For composite types, typedefBody contains also the definition of any /// inner children typedefBody : unit -> string baseType : ReferenceToExistingDefinition option } -type TypeDefintionOrReference = +type TypeDefinitionOrReference = /// indicates that no extra type definition is required (e.g. INTEGER without constraints or type reference type without new constraints) - | ReferenceToExistingDefinition of ReferenceToExistingDefinition - /// indicates that a new type is - | TypeDefinition of TypeDefinition + | ReferenceToExistingDefinition of ReferenceToExistingDefinition + /// indicates that a new type is + | TypeDefinition of TypeDefinition -type ErroCode = { +type ErrorCode = { errCodeValue : int errCodeName : string comment : string option @@ -229,10 +226,10 @@ type BaseTypesEquivalence<'T> = { uper : 'T option acn : 'T option } - + (* -Generates initialization statement(s) that inititalize the type with the given Asn1GeneticValue. -*) +Generates initialization statement(s) that initialize the type with the given Asn1GeneticValue. +*) type InitFunctionResult = { funcBody : string localVariables : LocalVariable list @@ -244,14 +241,14 @@ type TestCaseValue = | TcvAnyValue | TcvEnumeratedValue of String | TcvSizeableTypeValue of BigInteger //length - | TcvChoiceAlternativePresentWhenInt of BigInteger + | TcvChoiceAlternativePresentWhenInt of BigInteger | TcvChoiceAlternativePresentWhenStr of String (* In general, an automatic test involves many types (e.g. in sequences, choices etc). It consists of function (initTestCaseFunc) that returns -a string with the statements than initialize all involved types plus the local variavles needed. +a string with the statements than initialize all involved types plus the local variables needed. The id of the types that are involved in this automatic test case are stored within a map with name testCaseTypeIDsMap. The need for this map -is in order to generate valid ACN test cases. I.e. the ACN checks that test case provides values for all ACN inserted fields. Otherwise is invalid and not +is in order to generate valid ACN test cases. I.e. the ACN checks that test case provides values for all ACN inserted fields. Otherwise is invalid and not generated. *) type AutomaticTestCase = { @@ -260,14 +257,14 @@ type AutomaticTestCase = { } type InitProcedure0 = { - funcName:string; - def:string; - body:string + funcName:string; + def:string; + body:string } type InitFunction = { - initExpression : string // an expression that provides the default initialization. - initExpressionGlobal : string // an expression that provides the default initialization. + initExpression : string // an expression that provides the default initialization. + initExpressionGlobal : string // an expression that provides the default initialization. //It is usually present except of some rare cases such as an empty sequence (for C only) etc initProcedure : InitProcedure0 option initFunction : InitProcedure0 option // an expression that initializes the given type to a default value. @@ -289,7 +286,7 @@ type IsEqualBody = | EqualBodyStatementList of (CallerScope -> CallerScope -> (string*(LocalVariable list)) option) type EqualFunction = { - isEqualFuncName : string option // the name of the equal function. + isEqualFuncName : string option // the name of the equal function. isEqualFunc : string option // the body of the equal function isEqualFuncDef : string option isEqualBody : IsEqualBody // a function that returns an expression or a statement list @@ -299,21 +296,21 @@ type EqualFunction = { type AnonymousVariable = { valueName : string - valueExpresion : string + valueExpression : string typeDefinitionName : string valKind : Asn1ValueKind // the value } type IsValidFunction = { - errCodes : ErroCode list + errCodes : ErrorCode list funcName : string option // the name of the function. Valid only for TASes) func : string option // the body of the function funcDef : string option // function definition in header file //funcExp : (CallerScope -> ValidationCodeBlock) // return a single boolean expression funcBody : CallerScope -> ValidationStatement //returns a list of validations statements - //funcBody2 : string -> string -> string //like funBody but with two arguement p and accessOper ( i.e. '->' or '.') - - alphaFuncs : AlphaFunc list + //funcBody2 : string -> string -> string //like funBody but with two arguments p and accessOper ( i.e. '->' or '.') + + alphaFuncs : AlphaFunc list localVariables : LocalVariable list anonymousVariables : AnonymousVariable list //list with the anonymous asn1 values used in constraints and which must be declared. //these are the bit and octet string values which cannot be expressed as single primitives in C/Ada @@ -325,31 +322,32 @@ type IsValidFunction = { type UPERFuncBodyResult = { funcBody : string - errCodes : ErroCode list + errCodes : ErrorCode list localVariables : LocalVariable list - bValIsUnReferenced : bool - bBsIsUnReferenced : bool + bValIsUnReferenced : bool + bBsIsUnReferenced : bool + resultExpr : string option } type UPerFunction = { funcName : string option // the name of the function func : string option // the body of the function funcDef : string option // function definition in header file funcBody : CallerScope -> (UPERFuncBodyResult option) // returns a list of validations statements - funcBody_e : ErroCode -> CallerScope -> (UPERFuncBodyResult option) + funcBody_e : ErrorCode -> CallerScope -> (UPERFuncBodyResult option) } type AcnFuncBodyResult = { funcBody : string - errCodes : ErroCode list + errCodes : ErrorCode list localVariables : LocalVariable list - bValIsUnReferenced : bool - bBsIsUnReferenced : bool - + bValIsUnReferenced : bool + bBsIsUnReferenced : bool + resultExpr : string option } type XERFuncBodyResult = { funcBody : string - errCodes : ErroCode list + errCodes : ErrorCode list localVariables : LocalVariable list encodingSizeInBytes : BigInteger } @@ -364,7 +362,7 @@ type XerFunctionRec = { funcDef : string option // function definition in header file encodingSizeInBytes : BigInteger funcBody : CallerScope -> (XerTag option) -> (XERFuncBodyResult option) - funcBody_e : ErroCode -> CallerScope -> (XerTag option) -> (XERFuncBodyResult option) //p, XmlTag, returns a list of encoding/decoding statements + funcBody_e : ErrorCode -> CallerScope -> (XerTag option) -> (XERFuncBodyResult option) //p, XmlTag, returns a list of encoding/decoding statements } type XerFunction = @@ -384,8 +382,8 @@ type AcnFunction = { // takes as input (a) any acn arguments and (b) the field where the encoding/decoding takes place // returns a list of acn encoding statements - funcBody : State->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State) - funcBodyAsSeqComp : State->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> string -> ((AcnFuncBodyResult option)*State) + funcBody : State->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> ((AcnFuncBodyResult option)*State) + funcBodyAsSeqComp : State->((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> string -> ((AcnFuncBodyResult option)*State) isTestVaseValid : AutomaticTestCase -> bool icd : IcdAux option (* always present in Encode, always None in Decode *) } @@ -403,7 +401,7 @@ type TestCaseFunction = { } type Integer = { - //bast inherrited properties + //bast inherited properties baseInfo : Asn1AcnAst.Integer //DAst properties @@ -411,12 +409,12 @@ type Integer = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : IntegerValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -439,12 +437,12 @@ type Enumerated = { //DAst properties //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : EnumValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -462,12 +460,12 @@ type ObjectIdentifier = { baseInfo : Asn1AcnAst.ObjectIdentifier constraintsAsn1Str : string list //an ASN.1 representation of the constraints - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string - //initialValue : ObjectIdenfierValue + //initialValue : ObjectIdentifierValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -485,12 +483,12 @@ type TimeType = { baseInfo : Asn1AcnAst.TimeType constraintsAsn1Str : string list //an ASN.1 representation of the constraints - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : TimeValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -513,12 +511,12 @@ type Real = { //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : RealValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -540,12 +538,12 @@ type Boolean = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : BooleanValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -567,7 +565,7 @@ type NullType = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string initFunction : InitFunction //initialValue : NullValue @@ -591,12 +589,12 @@ type StringType = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : StringValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -619,12 +617,12 @@ type OctetString = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : OctetStringValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -647,12 +645,12 @@ type BitString = { constraintsAsn1Str : string list //an ASN.1 representation of the constraints //baseTypeEquivalence: BaseTypesEquivalence //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string //initialValue : BitStringValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -673,14 +671,11 @@ type SequenceOf = { //DAst properties constraintsAsn1Str : string list //an ASN.1 representation of the constraints - //baseTypeEquivalence: BaseTypesEquivalence - //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string - //initialValue : SeqOfValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option + isValidFunction : IsValidFunction option uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -690,26 +685,8 @@ type SequenceOf = { uperEncDecTestFunc : EncodeDecodeTestFunc option acnEncDecTestFunc : EncodeDecodeTestFunc option xerEncDecTestFunc : EncodeDecodeTestFunc option - - //automaticTestCasesValues : Asn1Value list -} - - - -(* -and SeqChildInfo = { - baseInfo : Asn1AcnAst.SeqChildInfo - chType : Asn1Type - - - //DAst properties - c_name : string - isEqualBodyStats : string -> string -> string -> (string*(LocalVariable list)) option // - isValidBodyStats : int -> (SeqChoiceChildInfoIsValid option * int) } -*) - and AcnChild = { Name : StringLoc @@ -718,11 +695,12 @@ and AcnChild = { Type : Asn1AcnAst.AcnInsertedType typeDefinitionBodyWithinSeq : string funcBody : CommonTypes.Codec -> ((AcnGenericTypes.RelativePath*AcnGenericTypes.AcnParameter) list) -> CallerScope -> (AcnFuncBodyResult option) // returns a list of validations statements - funcUpdateStatement : AcnChildUpdateResult option // vTarget, pSrcRoot, return the update statement + funcUpdateStatement : AcnChildUpdateResult option // vTarget, pSrcRoot, return the update statement Comments : string array + initExpression : string } -and SeqChildInfo = +and SeqChildInfo = | Asn1Child of Asn1Child | AcnChild of AcnChild @@ -731,9 +709,8 @@ and Asn1Child = { Name : StringLoc _c_name : string _scala_name : string - _ada_name : string - isEqualBodyStats : CallerScope -> CallerScope -> (string*(LocalVariable list)) option // - //isValidBodyStats : State -> (SeqChoiceChildInfoIsValid option * State) + _ada_name : string + isEqualBodyStats : CallerScope -> CallerScope -> (string*(LocalVariable list)) option Type : Asn1Type Optionality : Asn1AcnAst.Asn1Optionality option Comments : string array @@ -748,14 +725,11 @@ and Sequence = { //DAst properties constraintsAsn1Str : string list //an ASN.1 representation of the constraints - //baseTypeEquivalence: BaseTypesEquivalence - //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string - //initialValue : SeqValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstraint integer) + isValidFunction : IsValidFunction option // it is optional because some types do not require an IsValid function (e.g. an unconstrained integer) uperEncFunction : UPerFunction uperDecFunction : UPerFunction // @@ -766,8 +740,6 @@ and Sequence = { uperEncDecTestFunc : EncodeDecodeTestFunc option acnEncDecTestFunc : EncodeDecodeTestFunc option xerEncDecTestFunc : EncodeDecodeTestFunc option - - //automaticTestCasesValues : Asn1Value list } @@ -777,17 +749,16 @@ and ChChildInfo = { Name : StringLoc _c_name : string _scala_name : string - _ada_name : string + _ada_name : string _present_when_name_private : string // Does not contain the "_PRESENT". Not to be used directly by backends. Backends should use presentWhenName acnPresentWhenConditions : AcnGenericTypes.AcnPresentWhenConditionChoiceChild list Comments : string array - chType :Asn1Type + chType : Asn1Type Optionality : Asn1AcnAst.Asn1ChoiceOptionality option - + //DAst properties - isEqualBodyStats : CallerScope -> CallerScope -> string*(LocalVariable list) // - //isValidBodyStats : State -> (SeqChoiceChildInfoIsValid option * State) + isEqualBodyStats : CallerScope -> CallerScope -> string*(LocalVariable list) } and AcnChoiceEncClass = @@ -795,12 +766,12 @@ and AcnChoiceEncClass = | CEC_enum of (Asn1AcnAst.ReferenceToEnumerated * Asn1AcnAst.Determinant) | CEC_presWhen with - override this.ToString () = + override this.ToString () = match this with | CEC_uper -> "CEC_uper" | CEC_enum (a,b) -> sprintf "CEC_enum(%s)" b.id.AsString | CEC_presWhen -> "CEC_presWhen" - + and Choice = { @@ -809,14 +780,11 @@ and Choice = { ancEncClass : AcnChoiceEncClass //DAst properties constraintsAsn1Str : string list //an ASN.1 representation of the constraints - //baseTypeEquivalence: BaseTypesEquivalence - //typeDefinition : TypeDefinitionCommon - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string - //initialValue : ChValue initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option + isValidFunction : IsValidFunction option uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -826,8 +794,6 @@ and Choice = { uperEncDecTestFunc : EncodeDecodeTestFunc option acnEncDecTestFunc : EncodeDecodeTestFunc option xerEncDecTestFunc : EncodeDecodeTestFunc option - - //automaticTestCasesValues : Asn1Value list } @@ -835,14 +801,12 @@ and ReferenceType = { baseInfo : Asn1AcnAst.ReferenceType resolvedType : Asn1Type - //typeDefinition : TypeDefinitionCommon constraintsAsn1Str : string list //an ASN.1 representation of the constraints - definitionOrRef : TypeDefintionOrReference + definitionOrRef : TypeDefinitionOrReference printValue : string -> (Asn1ValueKind option) -> (Asn1ValueKind) -> string - //initialValue : Asn1Value initFunction : InitFunction equalFunction : EqualFunction - isValidFunction : IsValidFunction option + isValidFunction : IsValidFunction option uperEncFunction : UPerFunction uperDecFunction : UPerFunction acnEncFunction : AcnFunction @@ -852,19 +816,17 @@ and ReferenceType = { uperEncDecTestFunc : EncodeDecodeTestFunc option acnEncDecTestFunc : EncodeDecodeTestFunc option xerEncDecTestFunc : EncodeDecodeTestFunc option - - //automaticTestCasesValues : Asn1Value list } and AcnChildUpdateResult = { - updateAcnChildFnc : (*typedef name*)string -> CallerScope -> CallerScope -> string + updateAcnChildFnc : AcnChild -> CallerScope -> CallerScope -> string //Given an automatic test case (which includes a map with the IDs of the involved types), this function //checks if the automatic test case contains a type which depends on this acn Child. If this is true - // it returns the value of the depenendency, otherwise none + // it returns the value of the dependency, otherwise none //if the acn child depends on multiple ASN.1 types then this function (multi ACN update) checks that all ASN.1 types //have value and the value is the same. In this case the value is returned. Otherwise none - testCaseFnc : AutomaticTestCase -> TestCaseValue option - errCodes : ErroCode list + testCaseFnc : AutomaticTestCase -> TestCaseValue option + errCodes : ErrorCode list localVariables : LocalVariable list } @@ -875,14 +837,13 @@ and DastAcnParameter = { loc : SrcLoc id : ReferenceToType typeDefinitionBodyWithinSeq : string - //funcUpdateStatement00 : AcnChildUpdateResult option // vTarget, pSrcRoot, return the update statement } - + and Asn1Type = { id : ReferenceToType - acnAligment : AcnGenericTypes.AcnAligment option + acnAlignment : AcnGenericTypes.AcnAlignment option acnParameters : DastAcnParameter list Location : SrcLoc //Line no, Char pos moduleName : string @@ -894,10 +855,7 @@ and Asn1Type = { typeAssignmentInfo : AssignmentInfo option Kind : Asn1TypeKind - unitsOfMeasure : string option - - //parInfoData : Asn1Fold.ParentInfo option - //newTypeDefName : string + unitsOfMeasure : string option } @@ -920,18 +878,13 @@ and Asn1TypeKind = let getNextValidErrorCode (cur:State) (errCodeName:string) (comment:string option) = - - //if (errCodeName.ToUpper() = "ERR_ACN_ENCODE_TC_DATA_HEADER_TCPACKETPUSVERSIONNUMBER") then - // let aaa = cur.curErrCodeNames |> Set.toArray - // printfn "???" - - let rec getErroCode (errCodeName:string) = + let rec getErrorCode (errCodeName:string) = match cur.curErrCodeNames.Contains errCodeName with - | false -> {ErroCode.errCodeName = errCodeName; errCodeValue = cur.currErrorCode; comment=comment} - | true -> - getErroCode (errCodeName + "_2") + | false -> {ErrorCode.errCodeName = errCodeName; errCodeValue = cur.currErrorCode; comment=comment} + | true -> + getErrorCode (errCodeName + "_2") - let errCode = getErroCode (errCodeName.ToUpper()) + let errCode = getErrorCode (errCodeName.ToUpper()) errCode, {cur with currErrorCode = cur.currErrorCode + 1; curErrCodeNames = cur.curErrCodeNames.Add errCode.errCodeName} type TypeAssignment = { @@ -1004,7 +957,7 @@ type TC_Param = { typeName : string } -type TC_EpressionType = +type TC_ExpressionType = | TC_INTEGER | TC_REAL | TC_STRING @@ -1018,14 +971,14 @@ type TC_Statement = | ForStatement of {|initExp:TC_Expression; termination : TC_Expression; incrementExpression : TC_Expression; innerStatement:TC_Statement|} | WhileStatement of {|whileTrueExp : TC_Expression; innerStatement:TC_Statement|} | IfStatement of {| ifelsif : {|whileTrueExp : TC_Expression; innerStatement:TC_Statement|} list; elseStatement: TC_Statement option |} - + and TC_Expression = | TC_EqExpression of TC_Expression*TC_Expression | TC_GtExpression of TC_Expression*TC_Expression | TC_GteExpression of TC_Expression*TC_Expression - | TC_ReferenceToVariable of TC_EpressionType*string - | TC_Literal of TC_EpressionType*string + | TC_ReferenceToVariable of TC_ExpressionType*string + | TC_Literal of TC_ExpressionType*string | TC_AccessToField of TC_Expression * string | TC_AccessToArrayElement of TC_Expression * TC_Expression diff --git a/FrontEndAst/EnsureUniqueEnumNames.fs b/FrontEndAst/EnsureUniqueEnumNames.fs index e170025be..fb14b2c68 100644 --- a/FrontEndAst/EnsureUniqueEnumNames.fs +++ b/FrontEndAst/EnsureUniqueEnumNames.fs @@ -28,7 +28,7 @@ let rec private handleEnumChoices (r:AstRoot) (renamePolicy:EnumRenamePolicy)= for tas in m.TypeAssignments do for t in GetMySelfAndChildren tas.Type do match t.Kind with - | Choice(children) -> + | Choice(children) -> let names = children |> List.map(fun x -> x.present_when_name) yield! names | _ -> () } |> Seq.toList |> List.keepDuplicatesCaseInsensitive @@ -44,30 +44,30 @@ let rec private handleEnumChoices (r:AstRoot) (renamePolicy:EnumRenamePolicy)= | false -> ch.present_when_name | true -> let aaaa = key |> List.rev |> List.map ToC |> Seq.skipWhile(fun x -> ch.present_when_name.Contains x) |> Seq.toList - let newPrefix = + let newPrefix = match aaaa with | z1::_ -> z1 - | [] -> + | [] -> let errMsg = sprintf "Choice ch.present_when_name = '%s', key=%A, state='%A'" ch.present_when_name key state raise (SemanticError(old.Location,errMsg)) newPrefix + "_" + ch.present_when_name - + {ch with Type = t; present_when_name = ToC2 newUniqueName},ns match old.Kind with - | Choice(children) -> + | Choice(children) -> //let newChildren, finalState = children |> foldMap CloneChild state let newChildren, finalState = match renamePolicy with - | AlwaysPrefixTypeName + | AlwaysPrefixTypeName | NoRenamePolicy -> children, state | SelectiveEnumerants -> children |> foldMap CloneChild state - | AllEnumerants -> + | AllEnumerants -> let newChildren, finalState = children |> foldMap CloneChild state let newPrefix = newChildren |> List.map(fun itm -> itm.present_when_name.Replace(ToC2 itm.Name.Value,"")) |> List.maxBy(fun prf -> prf.Length) - let newChildren = + let newChildren = children |> List.map(fun ch -> {ch with present_when_name = newPrefix + ch.present_when_name}) - + newChildren, finalState {old with Kind = Choice(newChildren)}, finalState | _ -> defaultConstructors.cloneType old m key cons state @@ -89,7 +89,7 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa let cmp (s1:string) (s2:string) = match lm.lg.isCaseSensitive with | true -> s1 = s2 - | false -> s1.icompare s2 + | false -> s1.icompare s2 match renamePolicy with | FieldPrefixAuto -> let invalidComponentNames = seq { @@ -97,11 +97,11 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa for tas in m.TypeAssignments do for t in GetMySelfAndChildren tas.Type do match t.Kind with - | Sequence(children) - | Choice(children) -> - let names = - children |> - List.choose(fun x -> + | Sequence(children) + | Choice(children) -> + let names = + children |> + List.choose(fun x -> let isKeyword = lm.lg.Keywords |> Seq.exists(cmp (lm.lg.getChildInfoName x) ) //In ASN.1 a type assignment name starts with a Capital letter while a field name starts with a small letter. //So, in case sensitive languages, the type assignment name will never conflict with a field name. @@ -117,15 +117,15 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa | false -> None | true -> r.Modules |> Seq.tryFind(fun m -> cmp (ToC (lm.lg.getChildInfoName x)) (ToC m.Name.Value) ) - + match isKeyword , conflictingTas, confilectingModuleName with | true, _, _ -> Some {curChildName = (lm.lg.getChildInfoName x); reasonToChange = FieldIsKeyword} | false, (Some tas), _ -> Some {curChildName = (lm.lg.getChildInfoName x); reasonToChange = (FieldIsAlsoType tas.Name.Value)} | false, None, Some m -> Some {curChildName = (lm.lg.getChildInfoName x); reasonToChange = (FieldIsAlsoModule m.Name.Value)} - | false, None, None -> None ) + | false, None, None -> None ) //List.map(fun x -> x.CName lang) yield! names - | _ -> () } |> Seq.toList + | _ -> () } |> Seq.toList match invalidComponentNames with @@ -152,12 +152,12 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa newCh, ns //match lang with //| ProgrammingLanguage.C -> {ch with Type = t; c_name = ToC2 newUniqueName},ns - //| ProgrammingLanguage.Scala -> {ch with Type = t; scala_name = ToC2 newUniqueName},ns + //| ProgrammingLanguage.Scala -> {ch with Type = t; scala_name = ToC2 newUniqueName},ns //| ProgrammingLanguage.Ada -> {ch with Type = t; ada_name = ToC2 newUniqueName},ns match old.Kind with - | Choice(children) - | Sequence(children) -> + | Choice(children) + | Sequence(children) -> let newChildren, finalState = children |> foldMap CloneChild state match old.Kind with | Choice(children) -> {old with Kind = Choice(newChildren)}, finalState @@ -167,23 +167,23 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa let newTree = CloneTree r {defaultConstructors with cloneType = CloneType; } invalidComponentNames |> fst handleSequencesAndChoices newTree (lang,lm) renamePolicy - | FieldPrefixUserValue userValue -> + | FieldPrefixUserValue userValue -> let CloneType (old:Asn1Type) m (key:list) (cons:Constructors) (state:State) = match old.Kind with - | Choice(children) - | Sequence(children) -> + | Choice(children) + | Sequence(children) -> let newChildren, finalState = - let newChildren = + let newChildren = children |> List.map(fun ch -> lm.lg.setChildInfoName ch (userValue + lm.lg.getChildInfoName ch)) (* match lang with - | ProgrammingLanguage.C-> + | ProgrammingLanguage.C-> children |> List.map(fun ch -> {ch with c_name = ToC (userValue + ch.c_name)}) - | ProgrammingLanguage.Scala-> + | ProgrammingLanguage.Scala-> children |> List.map(fun ch -> {ch with scala_name = ToC (userValue + ch.scala_name)}) - | ProgrammingLanguage.Ada -> + | ProgrammingLanguage.Ada -> children |> List.map(fun ch -> {ch with ada_name = ToC(userValue + ch.ada_name)}) - *) + *) newChildren, state match old.Kind with | Choice(children) -> {old with Kind = Choice(newChildren)}, finalState @@ -197,29 +197,29 @@ let rec private handleSequencesAndChoices (r:AstRoot) ((lang, lm): ProgrammingLa let rec private handleEnums (r:AstRoot) (renamePolicy:EnumRenamePolicy) ((lang, lm): ProgrammingLanguage*LanguageMacros) = - - let doubleEnumNames0 = + + let doubleEnumNames0 = seq { for m in r.Modules do for tas in m.TypeAssignments do for t in GetMySelfAndChildren tas.Type do match t.Kind with - | Enumerated(itesm) -> - let names = itesm |> List.map(fun x -> lm.lg.getNamedItemBackendName0 x) + | Enumerated(items) -> + let names = items |> List.map(fun x -> lm.lg.getNamedItemBackendName0 x) yield! names - | _ -> () + | _ -> () for vas in m.ValueAssignments do - yield vas.Name.Value - } |> Seq.toList - - let doubleEnumNames = doubleEnumNames0@lm.lg.Keywords |> (List.keepDuplicates lm.lg.isCaseSensitive) + yield vas.Name.Value + } |> Seq.toList + + let doubleEnumNames = doubleEnumNames0@lm.lg.Keywords |> (List.keepDuplicates lm.lg.isCaseSensitive) match doubleEnumNames with | [] -> r | _ -> let CloneType (old:Asn1Type) m (key:list) (cons:Constructors) (state:State) = match old.Kind with - | Enumerated(itesm) -> + | Enumerated(items) -> let copyItem (old:NamedItem) = let newUniqueName = match state |> Seq.exists (lang.cmp (lm.lg.getNamedItemBackendName0 old)) with @@ -228,15 +228,15 @@ let rec private handleEnums (r:AstRoot) (renamePolicy:EnumRenamePolicy) ((lang, let newPrefix = key |> List.rev |> List.map ToC |> Seq.skipWhile(fun x -> (lm.lg.getNamedItemBackendName0 old).Contains x) |> Seq.head newPrefix + "_" + (lm.lg.getNamedItemBackendName0 old) lm.lg.setNamedItemBackendName0 old newUniqueName - let newItems = + let newItems = match renamePolicy with | AlwaysPrefixTypeName (* to be handled later when typedefname is known*) - | NoRenamePolicy -> itesm - | SelectiveEnumerants -> itesm|> List.map copyItem - | AllEnumerants -> - let newPrefix = itesm|> List.map copyItem |> List.map(fun itm -> (lm.lg.getNamedItemBackendName0 itm).Replace(ToC2 itm.Name.Value,"")) |> List.maxBy(fun prf -> prf.Length) - itesm|> - List.map(fun itm -> + | NoRenamePolicy -> items + | SelectiveEnumerants -> items |> List.map copyItem + | AllEnumerants -> + let newPrefix = items |> List.map copyItem |> List.map(fun itm -> (lm.lg.getNamedItemBackendName0 itm).Replace(ToC2 itm.Name.Value,"")) |> List.maxBy(fun prf -> prf.Length) + items|> + List.map(fun itm -> let oldName = lm.lg.getNamedItemBackendName0 itm let newName = newPrefix + oldName lm.lg.setNamedItemBackendName0 itm newName) @@ -250,7 +250,7 @@ let rec private handleEnums (r:AstRoot) (renamePolicy:EnumRenamePolicy) ((lang, let DoWork (ast:AstRoot) (lms:(ProgrammingLanguage*LanguageMacros) list) = let enumRenamePolicy = ast.args.renamePolicy - let r2 = + let r2 = match enumRenamePolicy with | AlwaysPrefixTypeName (* to be handled later when typedefname is known*) | NoRenamePolicy -> ast @@ -260,7 +260,7 @@ let DoWork (ast:AstRoot) (lms:(ProgrammingLanguage*LanguageMacros) list) = lms |> List.fold ( fun r z -> handleEnums r enumRenamePolicy z ) r1 match ast.args.fieldPrefix with | None -> r2 - | Some fldPrefixPolicy -> + | Some fldPrefixPolicy -> //let r3_c = handleSequencesAndChoices r2 ProgrammingLanguage.C fldPrefixPolicy //let r3_ada = handleSequencesAndChoices r3_c ProgrammingLanguage.Ada fldPrefixPolicy //let r3_scala = handleSequencesAndChoices r3_ada ProgrammingLanguage.Scala fldPrefixPolicy diff --git a/FrontEndAst/ExportToXml.fs b/FrontEndAst/ExportToXml.fs index 8e3d7b436..d96b2bc30 100644 --- a/FrontEndAst/ExportToXml.fs +++ b/FrontEndAst/ExportToXml.fs @@ -37,22 +37,22 @@ let private printBoolVal (v:bool) = XElement(xname "BooleanValue", v) let private printBitStringVal (v:BitStringValue,_) = XElement(xname "BitStringValue", v.Value) let private printOctetStringVal (v:OctetStringValue,_) = XElement(xname "OctetStringValue", (v |> List.map(fun b -> System.String.Format("{0:X2}", b.Value)) |> Seq.StrJoin "" )) -let rec private printSeqOfValue (v:SeqOfValue) = +let rec private printSeqOfValue (v:SeqOfValue) = XElement(xname "SequenceOfValue", (v |> List.map PrintAsn1GenericValue )) and private printSeqValue(v:SeqValue) = - XElement(xname "SequenceValue", - (v |> List.map(fun nv -> - XElement(xname "NamedValue", + XElement(xname "SequenceValue", + (v |> List.map(fun nv -> + XElement(xname "NamedValue", XAttribute(xname "Name", nv.name.Value), PrintAsn1GenericValue nv.Value )))) and private printChoiceValue (v:ChValue) = - XElement(xname "ChoiceValue", - ([v] |> List.map(fun nv -> - XElement(xname "NamedValue", + XElement(xname "ChoiceValue", + ([v] |> List.map(fun nv -> + XElement(xname "NamedValue", XAttribute(xname "Name", nv.name.Value), - PrintAsn1GenericValue nv.Value )))) -and private printObjectIdentifierValue (resCompList:CommonTypes.ResolvedObjectIdentifierValueCompoent list, compList:CommonTypes.ObjectIdentifierValueCompoent list) = - let printComponent (comp: CommonTypes.ObjectIdentifierValueCompoent) = + PrintAsn1GenericValue nv.Value )))) +and private printObjectIdentifierValue (resCompList:CommonTypes.ResolvedObjectIdentifierValueComponent list, compList:CommonTypes.ObjectIdentifierValueComponent list) = + let printComponent (comp: CommonTypes.ObjectIdentifierValueComponent) = match comp with | CommonTypes.ObjInteger nVal -> XElement(xname "ObjIdComponent", XAttribute(xname "IntValue", nVal.Value)) //integer form | CommonTypes.ObjNamedDefValue (label,(md,ts)) -> XElement(xname "ObjIdComponent", XAttribute(xname "label", label.Value), XAttribute(xname "Module", md.Value), XAttribute(xname "TypeAssignment", ts.Value)) //named form, points to an integer value @@ -61,14 +61,14 @@ and private printObjectIdentifierValue (resCompList:CommonTypes.ResolvedObjectId | CommonTypes.ObjDefinedValue (md,ts) -> XElement(xname "ObjIdComponent", XAttribute(xname "Module", md.Value), XAttribute(xname "TypeAssignment", ts.Value)) //value assignment to Integer value or ObjectIdentifier or RelativeObject XElement(xname "ObjectIdentifierValue", (compList |> List.map printComponent)) -and private printRefValue ((md:StringLoc,ts:StringLoc), v:Asn1Value) = - XElement(xname "ReferenceValue", +and private printRefValue ((md:StringLoc,ts:StringLoc), v:Asn1Value) = + XElement(xname "ReferenceValue", XAttribute(xname "Module", md.Value), XAttribute(xname "Name", ts.Value), XAttribute(xname "Line", ts.Location.srcLine), XAttribute(xname "CharPositionInLine", ts.Location.charPos), (PrintAsn1GenericValue v)) -and private PrintAsn1GenericValue (v:Asn1Value) = +and private PrintAsn1GenericValue (v:Asn1Value) = match v.kind with |IntegerValue(v) -> printIntVal v.Value |RealValue(v) -> printRealVal v.Value @@ -85,116 +85,116 @@ and private PrintAsn1GenericValue (v:Asn1Value) = |TimeValue dt -> XElement(xname "IntegerValue", dt.Value) |RefValue ((md,ts), v) -> printRefValue ((md,ts), v) -let private printGenericConstraint printValue (c:GenericConstraint<'v>) = +let private printGenericConstraint printValue (c:GenericConstraint<'v>) = foldGenericConstraint (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2) , s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> printValue v, s) - c + c 0 |> fst -let private printRangeConstraint0 (printValue:'v1->XElement) printValue2 (c:RangeTypeConstraint<'v1,'v2>) = +let private printRangeConstraint0 (printValue:'v1->XElement) printValue2 (c:RangeTypeConstraint<'v1,'v2>) = foldRangeTypeConstraint (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2), s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> printValue2 v,s) (fun _ v1 v2 b1 b2 s -> XElement(xname "Range", (XElement(xname "Min", (printValue v1))), (XElement(xname "Max", (printValue v2)))), s) (fun _ v1 b s -> XElement(xname "GT", (XElement(xname "Min", (printValue v1))) ),s ) (fun _ v2 b s -> XElement(xname "LT", (XElement(xname "Max", (printValue v2))) ), s) - c + c 0 |> fst -let private printRangeConstraint printValue (c:RangeTypeConstraint<'v1,'v1>) = - printRangeConstraint0 printValue printValue c +let private printRangeConstraint printValue (c:RangeTypeConstraint<'v1,'v1>) = + printRangeConstraint0 printValue printValue c -let private printSizableConstraint printValue (c:SizableTypeConstraint<'v>) = +let private printSizableConstraint printValue (c:SizableTypeConstraint<'v>) = foldSizableTypeConstraint2 (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2), s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> printValue v,s) - (fun _ sc s -> - let sizeCon = printRangeConstraint0 printUInt printUInt sc + (fun _ sc s -> + let sizeCon = printRangeConstraint0 printUInt printUInt sc XElement(xname "SIZE", sizeCon), s) - c + c 0 |> fst -let private printAlphaConstraint printValue (c:IA5StringConstraint) = +let private printAlphaConstraint printValue (c:IA5StringConstraint) = foldStringTypeConstraint2 (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2), s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> (printValue v),s) - (fun _ sc s -> - let sizeCon = printRangeConstraint0 printUInt printUInt sc + (fun _ sc s -> + let sizeCon = printRangeConstraint0 printUInt printUInt sc XElement(xname "SIZE", sizeCon), s) - (fun _ sc s -> - let alphaCon = printRangeConstraint0 printCharVal printStringVal sc + (fun _ sc s -> + let alphaCon = printRangeConstraint0 printCharVal printStringVal sc XElement(xname "ALPHA", alphaCon), s) - c + c 0 |> fst -let rec private printSequenceOfConstraint printValue (c:SequenceOfConstraint) = +let rec private printSequenceOfConstraint printValue (c:SequenceOfConstraint) = foldSequenceOfTypeConstraint2 (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2), s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> printValue v,s) - (fun _ sc s -> - let sizeCon = printRangeConstraint0 printUInt printUInt sc + (fun _ sc s -> + let sizeCon = printRangeConstraint0 printUInt printUInt sc XElement(xname "SIZE", sizeCon), s) - (fun _ c l s -> + (fun _ c l s -> XElement(xname "WithComponent", printAnyConstraint c), s) c 0 |> fst - -and private printSeqOrChoiceConstraint printValue (c:SeqOrChoiceConstraint<'v>) = + +and private printSeqOrChoiceConstraint printValue (c:SeqOrChoiceConstraint<'v>) = let printNamedConstaintItem (nc:NamedConstraint) = - let nc_mark = + let nc_mark = match nc.Mark with | Asn1Ast.MarkPresent -> XAttribute(xname "present", "always" ) | Asn1Ast.MarkAbsent -> XAttribute(xname "present", "never" ) | Asn1Ast.MarkOptional -> XAttribute(xname "present", "optional" ) | Asn1Ast.NoMark -> null - XElement(xname "WithComponent", + XElement(xname "WithComponent", XAttribute(xname "Name", nc.Name.Value), nc_mark, - (match nc.Contraint with + (match nc.Constraint with | None -> null | Some c -> printAnyConstraint c)) foldSeqOrChConstraint (fun _ r1 r2 b s -> XElement(xname "OR", r1, r2) , s) (fun _ r1 r2 s -> XElement(xname "AND", r1, r2) , s) - (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) + (fun _ r s -> XElement(xname "ALL_EXCEPT", r), s) (fun _ r1 r2 s -> XElement(xname "EXCEPT", r1, r2), s) - (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) + (fun _ r s -> XElement(xname "ROOTC_CONSTRAINT", r), s) (fun _ r1 r2 s -> XElement(xname "ROOTC_CONSTRAINT_WITH_EXTENSION", r1, r2), s) (fun _ v s -> printValue v, s) (fun _ nitms s -> XElement(xname withCompConstraintsTag, nitms |> List.map(printNamedConstaintItem )), s) - c + c 0 |> fst -and private printAnyConstraint (ac:AnyConstraint) : XElement = +and private printAnyConstraint (ac:AnyConstraint) : XElement = match ac with | IntegerTypeConstraint c -> XElement(xname "IntegerTypeConstraint", printRangeConstraint printIntVal c) | IA5StringConstraint c -> XElement(xname "IA5StringConstraint", printAlphaConstraint printStringVal c) @@ -226,49 +226,49 @@ let exportOptionality (opt:Asn1Optionality option) = match opt.acnPresentWhen, opt.defaultValue with | Some (PresenceWhenBool( RelativePath rp)), Some v -> [XAttribute(xname "Optional", "true" ); XAttribute(xname "present-when", (rp |> Seq.StrJoin ".") ); XElement(xname "Default",(PrintAsn1GenericValue v))] | Some (PresenceWhenBool( RelativePath rp)), None -> [XAttribute(xname "Optional", "true" ); XAttribute(xname "present-when", (rp |> Seq.StrJoin ".") )] - | Some (PresenceWhenBoolExpression acnExp), Some v -> + | Some (PresenceWhenBoolExpression acnExp), Some v -> let _, debugStr = AcnGenericCreateFromAntlr.printDebug acnExp [XAttribute(xname "Optional", "true" ); XAttribute(xname "present-when", debugStr ); XElement(xname "Default",(PrintAsn1GenericValue v))] - | Some (PresenceWhenBoolExpression acnExp), None -> + | Some (PresenceWhenBoolExpression acnExp), None -> let _, debugStr = AcnGenericCreateFromAntlr.printDebug acnExp [XAttribute(xname "Optional", "true" ); XAttribute(xname "present-when", debugStr )] | None, Some v -> [XElement(xname "Default",(PrintAsn1GenericValue v))] | None, None -> [XAttribute(xname "Optional", "true" );] - + let exportChoiceChildPresentWhenCondition (presentConditions:AcnPresentWhenConditionChoiceChild list) = - let attrValue (aa:AcnPresentWhenConditionChoiceChild) = + let attrValue (aa:AcnPresentWhenConditionChoiceChild) = match aa with - | PresenceInt (RelativePath path, intVal) -> (sprintf "%s = %A" (path |> Seq.StrJoin ".") intVal.Value) - | PresenceStr (RelativePath path, strVal) -> (sprintf "%s = %A" (path |> Seq.StrJoin ".") strVal.Value) + | PresenceInt (RelativePath path, intVal) -> (sprintf "%s = %A" (path |> Seq.StrJoin ".") intVal.Value) + | PresenceStr (RelativePath path, strVal) -> (sprintf "%s = %A" (path |> Seq.StrJoin ".") strVal.Value) match presentConditions with | [] -> null | _ -> let attrValue = presentConditions |> List.map attrValue |> Seq.StrJoin " " XAttribute(xname "present-when", attrValue) - + let exportAcnEndianness (a:AcnEndianness option) = match a with | (Some LittleEndianness) -> XAttribute(xname "endianness", "little" ) - | (Some BigEndianness) -> XAttribute(xname "endianness", "big" ) + | (Some BigEndianness) -> XAttribute(xname "endianness", "big" ) | None -> null -let exportAcnAligment (a:AcnAligment option) = +let exportAcnAlignment (a:AcnAlignment option) = match a with | Some NextByte -> XAttribute(xname "align-to-next", "byte" ) | Some NextWord -> XAttribute(xname "align-to-next", "word" ) | Some NextDWord -> XAttribute(xname "align-to-next", "dword" ) | None -> null -let exportAcnIntSizeProperty (a:AcnIntSizeProperty option) = +let exportAcnIntSizeProperty (a:AcnIntSizeProperty option) = match a with | None -> [] | Some (Fixed s) -> [XAttribute(xname "size", s )] | Some (IntNullTerminated b) -> [XAttribute(xname "size", "null-terminated" ); XAttribute(xname "termination-pattern", b )] let exportAcnIntEncoding (a:AcnIntEncoding option) = - match a with + match a with | Some PosInt -> [XAttribute(xname "encoding", "pos-int" )] | Some TwosComplement -> [XAttribute(xname "encoding", "twos-complement" )] | Some IntAscii -> [XAttribute(xname "encoding", "ASCII" )] @@ -276,12 +276,12 @@ let exportAcnIntEncoding (a:AcnIntEncoding option) = | None -> [] let exportAcnRealEncoding (a:AcnRealEncoding option) = - match a with + match a with | Some IEEE754_32 -> [XAttribute(xname "encoding", "IEEE754-1985-32" )] | Some IEEE754_64 -> [XAttribute(xname "encoding", "IEEE754-1985-64" )] | None -> [] -let exportAcnStringEncoding (a:AcnStringEncoding option) = +let exportAcnStringEncoding (a:AcnStringEncoding option) = match a with | Some StrAscii -> [XAttribute(xname "encoding", "ASCII" )] | None -> [] @@ -291,13 +291,13 @@ let exportAcnStringSizeProperty (a:AcnStringSizeProperty option) = | Some (StrNullTerminated b) -> [XAttribute(xname "size", "null-terminated" ); XAttribute(xname "termination-pattern", b )] | None -> [] -let exportSizeableSizeProp (a:AcnSizeableSizeProperty option) = +let exportSizeableSizeProp (a:AcnSizeableSizeProperty option) = match a with | Some (SzExternalField (RelativePath path)) -> [XAttribute(xname "size", (path |> Seq.StrJoin ".") )] | Some (SzNullTerminated bitPattern) -> [XAttribute(xname "size", ("null-terminated") ); XAttribute(xname "termination-pattern", (bitPattern.Value) )] | None -> [] -let exportChoiceDeterminant (a:RelativePath option) = +let exportChoiceDeterminant (a:RelativePath option) = match a with | Some (RelativePath path) -> [XAttribute(xname "determinant", (path |> Seq.StrJoin ".") )] | None -> [] @@ -316,24 +316,24 @@ let exportAcnNullType (a:PATTERN_PROP_VALUE option) = | None -> [] | Some (AcnGenericTypes.PATTERN_PROP_BITSTR_VALUE pat) -> [XAttribute(xname "pattern", pat.Value )] | Some (AcnGenericTypes.PATTERN_PROP_OCTSTR_VALUE v) -> [XAttribute(xname "pattern", (v |> List.map(fun b -> System.String.Format("{0:X2}", b.Value)) |> Seq.StrJoin "" ) )] - + let exportAcnParameter (a:AcnParameter) = - XElement(xname "AcnParameter", + XElement(xname "AcnParameter", XAttribute(xname "Id", a.id.AsString), XAttribute(xname "Name", a.name), - XAttribute(xname "Type", (a.asn1Type.ToString()))) + XAttribute(xname "Type", (a.asn1Type.ToString()))) let exportReferenceTypeArg (inh:CommonTypes.InheritanceInfo option)= match inh with | None -> [] | Some ref -> [XAttribute(xname "Module", ref.modName); XAttribute(xname "TypeAssignment", ref.tasName)] - + let foo (t:Asn1Type) = - t.FT_TypeDefintion.[CommonTypes.C].kind + t.FT_TypeDefinition.[CommonTypes.C].kind -let private exportType (t:Asn1Type) = +let private exportType (t:Asn1Type) = Asn1Fold.foldType - (fun ti us -> + (fun ti us -> XElement(xname "INTEGER", (XAttribute(xname "acnMaxSizeInBits", ti.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ti.acnMinSizeInBits )), @@ -384,12 +384,12 @@ let private exportType (t:Asn1Type) = XElement(xname constraintsTag, ti.cons |> List.map(printSizableConstraint printOctetStringVal )), XElement(xname withCompConstraintsTag, ti.withcons |> List.map(printSizableConstraint printOctetStringVal )) ), us ) - (fun ti us -> XElement(xname "TIME", + (fun ti us -> XElement(xname "TIME", (XAttribute(xname "acnMaxSizeInBits", ti.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ti.acnMinSizeInBits )), (XAttribute(xname "uperMaxSizeInBits", ti.uperMaxSizeInBits )), (XAttribute(xname "uperMinSizeInBits", ti.uperMinSizeInBits ))), us) - (fun ti us -> XElement(xname "NULL", + (fun ti us -> XElement(xname "NULL", (XAttribute(xname "acnMaxSizeInBits", ti.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ti.acnMinSizeInBits )), (XAttribute(xname "uperMaxSizeInBits", ti.uperMaxSizeInBits )), @@ -412,7 +412,7 @@ let private exportType (t:Asn1Type) = (exportAcnBooleanEncoding ti.acnProperties.encodingPattern), XElement(xname constraintsTag, ti.cons |> List.map(printGenericConstraint printBoolVal )), XElement(xname withCompConstraintsTag, ti.withcons |> List.map(printGenericConstraint printBoolVal )) - ), us ) + ), us ) (fun ti us -> XElement(xname "ENUMERATED", (XAttribute(xname "acnMaxSizeInBits", ti.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ti.acnMinSizeInBits )), @@ -422,13 +422,13 @@ let private exportType (t:Asn1Type) = (exportAcnIntSizeProperty ti.acnProperties.sizeProp), (exportAcnIntEncoding ti.acnProperties.encodingProp), (XAttribute(xname "encode-values", ti.encodeValues)), - XElement(xname "Items", ti.items |> List.map(fun c -> - XElement(xname "Item", - XAttribute(xname "Name", c.Name.Value), - XAttribute(xname "CName", c.c_name), - XAttribute(xname "ScalaName", c.scala_name), - XAttribute(xname "AdaName", c.ada_name), - XAttribute(xname "Value", c.definitionValue), + XElement(xname "Items", ti.items |> List.map(fun c -> + XElement(xname "Item", + XAttribute(xname "Name", c.Name.Value), + XAttribute(xname "CName", c.c_name), + XAttribute(xname "ScalaName", c.scala_name), + XAttribute(xname "AdaName", c.ada_name), + XAttribute(xname "Value", c.definitionValue), XAttribute(xname "Line", c.Name.Location.srcLine), XAttribute(xname "acnEncodeValue", c.acnEncodeValue), @@ -472,72 +472,72 @@ let private exportType (t:Asn1Type) = (if ch.asn1Comments.Length > 0 then (XElement (xname "AsnComment", (ch.asn1Comments |> Seq.StrJoin "\n"))) else null), (if ch.acnComments.Length > 0 then (XElement (xname "AcnComment", (ch.acnComments |> Seq.StrJoin "\n"))) else null), nt), us ) - (fun ch us -> + (fun ch us -> match ch.Type with - | AcnInteger (a) -> - XElement(xname "ACN_COMPONENT", + | AcnInteger (a) -> + XElement(xname "ACN_COMPONENT", XAttribute(xname "Id", ch.id.AsString), XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "Type", "INTEGER"), + XAttribute(xname "Type", "INTEGER"), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )), (exportReferenceTypeArg a.inheritInfo), (exportAcnEndianness a.acnProperties.endiannessProp), (exportAcnIntSizeProperty a.acnProperties.sizeProp), (exportAcnIntEncoding a.acnProperties.encodingProp), - (exportAcnAligment a.acnAligment), - (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null)), us - | AcnNullType (a) -> - XElement(xname "ACN_COMPONENT", + (exportAcnAlignment a.acnAlignment), + (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null)), us + | AcnNullType (a) -> + XElement(xname "ACN_COMPONENT", XAttribute(xname "Id", ch.id.AsString), XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "Type", "NULL"), + XAttribute(xname "Type", "NULL"), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )), (exportAcnNullType a.acnProperties.encodingPattern), - (exportAcnAligment a.acnAligment), - (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null)), us + (exportAcnAlignment a.acnAlignment), + (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null)), us - | AcnReferenceToEnumerated (a) -> - XElement(xname "ACN_COMPONENT", + | AcnReferenceToEnumerated (a) -> + XElement(xname "ACN_COMPONENT", XAttribute(xname "Id", ch.id.AsString), XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "Type", "ENUMERATED"), + XAttribute(xname "Type", "ENUMERATED"), XAttribute(xname "Module", a.modName.Value), XAttribute(xname "TypeAssignment", a.tasName.Value), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )), - (exportAcnAligment a.acnAligment), + (exportAcnAlignment a.acnAlignment), (exportAcnEndianness a.enumerated.acnProperties.endiannessProp), (exportAcnIntSizeProperty a.enumerated.acnProperties.sizeProp), (exportAcnIntEncoding a.enumerated.acnProperties.encodingProp), (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null), XElement(xname "Items", a.enumerated.items |> List.map(fun c -> XElement(xname "Item", XAttribute(xname "Name", c.Name.Value), XAttribute(xname "Value", c.definitionValue)) )), XElement(xname constraintsTag, a.enumerated.cons |> List.map(printGenericConstraint printEnumVal )), - XElement(xname withCompConstraintsTag, a.enumerated.withcons |> List.map(printGenericConstraint printEnumVal )) ), us + XElement(xname withCompConstraintsTag, a.enumerated.withcons |> List.map(printGenericConstraint printEnumVal )) ), us - | AcnReferenceToIA5String (a) -> - XElement(xname "ACN_COMPONENT", + | AcnReferenceToIA5String (a) -> + XElement(xname "ACN_COMPONENT", XAttribute(xname "Id", ch.id.AsString), XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "Type", "IA5String"), + XAttribute(xname "Type", "IA5String"), XAttribute(xname "Module", a.modName.Value), XAttribute(xname "TypeAssignment", a.tasName.Value), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )), - (exportAcnAligment a.acnAligment), - (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null) ), us + (exportAcnAlignment a.acnAlignment), + (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null) ), us - | AcnBoolean (a) -> - XElement(xname "ACN_COMPONENT", + | AcnBoolean (a) -> + XElement(xname "ACN_COMPONENT", XAttribute(xname "Id", ch.id.AsString), XAttribute(xname "Name", ch.Name.Value), - XAttribute(xname "Type", "BOOLEAN"), + XAttribute(xname "Type", "BOOLEAN"), (XAttribute(xname "acnMaxSizeInBits", ch.Type.acnMaxSizeInBits )), (XAttribute(xname "acnMinSizeInBits", ch.Type.acnMinSizeInBits )), (exportAcnBooleanEncoding a.acnProperties.encodingPattern), - (exportAcnAligment a.acnAligment), + (exportAcnAlignment a.acnAlignment), (if ch.Comments.Length > 0 then (XElement (xname "AcnComment", (ch.Comments |> Seq.StrJoin "\n"))) else null)), us ) (fun ti children us -> XElement(xname "CHOICE", (XAttribute(xname "acnMaxSizeInBits", ti.acnMaxSizeInBits )), @@ -574,7 +574,7 @@ let private exportType (t:Asn1Type) = | args -> [XElement(xname "AcnArguments", (args |> List.map exprtRefTypeArgument) )]), nt), us ) (fun t nk us -> XElement(xname "Asn1Type", - XAttribute(xname "TD", t.FT_TypeDefintion.[CommonTypes.C].kind), + XAttribute(xname "TD", t.FT_TypeDefinition.[CommonTypes.C].kind), XAttribute(xname "id", t.id.AsString), XAttribute(xname "Line", t.Location.srcLine), XAttribute(xname "CharPositionInLine", t.Location.charPos), @@ -594,7 +594,7 @@ let private exportType (t:Asn1Type) = XAttribute(xname "File", loc.srcFilename), XAttribute(xname "Line", loc.srcLine), XAttribute(xname "CharPositionInLine", loc.charPos))), - (exportAcnAligment t.acnAligment), + (exportAcnAlignment t.acnAlignment), (match t.acnParameters with | [] -> [] | prms -> [XElement(xname "AcnParameters", (prms|> List.map exportAcnParameter) )]), @@ -607,9 +607,9 @@ let private exportType (t:Asn1Type) = let private exportTas (tas:TypeAssignment) = XElement(xname "TypeAssignment", XAttribute(xname "Name", tas.Name.Value), - XAttribute(xname "CName", tas.Type.FT_TypeDefintion.[CommonTypes.C].typeName), - XAttribute(xname "ScalaName", tas.Type.FT_TypeDefintion.[CommonTypes.Scala].typeName), - XAttribute(xname "AdaName", tas.Type.FT_TypeDefintion.[CommonTypes.Ada].typeName), + XAttribute(xname "CName", tas.Type.FT_TypeDefinition.[CommonTypes.C].typeName), + XAttribute(xname "ScalaName", tas.Type.FT_TypeDefinition.[CommonTypes.Scala].typeName), + XAttribute(xname "AdaName", tas.Type.FT_TypeDefinition.[CommonTypes.Ada].typeName), XAttribute(xname "Line", tas.Name.Location.srcLine), XAttribute(xname "CharPositionInLine", tas.Name.Location.charPos), (if tas.asn1Comments.Length > 0 then (XElement (xname "AsnComment", (tas.asn1Comments |> Seq.StrJoin "\n"))) else null), @@ -654,16 +654,16 @@ let private exportModule (m:Asn1Module) = ) let private exportAcnDependencyKind (d:AcnDependencyKind) = - match d with + match d with | AcnDepIA5StringSizeDeterminant _ -> XElement(xname "SizeDependency") | AcnDepSizeDeterminant _ -> XElement(xname "SizeDependency") | AcnDepRefTypeArgument prm -> XElement(xname "RefTypeArgumentDependency", XAttribute(xname "prmId", prm.id.AsString)) | AcnDepPresenceBool -> XElement(xname "PresenceBoolDependency") | AcnDepPresence _ -> XElement(xname "ChoicePresenceDependency") | AcnDepPresenceStr _ -> XElement(xname "ChoicePresenceStrDependency") - | AcnDepChoiceDeteterminant _ -> XElement(xname "ChoiceEnumDependency") - | AcnDepSizeDeterminant_bit_oct_str_containt _ -> XElement(xname "SizeDependency2") - + | AcnDepChoiceDeterminant _ -> XElement(xname "ChoiceEnumDependency") + | AcnDepSizeDeterminant_bit_oct_str_contain _ -> XElement(xname "SizeDependency2") + let private exportAcnDependency (d:AcnDependency) = XElement(xname "AcnDependency", XAttribute(xname "Asn1TypeID", d.asn1Type.AsString), @@ -701,16 +701,16 @@ let exportFile (r:AstRoot) (deps:AcnInsertedFieldDependencies) (fileName:string) let doc =new XDocument(dec) doc.AddFirst wsRoot doc.Save(fileName) - let getResourceAsString (rsName:string) = + let getResourceAsString (rsName:string) = FsUtils.getResourceAsString0 "FrontEndAst" (System.Reflection.Assembly.GetExecutingAssembly ()) rsName let schema = getResourceAsString customWsSchemaLocation - + let outDir = Path.GetDirectoryName fileName - writeTextFile (Path.Combine(outDir, customWsSchemaLocation)) schema + writeTextFile (Path.Combine(outDir, customWsSchemaLocation)) schema //try to open the document. //if there are errors, it will stop FsUtils.loadXmlFile ValidationType.Schema fileName |> ignore - + () diff --git a/FrontEndAst/FE_TypeDefinition.fs b/FrontEndAst/FE_TypeDefinition.fs index 2a04c2bbb..3c3fe0d13 100644 --- a/FrontEndAst/FE_TypeDefinition.fs +++ b/FrontEndAst/FE_TypeDefinition.fs @@ -16,13 +16,13 @@ open Asn1AcnAst let private reserveTypeDefinitionName (typePrefix:string) (allocatedTypeNames : (ProgrammingLanguage*string*string) list) (l:ProgrammingLanguage) (programUnit:string) (proposedTypeDefName:string) = let getNextCount (oldName:string) = match oldName.Split('_') |> Seq.toList |> List.rev with - | [] + | [] | _::[] -> oldName + "_1" | curN::oldPart -> match Int32.TryParse curN with | true, num -> (oldPart |> List.rev |> Seq.StrJoin "_") + "_" + ((num+1).ToString()) | _ -> oldName + "_1" - let rec getValidTypeDefname (proposedTypeDefName:string) = + let rec getValidTypeDefname (proposedTypeDefName:string) = let keywords = l.keywords let cmp (l:ProgrammingLanguage) (s1:String) (s2:String) = l.cmp s1 s2 @@ -32,23 +32,23 @@ let private reserveTypeDefinitionName (typePrefix:string) (allocatedTypeNames : | Some _ -> getNextCount proposedTypeDefName match l.OnTypeNameConflictTryAppendModName with - | true -> + | true -> match allocatedTypeNames |> Seq.exists(fun (cl, _, ct) -> cl = l && ct = proposedTypeDefName) with | false -> proposedTypeDefName - | true -> + | true -> match allocatedTypeNames |> Seq.exists(fun (cl, cp, ct) -> cl = l && cp = programUnit && ct = proposedTypeDefName) with - | false -> + | false -> match proposedTypeDefName.StartsWith typePrefix with - | true -> getValidTypeDefname (typePrefix + programUnit + "_" + proposedTypeDefName.Substring(typePrefix.Length) ) - | false -> getValidTypeDefname (programUnit + "_" + proposedTypeDefName ) - | true -> getValidTypeDefname (getNextCount proposedTypeDefName ) - | false -> + | true -> getValidTypeDefname (typePrefix + programUnit + "_" + proposedTypeDefName.Substring(typePrefix.Length) ) + | false -> getValidTypeDefname (programUnit + "_" + proposedTypeDefName ) + | true -> getValidTypeDefname (getNextCount proposedTypeDefName ) + | false -> match allocatedTypeNames |> Seq.exists(fun (cl, cp, ct) -> cl = l && cp.ToUpper() = programUnit.ToUpper() && ct.ToUpper() = proposedTypeDefName.ToUpper()) with | false -> proposedTypeDefName - | true -> getValidTypeDefname (getNextCount proposedTypeDefName ) - - let validTypeDefname = getValidTypeDefname proposedTypeDefName - + | true -> getValidTypeDefname (getNextCount proposedTypeDefName ) + + let validTypeDefname = getValidTypeDefname proposedTypeDefName + validTypeDefname, (l, programUnit, validTypeDefname)::allocatedTypeNames @@ -60,18 +60,18 @@ let private reserveMasterTypeDefinitionName (us:Asn1AcnMergeState) (id:Reference //returns the proposed type definition name, does not change the current state let getProposedTypeDefName (us:Asn1AcnMergeState) l (id:ReferenceToType) = - let lastNodeName, asn1LastName = + let lastNodeName, asn1LastName = match id with - | ReferenceToType path -> + | ReferenceToType path -> match path |> List.rev |> List.head with - | SEQ_CHILD name -> name, name + | SEQ_CHILD (name, _) -> name, name | CH_CHILD (name,_,_) -> name, name | TA name -> us.args.TypePrefix + name, name | SQF -> "elem", "elem" | _ -> raise (BugErrorException "error in lastitem") let parentDef = match id with - | ReferenceToType refIdNodes -> + | ReferenceToType refIdNodes -> match refIdNodes with | (MD modName)::(TA tasName)::[] -> None | (MD modName)::(TA tasName)::_ -> @@ -87,15 +87,15 @@ let getProposedTypeDefName (us:Asn1AcnMergeState) l (id:ReferenceToType) = let temporaryRegisterTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) programUnit proposedTypeDefName : (string*Asn1AcnMergeState)= let typeName, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix us.allocatedTypeNames l programUnit proposedTypeDefName typeName, {us with allocatedTypeNames = newAllocatedTypeNames; temporaryTypesAllocation = us.temporaryTypesAllocation.Add((l,id), typeName)} - -/// Register the typeId + +/// Register the typeId let rec registerPrimitiveTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) getRtlDefinitionFunc : (FE_PrimitiveTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_PrimitiveTypeDefinition v) -> + | Some (FE_PrimitiveTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | PrimitiveNewSubTypeDefinition _ -> v, us | _ -> @@ -107,13 +107,13 @@ let rec registerPrimitiveTypeDefinition (us:Asn1AcnMergeState) l (id : Reference itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_PrimitiveTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with - | FEI_Reference2RTL -> + | FEI_Reference2RTL -> match getRtlDefinitionFunc with | None -> raise(BugErrorException "kind is FE_Reference2RTL but no getRtlDefinitionFunc was provided") - | Some fnc -> + | Some fnc -> let programUnit, typeName, asn1Name = fnc l {FE_PrimitiveTypeDefinition.programUnit = programUnit; typeName = typeName; kind=PrimitiveReference2RTL; asn1Name = asn1Name; asn1Module = None} , us | FEI_NewTypeDefinition -> @@ -127,13 +127,13 @@ let rec registerPrimitiveTypeDefinition (us:Asn1AcnMergeState) l (id : Reference let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName us id l programUnit proposedTypeDefName let itm = {FE_PrimitiveTypeDefinition.programUnit = programUnit; typeName = typeName; kind=(PrimitiveNewSubTypeDefinition subType); asn1Name = asn1Name; asn1Module = Some id.ModName } itm, {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_PrimitiveTypeDefinition itm))} - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when let actDef, ns = registerPrimitiveTypeDefinition us l refId FEI_NewTypeDefinition getRtlDefinitionFunc let itm = {actDef with kind = PrimitiveReference2OtherType} itm, ns //itm, {ns with allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_PrimitiveTypeDefinition itm))} - + ret, ns @@ -141,21 +141,21 @@ let rec registerPrimitiveTypeDefinition (us:Asn1AcnMergeState) l (id : Reference let rec registerStringTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) : (FE_StringTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_StringTypeDefinition v) -> + | Some (FE_StringTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | NonPrimitiveNewSubTypeDefinition _ -> v, us | _ -> // fix early main type allocation - let subType, ns1 = registerStringTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerStringTypeDefinition us l subId FEI_NewTypeDefinition let newMap = ns1.allocatedFE_TypeDefinition.Remove (l,id) let itm = {v with kind = (NonPrimitiveNewSubTypeDefinition subType)} itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_StringTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with | FEI_Reference2RTL -> raise(BugErrorException "String types are not defined in RTL") @@ -170,7 +170,7 @@ let rec registerStringTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let itm = {FE_StringTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; encoding_range=encoding_range; index=index; alpha_set=alpha_set; alpha=alpha; alpha_index=alpha_index} itm, {us with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_StringTypeDefinition itm))} | FEI_NewSubTypeDefinition subId -> - let subType, ns1 = registerStringTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerStringTypeDefinition us l subId FEI_NewTypeDefinition let proposedTypeDefName, asn1Name = getProposedTypeDefName ns1 l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName ns1 id l programUnit proposedTypeDefName let encoding_range, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_alpha_index") @@ -181,9 +181,9 @@ let rec registerStringTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let itm = {FE_StringTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); encoding_range=encoding_range; index=index; alpha_set=alpha_set; alpha=alpha; alpha_index=alpha_index} let ns2 = {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_StringTypeDefinition itm))} itm, ns2 - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when - let actDef, ns = registerStringTypeDefinition us l refId FEI_NewTypeDefinition + let actDef, ns = registerStringTypeDefinition us l refId FEI_NewTypeDefinition let itm = {actDef with kind = NonPrimitiveReference2OtherType} itm, ns ret, ns @@ -193,20 +193,20 @@ let rec registerStringTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let rec registerSizeableTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) : (FE_SizeableTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_SizeableTypeDefinition v) -> + | Some (FE_SizeableTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | NonPrimitiveNewSubTypeDefinition _ -> v, us | _ -> // fix early main type allocation - let subType, ns1 = registerSizeableTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerSizeableTypeDefinition us l subId FEI_NewTypeDefinition let newMap = ns1.allocatedFE_TypeDefinition.Remove (l,id) let itm = {v with kind = (NonPrimitiveNewSubTypeDefinition subType)} itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_SizeableTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with | FEI_Reference2RTL -> raise(BugErrorException "String types are not defined in RTL") @@ -219,7 +219,7 @@ let rec registerSizeableTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceT let itm = {FE_SizeableTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; index=index; array=array; length_index=length_index} itm, {us with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_SizeableTypeDefinition itm))} | FEI_NewSubTypeDefinition subId -> - let subType, ns1 = registerSizeableTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerSizeableTypeDefinition us l subId FEI_NewTypeDefinition let proposedTypeDefName, asn1Name = getProposedTypeDefName ns1 l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName ns1 id l programUnit proposedTypeDefName let index, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_index") @@ -228,9 +228,9 @@ let rec registerSizeableTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceT let itm = {FE_SizeableTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); index=index; array=array; length_index=length_index} let ns2 = {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_SizeableTypeDefinition itm))} itm, ns2 - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when - let actDef, ns = registerSizeableTypeDefinition us l refId FEI_NewTypeDefinition + let actDef, ns = registerSizeableTypeDefinition us l refId FEI_NewTypeDefinition let itm = {actDef with kind = NonPrimitiveReference2OtherType} itm, ns ret, ns @@ -240,20 +240,20 @@ let rec registerSizeableTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceT let rec registerSequenceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) : (FE_SequenceTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_SequenceTypeDefinition v) -> + | Some (FE_SequenceTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | NonPrimitiveNewSubTypeDefinition _ -> v, us | _ -> // fix early main type allocation - let subType, ns1 = registerSequenceTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerSequenceTypeDefinition us l subId FEI_NewTypeDefinition let newMap = ns1.allocatedFE_TypeDefinition.Remove (l,id) let itm = {v with kind = (NonPrimitiveNewSubTypeDefinition subType)} itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_SequenceTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with | FEI_Reference2RTL -> raise(BugErrorException "String types are not defined in RTL") @@ -261,23 +261,23 @@ let rec registerSequenceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceT let proposedTypeDefName, asn1Name = getProposedTypeDefName us l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName us id l programUnit proposedTypeDefName let exist, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_exist") - let extention_function_potisions, newAllocatedTypeNames = + let extension_function_positions, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_extension_function_positions") - let itm = {FE_SequenceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; exist=exist; extention_function_potisions=extention_function_potisions} + let itm = {FE_SequenceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; exist=exist; extension_function_positions=extension_function_positions} itm, {us with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_SequenceTypeDefinition itm))} | FEI_NewSubTypeDefinition subId -> - let subType, ns1 = registerSequenceTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerSequenceTypeDefinition us l subId FEI_NewTypeDefinition let proposedTypeDefName, asn1Name = getProposedTypeDefName ns1 l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName ns1 id l programUnit proposedTypeDefName let exist, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_exist") - let extention_function_potisions, newAllocatedTypeNames = + let extension_function_positions, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_extension_function_positions") - let itm = {FE_SequenceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); exist=exist; extention_function_potisions=extention_function_potisions} + let itm = {FE_SequenceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); exist=exist; extension_function_positions=extension_function_positions} let ns2 = {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_SequenceTypeDefinition itm))} itm, ns2 - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when - let actDef, ns = registerSequenceTypeDefinition us l refId FEI_NewTypeDefinition + let actDef, ns = registerSequenceTypeDefinition us l refId FEI_NewTypeDefinition let itm = {actDef with kind = NonPrimitiveReference2OtherType} itm, ns ret, ns @@ -286,20 +286,20 @@ let rec registerSequenceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceT let rec registerChoiceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) : (FE_ChoiceTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_ChoiceTypeDefinition v) -> + | Some (FE_ChoiceTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | NonPrimitiveNewSubTypeDefinition _ -> v, us | _ -> // fix early main type allocation - let subType, ns1 = registerChoiceTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerChoiceTypeDefinition us l subId FEI_NewTypeDefinition let newMap = ns1.allocatedFE_TypeDefinition.Remove (l,id) let itm = {v with kind = (NonPrimitiveNewSubTypeDefinition subType)} itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_ChoiceTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with | FEI_Reference2RTL -> raise(BugErrorException "String types are not defined in RTL") @@ -312,7 +312,7 @@ let rec registerChoiceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let itm = {FE_ChoiceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; index_range=index_range; selection=selection; union_name=union_name} itm, {us with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_ChoiceTypeDefinition itm))} | FEI_NewSubTypeDefinition subId -> - let subType, ns1 = registerChoiceTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerChoiceTypeDefinition us l subId FEI_NewTypeDefinition let proposedTypeDefName, asn1Name = getProposedTypeDefName ns1 l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName ns1 id l programUnit proposedTypeDefName let index_range, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_index_range") @@ -321,9 +321,9 @@ let rec registerChoiceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let itm = {FE_ChoiceTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); index_range=index_range; selection=selection; union_name=union_name} let ns2 = {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_ChoiceTypeDefinition itm))} itm, ns2 - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when - let actDef, ns = registerChoiceTypeDefinition us l refId FEI_NewTypeDefinition + let actDef, ns = registerChoiceTypeDefinition us l refId FEI_NewTypeDefinition let itm = {actDef with kind = NonPrimitiveReference2OtherType} itm, ns ret, ns @@ -332,20 +332,20 @@ let rec registerChoiceTypeDefinition (us:Asn1AcnMergeState) l (id : ReferenceToT let rec registerEnumeratedTypeDefinition (us:Asn1AcnMergeState) (l:ProgrammingLanguage) (id : ReferenceToType) (kind : FE_TypeDefinitionKindInternal) : (FE_EnumeratedTypeDefinition*Asn1AcnMergeState)= let programUnit = ToC id.ModName match us.allocatedFE_TypeDefinition |> Map.tryFind(l,id) with - | Some (FE_EnumeratedTypeDefinition v) -> + | Some (FE_EnumeratedTypeDefinition v) -> match kind with - | FEI_NewSubTypeDefinition subId -> + | FEI_NewSubTypeDefinition subId -> match v.kind with | NonPrimitiveNewSubTypeDefinition _ -> v, us | _ -> // fix early main type allocation - let subType, ns1 = registerEnumeratedTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerEnumeratedTypeDefinition us l subId FEI_NewTypeDefinition let newMap = ns1.allocatedFE_TypeDefinition.Remove (l,id) let itm = {v with kind = (NonPrimitiveNewSubTypeDefinition subType)} itm, {ns1 with allocatedFE_TypeDefinition = newMap.Add((l,id),(FE_EnumeratedTypeDefinition itm))} | _ -> v, us | Some (_) -> raise (BugErrorException "bug in registerPrimitiveTypeDefinition") - | None -> + | None -> let ret, ns = match kind with | FEI_Reference2RTL -> raise(BugErrorException "String types are not defined in RTL") @@ -356,16 +356,16 @@ let rec registerEnumeratedTypeDefinition (us:Asn1AcnMergeState) (l:ProgrammingLa let itm = {FE_EnumeratedTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=NonPrimitiveNewTypeDefinition; index_range=index_range} itm, {us with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = us.allocatedFE_TypeDefinition.Add((l,id), (FE_EnumeratedTypeDefinition itm))} | FEI_NewSubTypeDefinition subId -> - let subType, ns1 = registerEnumeratedTypeDefinition us l subId FEI_NewTypeDefinition + let subType, ns1 = registerEnumeratedTypeDefinition us l subId FEI_NewTypeDefinition let proposedTypeDefName, asn1Name = getProposedTypeDefName ns1 l id let typeName, newAllocatedTypeNames = reserveMasterTypeDefinitionName ns1 id l programUnit proposedTypeDefName let index_range, newAllocatedTypeNames = reserveTypeDefinitionName us.args.TypePrefix newAllocatedTypeNames l programUnit (proposedTypeDefName + "_index_range") let itm = {FE_EnumeratedTypeDefinition.programUnit = programUnit; typeName = typeName; asn1Name = asn1Name; asn1Module = Some id.ModName; kind=(NonPrimitiveNewSubTypeDefinition subType); index_range=index_range} let ns2 = {ns1 with allocatedTypeNames = newAllocatedTypeNames; allocatedFE_TypeDefinition = ns1.allocatedFE_TypeDefinition.Add((l,id), (FE_EnumeratedTypeDefinition itm))} itm, ns2 - | FEI_Reference2OtherType refId -> + | FEI_Reference2OtherType refId -> // initially we register the base type as FE_NewTypeDefinition. It may a be FE_NewSubTypeDefinition though. This will be corrected when - let actDef, ns = registerEnumeratedTypeDefinition us l refId FEI_NewTypeDefinition + let actDef, ns = registerEnumeratedTypeDefinition us l refId FEI_NewTypeDefinition let itm = {actDef with kind = NonPrimitiveReference2OtherType} itm, ns ret, ns @@ -389,42 +389,42 @@ let rec registerAnyTypeDefinition (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (u | Asn1Ast.ReferenceType _ -> raise(BugErrorException "registerAnyTypeDefinition") *) -type GetTypeDifition_arg = { +type GetTypeDefinition_arg = { asn1TypeKind : Asn1Ast.Asn1TypeKind - loc:SrcLoc - curPath : ScopeNode list + loc:SrcLoc + curPath : ScopeNode list typeDefPath : ScopeNode list enmItemTypeDefPath : ScopeNode list - inferitInfo : InheritanceInfo option + inheritInfo : InheritanceInfo option typeAssignmentInfo : AssignmentInfo option rtlFnc : (ProgrammingLanguage -> (string*string*string)) option - + } -let getTypedefKind (arg:GetTypeDifition_arg) = +let getTypedefKind (arg:GetTypeDefinition_arg) = // first check if the type id is under a value assignment or type assignment match arg.curPath with - | (MD _)::(VA _)::_ -> + | (MD _)::(VA _)::_ -> //value assignment: The possible results are either reference to RTL or reference to other type (i.e. new types cannot be defined here) //There is a case where the typeDefPath is not correct (top level value assignments) to primitive types (see the mergeValueAssignment) match arg.typeDefPath with - | (MD _)::(VA _)::_ -> + | (MD _)::(VA _)::_ -> match arg.asn1TypeKind with | Asn1Ast.Integer | Asn1Ast.Real | Asn1Ast.NullType | Asn1Ast.Boolean -> FEI_Reference2RTL | _ -> raise(SemanticError(arg.loc, "Unnamed types are not supported in value assignments" )) - | _ -> - match arg.curPath.Length > 2 && arg.rtlFnc.IsSome && arg.inferitInfo.IsNone with + | _ -> + match arg.curPath.Length > 2 && arg.rtlFnc.IsSome && arg.inheritInfo.IsNone with | true -> FEI_Reference2RTL | false -> FEI_Reference2OtherType (ReferenceToType arg.typeDefPath) | _ -> // type under a type assignment // when curPath = typeDefPath then in most case it means a new type definition (or new subtype definition). - // however if curpath is greater than 2 (i.e. child type) and type has rtlFnc then it a reference to RTL + // however if curpath is greater than 2 (i.e. child type) and type has rtlFnc then it a reference to RTL match arg.curPath = arg.typeDefPath with | true -> - match arg.inferitInfo with - | None -> + match arg.inheritInfo with + | None -> match arg.curPath.Length > 2 && arg.rtlFnc.IsSome with | true -> FEI_Reference2RTL | false -> FEI_NewTypeDefinition @@ -432,93 +432,93 @@ let getTypedefKind (arg:GetTypeDifition_arg) = | false -> //In this case the curPath is different to typedefPath. //Normally this is a reference to another type. However, there are two exceptions - // (a) if type is child type and rtlFnc is some and inferitInfo.IsNone then is reference to RTL (instead of reference to other type) + // (a) if type is child type and rtlFnc is some and inheritInfo.IsNone then is reference to RTL (instead of reference to other type) // (b) if this type is type assignment (the case is A::=B) then we must define a new type (A) which has a subtype (B) match arg.typeAssignmentInfo with - | Some (ValueAssignmentInfo _) - | None -> - match arg.curPath.Length > 2 && arg.rtlFnc.IsSome && arg.inferitInfo.IsNone with + | Some (ValueAssignmentInfo _) + | None -> + match arg.curPath.Length > 2 && arg.rtlFnc.IsSome && arg.inheritInfo.IsNone with | true -> FEI_Reference2RTL | false -> FEI_Reference2OtherType (ReferenceToType arg.typeDefPath) - //match arg.inferitInfo with + //match arg.inheritInfo with //| None -> FEI_Reference2OtherType (ReferenceToType arg.typeDefPath) //| Some inh -> FEI_NewSubTypeDefinition (ReferenceToType [MD inh.modName; TA inh.tasName]) | Some (TypeAssignmentInfo tsInfo) -> FEI_NewSubTypeDefinition (ReferenceToType arg.typeDefPath) -let getPrimitiveTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getPrimitiveTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerPrimitiveTypeDefinition us l (ReferenceToType arg.curPath) typedefKind arg.rtlFnc + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerPrimitiveTypeDefinition us l (ReferenceToType arg.curPath) typedefKind arg.rtlFnc (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getStringTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getStringTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerStringTypeDefinition us l (ReferenceToType arg.curPath) typedefKind + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerStringTypeDefinition us l (ReferenceToType arg.curPath) typedefKind (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getSizeableTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getSizeableTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerSizeableTypeDefinition us l (ReferenceToType arg.curPath) typedefKind + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerSizeableTypeDefinition us l (ReferenceToType arg.curPath) typedefKind (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getSequenceTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getSequenceTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerSequenceTypeDefinition us l (ReferenceToType arg.curPath) typedefKind + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerSequenceTypeDefinition us l (ReferenceToType arg.curPath) typedefKind (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getChoiceTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getChoiceTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerChoiceTypeDefinition us l (ReferenceToType arg.curPath) typedefKind + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerChoiceTypeDefinition us l (ReferenceToType arg.curPath) typedefKind (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getEnumeratedTypeDifition (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState)= - //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, referece to other type etc) +let getEnumeratedTypeDefinition (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState)= + //first determine the type definition kind (i.e. if it is a new type definition or reference to rtl, reference to other type etc) let typedefKind = getTypedefKind arg //let typedefKindEmnItem = getTypedefKind {arg with typeDefPath=arg.enmItemTypeDefPath} let lanDefs, us1 = - ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> - let itm, ns = registerEnumeratedTypeDefinition us l (ReferenceToType arg.curPath) typedefKind + ProgrammingLanguage.AllLanguages |> foldMap (fun us l -> + let itm, ns = registerEnumeratedTypeDefinition us l (ReferenceToType arg.curPath) typedefKind (l,itm), ns) us lanDefs |> Map.ofList, us1 -let getRefereceTypeDefinition (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (arg:GetTypeDifition_arg) (us:Asn1AcnMergeState) = - +let getReferenceTypeDefinition (asn1:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (arg:GetTypeDefinition_arg) (us:Asn1AcnMergeState) = + match (Asn1Ast.GetActualType t asn1).Kind with - | Asn1Ast.Integer -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.ObjectIdentifier -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.RelativeObjectIdentifier -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.Real -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.NullType -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.TimeType _ -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.Boolean -> getPrimitiveTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.Enumerated _ -> getEnumeratedTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_EnumeratedTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.OctetString -> getSizeableTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.BitString _ -> getSizeableTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.SequenceOf _ -> getSizeableTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.NumericString -> getStringTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_StringTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.IA5String -> getStringTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_StringTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.Sequence _ -> getSequenceTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SequenceTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.Choice _ -> getChoiceTypeDifition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_ChoiceTypeDefinition d)) |> Map.ofList,b) - | Asn1Ast.ReferenceType _ -> raise(BugErrorException "getRefereceTypeDefinition") + | Asn1Ast.Integer -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.ObjectIdentifier -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.RelativeObjectIdentifier -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.Real -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.NullType -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.TimeType _ -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.Boolean -> getPrimitiveTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_PrimitiveTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.Enumerated _ -> getEnumeratedTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_EnumeratedTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.OctetString -> getSizeableTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.BitString _ -> getSizeableTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.SequenceOf _ -> getSizeableTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SizeableTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.NumericString -> getStringTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_StringTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.IA5String -> getStringTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_StringTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.Sequence _ -> getSequenceTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_SequenceTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.Choice _ -> getChoiceTypeDefinition arg us |> (fun (a,b) -> a |> Map.toList |> List.map (fun (l, d) -> (l, FE_ChoiceTypeDefinition d)) |> Map.ofList,b) + | Asn1Ast.ReferenceType _ -> raise(BugErrorException "getReferenceTypeDefinition") diff --git a/FrontEndAst/FrontEndAst.fsproj b/FrontEndAst/FrontEndAst.fsproj index eb3697243..2cc04b1b8 100644 --- a/FrontEndAst/FrontEndAst.fsproj +++ b/FrontEndAst/FrontEndAst.fsproj @@ -13,7 +13,7 @@ - + @@ -43,12 +43,12 @@ - + - + ..\Antlr\antlr313\antlr.runtime.dll @@ -63,7 +63,7 @@ ..\Antlr\antlr313\StringTemplate.dll - + diff --git a/FrontEndAst/GenericFold2.fs b/FrontEndAst/GenericFold2.fs index 138c94da8..3c5ebd334 100644 --- a/FrontEndAst/GenericFold2.fs +++ b/FrontEndAst/GenericFold2.fs @@ -6,7 +6,7 @@ open Asn1Ast open FsUtils -let enumIntegerType = +let enumIntegerType = { Asn1Type.Kind = Integer Constraints = [] @@ -14,7 +14,7 @@ let enumIntegerType = acnProperties = None } -let stringType = +let stringType = { Asn1Type.Kind = IA5String Constraints = [] @@ -22,10 +22,10 @@ let stringType = acnProperties = None } -let sizeIntegerType = +let sizeIntegerType = { Asn1Type.Kind = Integer - Constraints = [RangeContraint_val_MAX ({Asn1Value.Kind = IntegerValue(FsUtils.IntLoc.ByValue 0I); Location=FsUtils.emptyLocation},true)] + Constraints = [RangeConstraint_val_MAX ({Asn1Value.Kind = IntegerValue(FsUtils.IntLoc.ByValue 0I); Location=FsUtils.emptyLocation},true)] Location = FsUtils.emptyLocation acnProperties = None } @@ -35,7 +35,7 @@ let sizeIntegerType = let rec foldMap func state lst = match lst with | [] -> [],state - | h::tail -> + | h::tail -> let procItem, newState = func state h let restList, finalState = tail |> foldMap func newState procItem::restList, finalState @@ -46,7 +46,7 @@ type ScopeNode = | MD of string //MODULE | TA of string //TYPE ASSIGNMENT | VA of string //VALUE ASSIGNMENT - | SEQ_CHILD of string + | SEQ_CHILD of string | CH_CHILD of string //SEQUENCE OF CHOICE CHILD | PRM of string // ACN parameter | TMP of string // ACN temp type @@ -109,8 +109,8 @@ type VarScopNode = | VA2 strVal -> strVal | DV -> "DV" | NI ni -> ni - | VL idx -> "v" + idx.ToString() - | IMG idx -> "img" + idx.ToString() + | VL idx -> "v" + idx.ToString() + | IMG idx -> "img" + idx.ToString() | CON idx -> "c" + idx.ToString() | SQOV i -> sprintf"[%d]" i | SQCHILD s-> s @@ -129,7 +129,7 @@ type Scope = | UserDefinedTypeScope of UserDefinedTypeScope | GlobanIntScope - + type UserDefinedVarScope = VarScopNode list @@ -138,31 +138,31 @@ let visitValueVas (vs:ValueAssignment) : UserDefinedVarScope= -let visitDefaultValue () : UserDefinedVarScope = +let visitDefaultValue () : UserDefinedVarScope = [DV] -let visitNamedItemValue (nm:NamedItem) : UserDefinedVarScope= +let visitNamedItemValue (nm:NamedItem) : UserDefinedVarScope= [NI nm.Name.Value] -let visitConstraint (s:UserDefinedVarScope) : UserDefinedVarScope= +let visitConstraint (s:UserDefinedVarScope) : UserDefinedVarScope= s@[CON 0] -let visitSilbingConstraint (s:UserDefinedVarScope) : UserDefinedVarScope = - let idx, xs = +let visitSiblingConstraint (s:UserDefinedVarScope) : UserDefinedVarScope = + let idx, xs = match s |> List.rev with | (CON idx)::xs -> idx, xs - | _ -> raise(BugErrorException "invalid call to visitSilbingConstraint") + | _ -> raise(BugErrorException "invalid call to visitSiblingConstraint") xs@[CON (idx+1)] -let visitValue (s:UserDefinedVarScope) :UserDefinedVarScope = +let visitValue (s:UserDefinedVarScope) :UserDefinedVarScope = s @[VL 0] -let visitSilbingValue (s:UserDefinedVarScope) :UserDefinedVarScope = - let idx, xs = +let visitSiblingValue (s:UserDefinedVarScope) :UserDefinedVarScope = + let idx, xs = match s |> List.rev with | (VL idx)::xs -> idx, xs - | _ -> raise(BugErrorException "invalid call to visitSilbingConstraint") + | _ -> raise(BugErrorException "invalid call to visitSiblingConstraint") xs@[VL (idx+1)] let visitSeqOfValue (s:UserDefinedVarScope) idx :UserDefinedVarScope = @@ -171,26 +171,26 @@ let visitSeqOfValue (s:UserDefinedVarScope) idx :UserDefinedVarScope = let visitSeqChildValue (s:UserDefinedVarScope) childName :UserDefinedVarScope = s @[SQCHILD childName ] -let error (loc: SrcLoc) format = - let doAfter s = +let error (loc: SrcLoc) format = + let doAfter s = raise (SemanticError (loc, s)) - Printf.ksprintf doAfter format + Printf.ksprintf doAfter format type CheckContext = | CheckContent - | CheckSize - | CheckCharacter + | CheckSize + | CheckCharacter -let foldAstRoot - rootFunc - fileFunc - modFunc - tasFunc - vasFunc +let foldAstRoot + rootFunc + fileFunc + modFunc + tasFunc + vasFunc typeFunc // refTypeFunc - integerFunc + integerFunc realFunc ia5StringFunc numericStringFunc @@ -199,34 +199,34 @@ let foldAstRoot bitStringFunc booleanFunc enumeratedFunc - enmItemFunc - seqOfTypeFunc - seqTypeFunc - chTypeFunc - sequenceChildFunc + enmItemFunc + seqOfTypeFunc + seqTypeFunc + chTypeFunc + sequenceChildFunc alwaysAbsentFunc alwaysPresentFunc optionalFunc defaultFunc - choiceChildFunc - refValueFunc - enumValueFunc - intValFunc - realValFunc - ia5StringValFunc - numStringValFunc - boolValFunc - octetStringValueFunc - bitStringValueFunc - nullValueFunc - seqOfValueFunc - seqValueFunc + choiceChildFunc + refValueFunc + enumValueFunc + intValFunc + realValFunc + ia5StringValFunc + numStringValFunc + boolValFunc + octetStringValueFunc + bitStringValueFunc + nullValueFunc + seqOfValueFunc + seqValueFunc chValueFunc - singleValueContraintFunc - rangeContraintFunc - rangeContraint_val_MAXFunc - rangeContraint_MIN_valFunc - rangeContraint_MIN_MAXFunc + singleValueConstraintFunc + rangeConstraintFunc + rangeConstraint_val_MAXFunc + rangeConstraint_MIN_valFunc + rangeConstraint_MIN_MAXFunc typeInclConstraintFunc unionConstraintFunc intersectionConstraintFunc @@ -234,8 +234,8 @@ let foldAstRoot exceptConstraintFunc rootConstraintFunc rootConstraint2Func - sizeContraint - alphabetContraint + sizeConstraint + alphabetConstraint withComponentConstraint withComponentConstraints globalIntType @@ -244,10 +244,10 @@ let foldAstRoot getSequenceTypeChild getTypeKind getTypeFromStateFunc - (r:AstRoot) - (us:'UserState) + (r:AstRoot) + (us:'UserState) = - + let rec loopAstRoot (r:AstRoot) (us:'UserState) = let files, nus = r.Files |> foldMap (loopFile r) us rootFunc nus r files @@ -283,19 +283,19 @@ let foldAstRoot let withCompCons = (t.Constraints@witchCompsCons) |> List.choose(fun c -> match c with WithComponentConstraint _ -> Some c| WithComponentsConstraint _ -> Some c | _ -> None) (* match t.Kind with - | ReferenceType (mdName,tasName, tabularized) when not (withCompCons.IsEmpty) -> + | ReferenceType (mdName,tasName, tabularized) when not (withCompCons.IsEmpty) -> let oldBaseType = Ast.GetBaseType t r let oldBaseType = {oldBaseType with Constraints = oldBaseType.Constraints@t.Constraints@witchCompsCons} loopType us (s, oldBaseType) [] | _ ->*) let newTypeKind, nus = loopTypeKind us s t.Kind withCompCons None - let newCons, (retScope, nus1) = t.Constraints |> foldMap (fun (ss, uds) c -> + let newCons, (retScope, nus1) = t.Constraints |> foldMap (fun (ss, uds) c -> let lc, uds2 = loopConstraint uds (s, newTypeKind,t) CheckContent (ss,c) - lc, (visitSilbingConstraint ss,uds2)) (conScope, nus) - let fromWithComps, (_, nus2) = witchCompsCons |> foldMap (fun (ss, uds) c -> + lc, (visitSiblingConstraint ss,uds2)) (conScope, nus) + let fromWithComps, (_, nus2) = witchCompsCons |> foldMap (fun (ss, uds) c -> let lc, uds2 = loopConstraint uds (s, newTypeKind,t) CheckContent (ss,c) - lc, (visitSilbingConstraint ss, uds2)) (retScope, nus1) - typeFunc nus2 s t newTypeKind (newCons,fromWithComps) + lc, (visitSiblingConstraint ss, uds2)) (retScope, nus1) + typeFunc nus2 s t newTypeKind (newCons,fromWithComps) | Some res -> res @@ -307,10 +307,10 @@ let foldAstRoot | NumericString -> numericStringFunc newBaseType us | OctetString -> octetStringFunc newBaseType us | NullType -> nullTypeFunc newBaseType us - | BitString -> bitStringFunc newBaseType us + | BitString -> bitStringFunc newBaseType us | Boolean -> booleanFunc newBaseType us - | Enumerated (enmItems) -> - enumeratedFunc us newBaseType enmItems + | Enumerated (enmItems) -> + enumeratedFunc us newBaseType enmItems | SequenceOf (innerType) -> let childScope = visitSeqOfChild s let withCompCons = witchCompsCons |> List.choose(fun c -> match c with WithComponentConstraint wc -> Some wc | _ -> None) @@ -318,21 +318,21 @@ let foldAstRoot seqOfTypeFunc nus newInnerType newBaseType | Sequence (children) -> let withCompCons = witchCompsCons |> List.choose(fun c -> match c with WithComponentsConstraint wc -> Some wc | _ -> None) |> List.collect id - let newChildren, fus = - children |> foldMap (fun cs chInfo -> + let newChildren, fus = + children |> foldMap (fun cs chInfo -> let childScope = visitSeqChild s chInfo - let chidlWithComps = withCompCons |> List.filter(fun x -> x.Name.Value = chInfo.Name.Value) - loopSequenceChild cs childScope chInfo chidlWithComps) us + let childWithComps = withCompCons |> List.filter(fun x -> x.Name.Value = chInfo.Name.Value) + loopSequenceChild cs childScope chInfo childWithComps) us seqTypeFunc fus newChildren newBaseType | Choice (children) -> let withCompCons = witchCompsCons |> List.choose(fun c -> match c with WithComponentsConstraint wc -> Some wc | _ -> None) |> List.collect id - let newChildren, fus = + let newChildren, fus = children |> foldMap (fun cs chInfo -> let childScope = visitChoiceChild s chInfo - let chidlWithComps = withCompCons |> List.filter(fun x -> x.Name.Value = chInfo.Name.Value) - loopChoiceChild cs childScope chInfo chidlWithComps) us + let childWithComps = withCompCons |> List.filter(fun x -> x.Name.Value = chInfo.Name.Value) + loopChoiceChild cs childScope chInfo childWithComps) us chTypeFunc fus newChildren newBaseType - | ReferenceType rf -> + | ReferenceType rf -> let oldBaseType = GetBaseTypeByName rf.modName rf.tasName r let refTypeScope = [MD rf.modName.Value; TA rf.tasName.Value] let newBaseType, nus = loopType us (refTypeScope, oldBaseType) [] @@ -361,11 +361,11 @@ let foldAstRoot | None -> enmItemFunc us ni None and loopSequenceChild (us:'UserState) (ts:UserDefinedTypeScope) (chInfo:ChildInfo) (nc:NamedConstraint list) = - let withCompCons = nc |> List.choose (fun x -> x.Contraint) + let withCompCons = nc |> List.choose (fun x -> x.Constraint) let newType, us1 = loopType us (ts,chInfo.Type) withCompCons let presMark = nc |> Seq.tryFind (fun x -> x.Mark <> NoMark) |> Option.map (fun nc -> nc.Mark) - let newOptionality, us2 = + let newOptionality, us2 = match presMark, chInfo.Optionality with | Some MarkPresent, _ -> Some (alwaysPresentFunc ts), us1 | Some MarkAbsent, _ -> Some (alwaysAbsentFunc ts), us1 @@ -382,7 +382,7 @@ let foldAstRoot sequenceChildFunc us2 ts chInfo newType newOptionality and loopChoiceChild (us:'UserState) (ts:UserDefinedTypeScope) (chInfo:ChildInfo) (nc:NamedConstraint list) = - let withCompCons = nc |> List.choose (fun x -> x.Contraint) + let withCompCons = nc |> List.choose (fun x -> x.Constraint) let newType, nus = loopType us (ts, chInfo.Type) withCompCons choiceChildFunc nus ts chInfo newType and loopAsn1Value (us:'UserState) (ts:UserDefinedTypeScope, newTypeKind, t:Asn1Type) (asn1ValName:(StringLoc*StringLoc) option) (vs:UserDefinedVarScope, v:Asn1Value, childValue:bool) : 'ASN1VALUE*'UserState = @@ -402,11 +402,11 @@ let foldAstRoot | IntegerValue bi, Real _ -> let dc:double = (double)bi.Value realValFunc us asn1ValName ts vs v {Value=dc;Location=v.Location} childValue - | RealValue dc , Real _ -> + | RealValue dc , Real _ -> realValFunc us asn1ValName ts vs v dc childValue - | StringValue str, IA5String _ -> + | StringValue str, IA5String _ -> ia5StringValFunc us asn1ValName ts vs v str childValue - | StringValue str , NumericString _ -> + | StringValue str , NumericString _ -> numStringValFunc us asn1ValName ts vs v str childValue | BooleanValue b, Boolean _ -> boolValFunc us asn1ValName ts vs v b childValue @@ -423,7 +423,7 @@ let foldAstRoot | SeqOfValue vals, SequenceOf chType -> let eqType = GetActualType chType r let newChScope, newChT = getSequenceOfTypeChild us newTypeKind - let newVals, (fs,_) = vals |> foldMap (fun (ust,idx) chVal -> + let newVals, (fs,_) = vals |> foldMap (fun (ust,idx) chVal -> let newV,newS = loopAsn1Value ust (newChScope, newChT, eqType) None ((visitSeqOfValue vs idx), chVal, true) newV,(newS, idx+1)) (us,0) seqOfValueFunc fs asn1ValName ts vs v newVals childValue @@ -434,17 +434,17 @@ let foldAstRoot match children |> Seq.tryFind(fun ch -> ch.Name.Value = name.Value) with | Some chType -> let newChScope, newChT = getChoiceTypeChild us newTypeKind name - let eqType = GetActualType chType.Type r + let eqType = GetActualType chType.Type r let newValue, fs = loopAsn1Value us (newChScope, newChT,eqType) None ((visitSeqChildValue vs name.Value),vl, true) chValueFunc fs asn1ValName ts vs v name newValue childValue - | None -> + | None -> error name.Location "Invalid alternative name '%s'" name.Value | _ -> error v.Location "Invalid combination ASN.1 type and ASN.1 value" - and loopSeqValueChild (us:'UserState) (newSeqT) (children: list) (vs:UserDefinedVarScope) (nm:StringLoc, chv:Asn1Value) = - let child = + and loopSeqValueChild (us:'UserState) (newSeqT) (children: list) (vs:UserDefinedVarScope) (nm:StringLoc, chv:Asn1Value) = + let child = match children |> Seq.tryFind (fun ch -> ch.Name.Value = nm.Value) with | Some ch -> ch | None -> error nm.Location "Invalid child name '%s'" nm.Value @@ -461,30 +461,30 @@ let foldAstRoot | CheckContent -> GetActualType t r match c with - | SingleValueContraint v -> + | SingleValueConstraint v -> let newValue, fs = loopAsn1Value us (s, newT ,vtype) None (visitValue cs,v, false) - singleValueContraintFunc fs newT t checContent newValue - | RangeContraint(v1,v2,b1,b2) -> + singleValueConstraintFunc fs newT t checContent newValue + | RangeConstraint(v1,v2,b1,b2) -> let vs1 = visitValue cs - let vs2 = visitSilbingValue vs1 + let vs2 = visitSiblingValue vs1 let newValue1, fs1 = loopAsn1Value us (s, newT,vtype) None (vs1,v1, false) let newValue2, fs2 = loopAsn1Value fs1 (s, newT,vtype) None (vs2,v2, false) - rangeContraintFunc fs2 newT t checContent newValue1 newValue2 b1 b2 - | RangeContraint_val_MAX (v,b) -> + rangeConstraintFunc fs2 newT t checContent newValue1 newValue2 b1 b2 + | RangeConstraint_val_MAX (v,b) -> let newValue, fs = loopAsn1Value us (s, newT,vtype) None (visitValue cs,v, false) - rangeContraint_val_MAXFunc fs newT t checContent newValue b - | RangeContraint_MIN_val (v,b) -> + rangeConstraint_val_MAXFunc fs newT t checContent newValue b + | RangeConstraint_MIN_val (v,b) -> let newValue, fs = loopAsn1Value us (s, newT,vtype) None (visitValue cs,v, false) - rangeContraint_MIN_valFunc fs newT t checContent newValue b - | RangeContraint_MIN_MAX -> - rangeContraint_MIN_MAXFunc us newT t checContent + rangeConstraint_MIN_valFunc fs newT t checContent newValue b + | RangeConstraint_MIN_MAX -> + rangeConstraint_MIN_MAXFunc us newT t checContent | TypeInclusionConstraint (md,tas) -> let actTypeAllCons = GetActualTypeByNameAllConsIncluded md tas r - let agrCon = + let agrCon = match actTypeAllCons.Constraints with | [] -> None | x::[] -> Some x - | x::xs -> + | x::xs -> let aa = xs |> List.fold(fun s cc -> IntersectionConstraint (s,cc)) x Some aa match agrCon with @@ -494,13 +494,13 @@ let foldAstRoot | None -> typeInclConstraintFunc us newT t None | UnionConstraint (c1,c2, virtualCon) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 let nc1, fs1 = loopConstraint us ( s, newT,t) checContent (cs1,c1) let nc2, fs2 = loopConstraint fs1 (s, newT,t) checContent (cs2,c2) unionConstraintFunc fs2 newT t nc1 nc2 virtualCon | IntersectionConstraint(c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 let nc1, fs1 = loopConstraint us (s, newT,t) checContent (cs1,c1) let nc2, fs2 = loopConstraint fs1 (s, newT,t) checContent (cs2,c2) intersectionConstraintFunc fs2 newT t nc1 nc2 @@ -509,25 +509,25 @@ let foldAstRoot allExceptConstraintFunc fs newT t nc | ExceptConstraint (c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 let nc1, fs1 = loopConstraint us (s, newT,t) checContent (cs1,c1) let nc2, fs2 = loopConstraint fs1 (s, newT,t) checContent (cs2,c2) exceptConstraintFunc fs2 newT t nc1 nc2 | RootConstraint c1 -> let nc, fs = loopConstraint us (s, newT,t) checContent ((visitConstraint cs),c1) - rootConstraintFunc fs newT t nc + rootConstraintFunc fs newT t nc | RootConstraint2 (c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 let nc1, fs1 = loopConstraint us (s, newT,t) checContent (cs1,c1) let nc2, fs2 = loopConstraint fs1 (s, newT,t) checContent (cs2,c2) rootConstraint2Func fs2 newT t nc1 nc2 - | SizeContraint(sc) -> + | SizeConstraint(sc) -> let nc, fs = loopConstraint us (s, newT,t) CheckSize (visitConstraint cs,sc) - sizeContraint fs newT t nc - | AlphabetContraint c -> + sizeConstraint fs newT t nc + | AlphabetConstraint c -> let nc, fs = loopConstraint us (s, newT, t) CheckCharacter (visitConstraint cs,c) - alphabetContraint fs newT t nc + alphabetConstraint fs newT t nc | WithComponentConstraint c -> withComponentConstraint us newT t | WithComponentsConstraint _ -> withComponentConstraints us newT t loopAstRoot r us diff --git a/FrontEndAst/Language.fs b/FrontEndAst/Language.fs index b93a1d826..ab8985b16 100644 --- a/FrontEndAst/Language.fs +++ b/FrontEndAst/Language.fs @@ -13,8 +13,8 @@ type Uper_parts = { requires_IA5String_i : bool count_var : LocalVariable requires_presenceBit : bool - catd : bool //if true then Choice Alternatives are Temporarily Decoded (i.e. in _tmp variables in curent scope) - //createBitStringFunction : (CallerScope -> CommonTypes.Codec -> ErroCode -> int -> BigInteger -> BigInteger -> BigInteger -> string -> BigInteger -> bool -> bool -> (string * LocalVariable list)) -> CommonTypes.Codec -> ReferenceToType -> TypeDefintionOrReference -> bool -> BigInteger -> BigInteger -> BigInteger -> ErroCode -> CallerScope -> UPERFuncBodyResult + catd : bool //if true then Choice Alternatives are Temporarily Decoded (i.e. in _tmp variables in current scope) + //createBitStringFunction : (CallerScope -> CommonTypes.Codec -> ErrorCode -> int -> BigInteger -> BigInteger -> BigInteger -> string -> BigInteger -> bool -> bool -> (string * LocalVariable list)) -> CommonTypes.Codec -> ReferenceToType -> TypeDefinitionOrReference -> bool -> BigInteger -> BigInteger -> BigInteger -> ErrorCode -> CallerScope -> UPERFuncBodyResult seqof_lv : ReferenceToType -> BigInteger -> BigInteger -> LocalVariable list } @@ -39,37 +39,41 @@ type Atc_parts = { } -type InitMethod = +type InitMethod = | Procedure | Function +type DecodingKind = + | InPlace + | Copy + [] type ILangGeneric () = abstract member ArrayStartIndex : int - abstract member getPointer : FuncParamType -> string; - abstract member getValue : FuncParamType -> string; - abstract member getAccess : FuncParamType -> string; - abstract member getStar : FuncParamType -> string; - abstract member getPtrPrefix : FuncParamType -> string; - abstract member getPtrSuffix : FuncParamType -> string; - abstract member getAmber : FuncParamType -> string; - abstract member toPointer : FuncParamType -> FuncParamType; - abstract member getArrayItem : FuncParamType -> (string) -> (bool) -> FuncParamType; + abstract member getPointer : Selection -> string; + abstract member getValue : Selection -> string; + abstract member getAccess : Selection -> string; + abstract member getAccess2 : Accessor -> string; + abstract member getStar : Selection -> string; + abstract member getPtrPrefix : Selection -> string; + abstract member getPtrSuffix : Selection -> string; + + abstract member getArrayItem : sel: Selection -> idx: string -> childTypeIsString: bool -> Selection; abstract member intValueToString : BigInteger -> Asn1AcnAst.IntegerClass -> string; abstract member doubleValueToString : double -> string abstract member initializeString : int -> string abstract member supportsInitExpressions : bool abstract member setNamedItemBackendName0 : Asn1Ast.NamedItem -> string -> Asn1Ast.NamedItem abstract member getNamedItemBackendName0 : Asn1Ast.NamedItem -> string - abstract member getNamedItemBackendName : TypeDefintionOrReference option -> Asn1AcnAst.NamedItem -> string + abstract member getNamedItemBackendName : TypeDefinitionOrReference option -> Asn1AcnAst.NamedItem -> string abstract member getNamedItemBackendName2 : string -> string -> Asn1AcnAst.NamedItem -> string abstract member decodeEmptySeq : string -> string option abstract member decode_nullType : string -> string option abstract member castExpression : string -> string -> string abstract member createSingleLineComment : string -> string abstract member SpecNameSuffix: string - abstract member SpecExtention : string - abstract member BodyExtention : string + abstract member SpecExtension : string + abstract member BodyExtension : string abstract member Keywords : string list abstract member isCaseSensitive : bool @@ -77,7 +81,7 @@ type ILangGeneric () = abstract member AlwaysPresentRtlFuncNames : string list abstract member detectFunctionCalls : string -> string -> string list - abstract member removeFunctionFromHeader : string -> string -> string + abstract member removeFunctionFromHeader : string -> string -> string abstract member removeFunctionFromBody : string -> string -> string @@ -97,27 +101,22 @@ type ILangGeneric () = abstract member Length : string -> string -> string abstract member typeDef : Map -> FE_PrimitiveTypeDefinition abstract member getTypeDefinition : Map -> FE_TypeDefinition - abstract member getEnmTypeDefintion : Map -> FE_EnumeratedTypeDefinition + abstract member getEnumTypeDefinition : Map -> FE_EnumeratedTypeDefinition abstract member getStrTypeDefinition : Map -> FE_StringTypeDefinition abstract member getChoiceTypeDefinition : Map -> FE_ChoiceTypeDefinition abstract member getSequenceTypeDefinition :Map -> FE_SequenceTypeDefinition abstract member getSizeableTypeDefinition : Map -> FE_SizeableTypeDefinition - abstract member getSeqChild : FuncParamType -> string -> bool -> bool -> FuncParamType; - abstract member getChChild : FuncParamType -> string -> bool -> FuncParamType; + abstract member getSeqChild: sel: Selection -> childName: string -> childTypeIsString: bool -> childIsOptional: bool -> Selection; + abstract member getChChild : Selection -> string -> bool -> Selection; abstract member getLocalVariableDeclaration : LocalVariable -> string; - abstract member getLongTypedefName : TypeDefintionOrReference -> string; - abstract member getEmptySequenceInitExpression : unit -> string + abstract member getLongTypedefName : TypeDefinitionOrReference -> string; + abstract member getEmptySequenceInitExpression : string -> string abstract member callFuncWithNoArgs : unit -> string - //abstract member getEnmLongTypedefName : FE_EnumeratedTypeDefinition -> string -> FE_EnumeratedTypeDefinition; - - - abstract member ArrayAccess : string -> string; - - abstract member presentWhenName : TypeDefintionOrReference option -> ChChildInfo -> string; + abstract member presentWhenName : TypeDefinitionOrReference option -> ChChildInfo -> string; abstract member getParamTypeSuffix : Asn1AcnAst.Asn1Type -> string -> Codec -> CallerScope; - abstract member getParamValue : Asn1AcnAst.Asn1Type -> FuncParamType -> Codec -> string + abstract member getParamValue : Asn1AcnAst.Asn1Type -> Selection -> Codec -> string abstract member getParamType : Asn1AcnAst.Asn1Type -> Codec -> CallerScope; abstract member rtlModuleName : string @@ -131,7 +130,7 @@ type ILangGeneric () = abstract member AssignOperator :string abstract member TrueLiteral :string abstract member FalseLiteral :string - abstract member emtyStatement :string + abstract member emptyStatement :string abstract member bitStreamName :string abstract member unaryNotOperator :string abstract member modOp :string @@ -139,7 +138,9 @@ type ILangGeneric () = abstract member neqOp :string abstract member andOp :string abstract member orOp :string - abstract member initMetod :InitMethod + abstract member initMethod :InitMethod + abstract member decodingKind :DecodingKind + abstract member usesWrappedOptional: bool abstract member bitStringValueToByteArray: BitStringValue -> byte[] abstract member toHex : int -> string @@ -158,15 +159,7 @@ type ILangGeneric () = abstract member getBoardDirs : Targets option -> string list - - -// abstract member createLocalVariable_frag : string -> LocalVariable - - default this.getAmber (fpt:FuncParamType) = - if this.getStar fpt = "*" then "&" else "" - default this.toPointer (fpt:FuncParamType) = - POINTER (this.getPointer fpt) - default this.getParamType (t:Asn1AcnAst.Asn1Type) (c:Codec) : CallerScope = + default this.getParamType (t:Asn1AcnAst.Asn1Type) (c:Codec) : CallerScope = this.getParamTypeSuffix t "" c default this.requiresHandlingOfEmptySequences = false default this.requiresHandlingOfZeroArrays = false @@ -177,7 +170,7 @@ type ILangGeneric () = sourceCode default this.removeFunctionFromBody (sourceCode: string) (functionName: string) : string = sourceCode - + //most programming languages are case sensitive default _.isCaseSensitive = true default _.getBoardNames _ = [] @@ -198,5 +191,14 @@ type LanguageMacros = { src : ISrcBody } - - +type Selection with + member this.joined (lg: ILangGeneric): string = + List.fold (fun str accessor -> $"{str}{lg.getAccess2 accessor}") this.receiverId this.path + member this.asIdentifier: string = + List.fold (fun str accessor -> + let acc = + match accessor with + | ValueAccess (id, _, _) -> ToC id + | PointerAccess (id, _, _) -> ToC id + | ArrayAccess _ -> "arr" + $"{str}_{acc}") this.receiverId this.path \ No newline at end of file diff --git a/FrontEndAst/LoadAcnInfo.fs b/FrontEndAst/LoadAcnInfo.fs index 3c6770061..6cbf375fe 100644 --- a/FrontEndAst/LoadAcnInfo.fs +++ b/FrontEndAst/LoadAcnInfo.fs @@ -43,7 +43,7 @@ let rec EvaluateConstant (constants:AcnConstant list) intConstant = |None -> raise(SemanticError(consLookUp.Location, (sprintf "Unknown symbol '%s'" consLookUp.Value))) |Some(cn) -> EvaluateAcnIntExpression constants cn.Value -and EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr = +and EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr = match acnExpr with | IntegerExpr(consta) -> EvaluateConstant constants consta | SumExpr(exp1,exp2) -> (EvaluateAcnIntExpression constants exp1) + (EvaluateAcnIntExpression constants exp2) @@ -51,9 +51,9 @@ and EvaluateAcnIntExpression (constants:AcnConstant list) acnExpr = | MulExpr(exp1,exp2) -> (EvaluateAcnIntExpression constants exp1) * (EvaluateAcnIntExpression constants exp2) | DivExpr(exp1,exp2) -> (EvaluateAcnIntExpression constants exp1) / (EvaluateAcnIntExpression constants exp2) | ModExpr(exp1,exp2) -> (EvaluateAcnIntExpression constants exp1) % (EvaluateAcnIntExpression constants exp2) - | PowExpr(exp1,exp2) -> + | PowExpr(exp1,exp2) -> System.Numerics.BigInteger.Pow(EvaluateAcnIntExpression constants exp1, int (EvaluateAcnIntExpression constants exp2)) - | UnMinExp(exp1) -> -(EvaluateAcnIntExpression constants exp1) + | UnMinExp(exp1) -> -(EvaluateAcnIntExpression constants exp1) type AntlrParserResult = { @@ -99,13 +99,13 @@ let CreateAcnAsn1Type (t:ITree) (r:AstRoot) = | acnParser.INTEGER -> AcnAsn1Type.AcnInteger t.Location | acnParser.BOOLEAN -> AcnAsn1Type.AcnBoolean t.Location | acnParser.NULL -> AcnAsn1Type.AcnNullType t.Location - | acnParser.REFERENCED_TYPE -> - let mdName, tsName = + | acnParser.REFERENCED_TYPE -> + let mdName, tsName = match t.Children with | first::[] -> first.GetAncestor(acnParser.MODULE_DEF).GetChild(0).TextL,first.TextL | first::sec::[] -> first.TextL,sec.TextL | _ -> raise(BugErrorException("AcnCreateFromAntlr::CreateAcnAsn1Type 1")) - let m = CheckModuleName r mdName + let m = CheckModuleName r mdName gatTasByName r m tsName |> ignore AcnAsn1Type.AcnRefType(mdName, tsName) | _ -> raise(BugErrorException("AcnCreateFromAntlr::CreateAcnAsn1Type 2")) @@ -115,27 +115,27 @@ let CreateAcnAsn1Type (t:ITree) (r:AstRoot) = let BalladerProperties = [acnParser.PRESENT_WHEN; acnParser.ALIGNTONEXT;] let rec AllowedPropertiesPerType (r:AstRoot) = function - | Integer -> [acnParser.ENCODING; acnParser.SIZE; acnParser.ENDIANNES; acnParser.MAPPING_FUNCTION] - | Real -> [acnParser.ENCODING; acnParser.ENDIANNES] + | Integer -> [acnParser.ENCODING; acnParser.SIZE; acnParser.ENDIANNESS; acnParser.MAPPING_FUNCTION] + | Real -> [acnParser.ENCODING; acnParser.ENDIANNESS] | IA5String -> [acnParser.ENCODING; acnParser.SIZE] | NumericString -> [acnParser.ENCODING; acnParser.SIZE] | OctetString -> [acnParser.SIZE] | NullType -> [acnParser.PATTERN] | BitString -> [acnParser.SIZE] | Boolean -> [acnParser.TRUE_VALUE; acnParser.FALSE_VALUE] - | Enumerated(_) -> [acnParser.ENCODING; acnParser.SIZE; acnParser.ENCODE_VALUES; acnParser.ENDIANNES] + | Enumerated(_) -> [acnParser.ENCODING; acnParser.SIZE; acnParser.ENCODE_VALUES; acnParser.ENDIANNESS] | SequenceOf(_) -> [acnParser.SIZE] | Sequence(_) -> [] | Choice(_) -> [acnParser.DETERMINANT] - | ReferenceType rf -> + | ReferenceType rf -> let baseType = GetBaseTypeByName rf.modName rf.tasName r AllowedPropertiesPerType r baseType.Kind let MandatoryAcnPropertiesPerType asn1Kind : List = match asn1Kind with - | Integer -> [acnParser.ENCODING; acnParser.SIZE; ] //ADJUST = 0, ENDIANNES=big - | Real -> [acnParser.ENCODING; ] //ENDIANNES=big + | Integer -> [acnParser.ENCODING; acnParser.SIZE; ] //ADJUST = 0, ENDIANNESS=big + | Real -> [acnParser.ENCODING; ] //ENDIANNESS=big | IA5String -> [] // pointing to a field | NumericString -> [] // pointing to a field | OctetString -> [acnParser.SIZE] // pointing to a field @@ -147,19 +147,19 @@ let MandatoryAcnPropertiesPerType asn1Kind : List = | Sequence(_) -> [] | Choice(_) -> [] | ReferenceType(_) -> [] - + let PropID_to_Text = function | acnParser.PRESENT_WHEN -> "present-when" | acnParser.ALIGNTONEXT -> "align-to-next" | acnParser.ENCODING -> "encoding" | acnParser.SIZE -> "size" - | acnParser.ENDIANNES -> "endianness" + | acnParser.ENDIANNESS -> "endianness" | acnParser.PATTERN -> "pattern" | acnParser.TRUE_VALUE -> "true-value" | acnParser.FALSE_VALUE -> "false-value" | acnParser.ENCODE_VALUES -> "encode-values" | acnParser.DETERMINANT -> "determinant" - | acnParser.MAPPING_FUNCTION -> "mapping-function" + | acnParser.MAPPING_FUNCTION -> "mapping-function" | _ -> raise(BugErrorException "") @@ -174,14 +174,14 @@ let CheckConsistencyOfAsn1TypeWithAcnProperty (r:AstRoot) asn1Kind (t:ITree) = -let getAcnAligmentProperty (t:ITree) = +let getAcnAlignmentProperty (t:ITree) = match t.Type with | acnParser.ALIGNTONEXT -> - match t.GetChild(0).Type with + match t.GetChild(0).Type with | acnParser.BYTE -> Some NextByte | acnParser.WORD -> Some NextWord | acnParser.DWORD -> Some NextDWord - | _ -> raise(BugErrorException("getAcnAligmentProperty")) + | _ -> raise(BugErrorException("getAcnAlignmentProperty")) | _ -> None let getAcnIntEncoding (t:ITree) = @@ -223,7 +223,7 @@ let getAcnStringEncoding (t:ITree) = | _ -> raise(BugErrorException("getAcnStringEncoding")) | _ -> None -let GetActualString (str:string) = +let GetActualString (str:string) = let strVal = str.Substring(1) strVal.Remove(strVal.Length-2).Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "") @@ -237,8 +237,8 @@ let handlNullTerminate (t:ITree) = match bitPattern.Length <> 8 with | true -> raise(SemanticError(tp.Location, sprintf "termination-pattern value must be a byte" )) | false -> - bitPattern.ToCharArray() |> - Seq.fold(fun (p,cs) c -> if c='0' then (p/2,cs) else (p/2,p+cs) ) (128, 0) + bitPattern.ToCharArray() |> + Seq.fold(fun (p,cs) c -> if c='0' then (p/2,cs) else (p/2,p+cs) ) (128, 0) |> snd |> byte | acnParser.OctectStringLiteral -> match bitPattern.Length <> 2 with @@ -251,7 +251,7 @@ let getAcnIntSizeProperty(r:AstRoot) (t:ITree) = match t.Type with | acnParser.SIZE -> match t.GetChild(0).Type with - | acnParser.NULL_TERMINATED -> + | acnParser.NULL_TERMINATED -> let nullByte = handlNullTerminate t Some (IntNullTerminated nullByte) | acnParser.INT -> Some (Fixed (t.GetChild(0)).BigInt) @@ -260,13 +260,13 @@ let getAcnIntSizeProperty(r:AstRoot) (t:ITree) = | _ -> None let getAcnStringSizeProperty (r:AstRoot) (t:ITree) = - let GetActualString (str:string) = + let GetActualString (str:string) = let strVal = str.Substring(1) strVal.Remove(strVal.Length-2).Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "") match t.Type with | acnParser.SIZE -> match t.GetChild(0).Type with - | acnParser.NULL_TERMINATED -> + | acnParser.NULL_TERMINATED -> let nullByte = handlNullTerminate t Some (StrNullTerminated nullByte) | acnParser.LONG_FIELD -> Some (StrExternalField (CreateLongField (t.GetChild(0)))) @@ -290,8 +290,8 @@ let getAcnSizeableSizeProperty (r:AstRoot) (t:ITree) = let getAcnEndianness (t:ITree) = match t.Type with - | acnParser.ENDIANNES -> - match t.GetChild(0).Type with + | acnParser.ENDIANNESS -> + match t.GetChild(0).Type with | acnParser.BIG -> Some BigEndianness | acnParser.LITTLE -> Some LittleEndianness | _ -> raise(BugErrorException("getAcnEndianness")) @@ -305,15 +305,15 @@ let getAcnEncodeValues (t:ITree) = let GetEnumValuesResetInAcn (enumItems:NamedItem list) (t:ITree) = match t.GetOptChild(acnParser.CHILDREN_ENC_SPEC) with | None -> None - | Some(childrenList) -> + | Some(childrenList) -> let errLoc = t.Location - let enmChildren = - childrenList.Children |> + let enmChildren = + childrenList.Children |> List.map(fun x -> match x.Type with - |acnParser.CHILD -> + |acnParser.CHILD -> let name = x.GetChild(0).TextL let errLoc = x.GetChild(0).Location - let chEncSpec = x.GetChildByType(acnParser.ENCODING_SPEC) + let chEncSpec = x.GetChildByType(acnParser.ENCODING_SPEC) let encValue = match chEncSpec.GetOptChild acnParser.ENCODING_PROPERTIES with | None -> raise(SemanticError(errLoc, "Expecting integer value")) | Some(propLst) -> @@ -326,28 +326,28 @@ let GetEnumValuesResetInAcn (enumItems:NamedItem list) (t:ITree) = | _ -> raise(SemanticError(x.Location, "Expecting an enumerated name")) ) // 1 make sure that the two lists match - let enmList1 = enumItems |> List.map(fun x -> x.Name) - let enmList2 = enmChildren |> List.map fst + let enmList1 = enumItems |> List.map(fun x -> x.Name) + let enmList2 = enmChildren |> List.map fst CompareLists enmList1 enmList2 (fun x -> SemanticError(x.Location, sprintf "Unexpected value '%s' " x.Value)) CompareLists enmList2 enmList1 (fun x -> SemanticError(errLoc, sprintf "Missing value '%s' " x.Value)) //2 make sure that there is no duplicate value enmChildren |> List.map snd |> CheckForDuplicates - let redefVals = enmChildren |> List.map(fun (nm, vl) -> {EnumeratedRedefinedValue.enumName = nm.Value; enumValue = vl.Value}) + let redefVals = enmChildren |> List.map(fun (nm, vl) -> {EnumeratedRedefinedValue.enumName = nm.Value; enumValue = vl.Value}) Some redefVals let getNullEncodingPattern (t:ITree) = match t.Type with - | acnParser.PATTERN -> + | acnParser.PATTERN -> let v = { StringLoc.Value = GetActualString(t.GetChild(0).Text); Location = t.GetChild(0).Location} Some v | _ -> None let getBoolEncodingPattern (t:ITree) = match t.Type with - | acnParser.TRUE_VALUE -> + | acnParser.TRUE_VALUE -> let v = { StringLoc.Value = GetActualString(t.GetChild(0).Text); Location = t.GetChild(0).Location} Some (TrueValue(v)) - | acnParser.FALSE_VALUE -> + | acnParser.FALSE_VALUE -> let v = { StringLoc.Value = GetActualString(t.GetChild(0).Text); Location = t.GetChild(0).Location} Some (FalseValue(v)) | _ -> None @@ -355,10 +355,10 @@ let getBoolEncodingPattern (t:ITree) = let getPresentWhenCondtition (r:AstRoot) (t:ITree) = match t.Type with - | acnParser.PRESENT_WHEN -> + | acnParser.PRESENT_WHEN -> match t.Type with | acnParser.LONG_FIELD -> Some(PresenceBool (CreateLongField(t))) - | acnParser.EQUAL -> + | acnParser.EQUAL -> Some (PresenceInt(CreateLongField(t.GetChild(0)), r.acnConstants.[(t.GetChild(1)).Text])) | acnParser.PRESENT_WHEN_STR_EQUAL -> Some (PresenceStr(CreateLongField(t.GetChild(0)), (t.GetChild(1).Text.Replace("\"","")))) @@ -370,7 +370,7 @@ let getPresentWhenCondtition (r:AstRoot) (t:ITree) = let GetArgumentList (allAcnFiles: AntlrParserResult list) (t:ITree) childTypeKind = match t.GetOptChild(acnParser.ARGUMENTS) with | None -> [] - | Some(argList) -> + | Some(argList) -> //I have arguments ==> I have to be a ref type. let prmNames = match childTypeKind with | ReferenceType rf -> GetParams allAcnFiles rf.modName.Value rf.tasName.Value @@ -389,15 +389,15 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars | Some tp -> match props |> Seq.tryFind(fun p -> p.Type = acnParser.SIZE) with | None -> raise(SemanticError(tp.Location, sprintf "termination-pattern can appear only if acn size NULL-TERMINATED is present" )) - | Some sz -> + | Some sz -> match sz.Children |> Seq.tryFind(fun p -> p.Type = acnParser.NULL_TERMINATED) with | None -> raise(SemanticError(tp.Location, sprintf "termination-pattern can appear only if acn size NULL-TERMINATED is present" )) - | Some _ -> + | Some _ -> sz.AddChild(tp) ret - let props = + let props = match tTree.GetOptChild(acnParser.ENCODING_PROPERTIES) with | None -> [] | Some(propList) -> propList.Children @@ -406,7 +406,7 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars //check each property against the asn1 type props |> Seq.iter(fun x -> CheckConsistencyOfAsn1TypeWithAcnProperty r t.Kind x) //check for duplicate ACN properties - props |> Seq.map(fun x -> x.TextL) |> CheckForDuplicates + props |> Seq.map(fun x -> x.TextL) |> CheckForDuplicates let props = mergeTerminationPatternWithNullTerminated props @@ -415,9 +415,9 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars let propsNoBallader = props |> List.filter(fun x -> not(BalladerProperties |> List.contains x.Type ) ) match propsNoBallader with | [] -> () // uper mode - | x::xs -> + | x::xs -> let errLoc = x.Location - let mandProps = MandatoryAcnPropertiesPerType t.Kind + let mandProps = MandatoryAcnPropertiesPerType t.Kind let missing = mandProps |> List.filter(fun x -> not(propsNoBallader |> List.exists(fun y -> y.Type=x) )) match missing with | [] -> () @@ -428,31 +428,31 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars | xx::_ -> Some xx | [] -> None - let acnAligment = getFirstOrNone getAcnAligmentProperty + let acnAlignment = getFirstOrNone getAcnAlignmentProperty let presenceConditions = props |> List.choose (getPresentWhenCondtition r) - + match presenceConditions with | [] -> () | _ -> match parentType with | Some parentType -> match parentType.Kind with - | Sequence _ + | Sequence _ | Choice _ -> () | _ -> raise (SemanticError(tTree.Location, "present-when' attribute can be applied to optional components only")) | None -> raise (SemanticError(tTree.Location, "present-when' attribute can be applied to optional components only")) - let newT = + let newT = match t.Kind with - | Integer -> - let props = + | Integer -> + let props = { IntegerAcnProperties.encodingProp = getFirstOrNone getAcnIntEncoding sizeProp = getFirstOrNone (getAcnIntSizeProperty r) endiannessProp = getFirstOrNone getAcnEndianness - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } - + {t with acnProperties = Some (IntegerAcnProperties props)} | Enumerated enmItems -> let props = @@ -460,74 +460,74 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars EnumeratedAcnProperties.encodingProp = getFirstOrNone getAcnIntEncoding sizeProp = getFirstOrNone (getAcnIntSizeProperty r) endiannessProp = getFirstOrNone getAcnEndianness - acnAligment = acnAligment + acnAlignment = acnAlignment redefinedValues = GetEnumValuesResetInAcn enmItems tTree encodeValues = getFirstOrNone getAcnEncodeValues presentWhen = presenceConditions } {t with acnProperties = Some (EnumeratedAcnProperties props)} - | Real -> - let props = + | Real -> + let props = { RealAcnProperties.encodingProp = getFirstOrNone getAcnRealEncoding endiannessProp = getFirstOrNone getAcnEndianness - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (RealAcnProperties props)} | IA5String | NumericString -> - let props = + let props = { StringAcnProperties.encodingProp = getFirstOrNone getAcnStringEncoding sizeProp = getFirstOrNone (getAcnStringSizeProperty r) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (StringAcnProperties props)} | OctetString -> - let props = + let props = { SizeableAcnProperties.sizeProp = getFirstOrNone (getAcnSizeableSizeProperty r) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (OctetStringAcnProperties props)} - | BitString -> - let props = + | BitString -> + let props = { SizeableAcnProperties.sizeProp = getFirstOrNone (getAcnSizeableSizeProperty r) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (BitStringAcnProperties props)} - | NullType -> - let props = + | NullType -> + let props = { NullTypeAcnProperties.encodingPattern = getFirstOrNone (getNullEncodingPattern) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (NullTypeAcnProperties props)} - | Boolean -> - let props = + | Boolean -> + let props = { BooleanAcnProperties.encodingPattern = getFirstOrNone (getBoolEncodingPattern) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } {t with acnProperties = Some (BooleanAcnProperties props)} - | SequenceOf chType -> - let props = + | SequenceOf chType -> + let props = { SizeableAcnProperties.sizeProp = getFirstOrNone (getAcnSizeableSizeProperty r) - acnAligment = acnAligment + acnAlignment = acnAlignment presentWhen = presenceConditions } //let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrParserResult) (r:AstRoot) (m:Asn1Module) (t:Asn1Type) (tTree:ITree) : Asn1Type = let childrenEncSpec = tTree.GetOptChild(acnParser.CHILDREN_ENC_SPEC) - let newChild = + let newChild = match childrenEncSpec with | None -> chType | Some childrenList -> @@ -544,9 +544,9 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars | ReferenceType rf -> let args= GetArgumentList allAcnFiles chTree chType.Kind let newChild = {chType with Kind = ReferenceType ({rf with acnArguments = args})} - CreateType allAcnFiles thisAcnFile r m (Some t) newChild (chTree.GetChildByType acnParser.ENCODING_SPEC) + CreateType allAcnFiles thisAcnFile r m (Some t) newChild (chTree.GetChildByType acnParser.ENCODING_SPEC) | _ -> - CreateType allAcnFiles thisAcnFile r m (Some t) chType (chTree.GetChildByType acnParser.ENCODING_SPEC) + CreateType allAcnFiles thisAcnFile r m (Some t) chType (chTree.GetChildByType acnParser.ENCODING_SPEC) | acnParser.CHILD_NEW -> raise(SemanticError(chTree.Location, "New fields can be inserted within sequences, not sequence ofs.")) | _ -> raise(BugErrorException("AcnCreateFromAntlr::CreateAcnChild")) | x1::x2::_ -> raise(SemanticError(t.Location, sprintf "SEQUENCE OFs have only one child")) @@ -554,7 +554,7 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars {t with acnProperties = Some (SequenceOfAcnProperties props); Kind = SequenceOf newChild} | Sequence children -> t | Choice children -> t - | ReferenceType rf -> + | ReferenceType rf -> let baseType = GetBaseType t r let virtualNewT = CreateType allAcnFiles thisAcnFile r m parentType baseType tTree {t with acnProperties = virtualNewT.acnProperties} @@ -564,10 +564,10 @@ let rec CreateType (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrPars let CreateTypeAssignment (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrParserResult) (r:AstRoot) (m:Asn1Module) (tas:TypeAssignment) (tasTree:ITree) : TypeAssignment = let encSpec = tasTree.GetChildByType(acnParser.ENCODING_SPEC) - let prms = + let prms = match tasTree.GetOptChild(acnParser.PARAM_LIST) with | None -> [] - | Some(paramList) -> + | Some(paramList) -> let CreateParam (x:ITree) = let prmName = x.GetChild(1).Text let loc = x.GetChild(1).Location @@ -585,35 +585,35 @@ let CreateModule (allAcnFiles: AntlrParserResult list) (thisAcnFile: AntlrParser let asn1Mod = CheckModuleName r modNameL let tasITreeList = modTree.GetChildrenByType(acnParser.TYPE_ENCODING) - + //check for duplicate type assignments in the ACN module tasITreeList |> List.map(fun x -> x.GetChildByType(acnParser.UID).TextL) |> CheckForDuplicates let newTassesMap = - tasITreeList |> + tasITreeList |> List.map(fun tasTree -> let tasNameL = tasTree.GetChildByType(acnParser.UID).TextL let tas = gatTasByName r asn1Mod tasNameL CreateTypeAssignment allAcnFiles thisAcnFile r asn1Mod tas tasTree) |> List.map(fun tas -> tas.Name.Value, tas) |> Map.ofList - + {asn1Mod with TypeAssignments = asn1Mod.TypeAssignments |> List.map(fun tas -> match newTassesMap.TryFind tas.Name.Value with Some x -> x | None -> tas)} -let LoadAcnFile (allAcnFiles: AntlrParserResult list) (r:AstRoot) (thisAcnFile: AntlrParserResult) : Asn1Module list = +let LoadAcnFile (allAcnFiles: AntlrParserResult list) (r:AstRoot) (thisAcnFile: AntlrParserResult) : Asn1Module list = thisAcnFile.rootItem.Children |> List.map (CreateModule allAcnFiles thisAcnFile r) -let CreateAcnIntegerConstant constantsSet (t:ITree) = +let CreateAcnIntegerConstant constantsSet (t:ITree) = match t.Type with | acnParser.INT -> IntConst(t.BigIntL) - | acnParser.UID -> + | acnParser.UID -> let extToThrow = SemanticError(t.Location, (sprintf "No ACN constant is defined with name '%s'" t.Text)) CheckExists t.TextL constantsSet extToThrow RefConst(t.TextL) | _ -> raise(BugErrorException("AcnCreateFromAntlr::CreateAcnIntegerConstant")) -let rec CreateExpression (r:AstRoot, st:List) (t:ITree) = +let rec CreateExpression (r:AstRoot, st:List) (t:ITree) = match t.Type with | acnParser.INT | acnParser.UID -> IntegerExpr(CreateAcnIntegerConstant st t) | acnParser.PLUS -> SumExpr(CreateExpression (r,st) (t.GetChild(0)), CreateExpression (r,st) (t.GetChild(1))) @@ -626,7 +626,7 @@ let rec CreateExpression (r:AstRoot, st:List) (t:ITree) = | _ -> raise( BugErrorException("AcnCreateFromAntlr::CreateExpression Unsupported operator")) -let CreateNamedExpression (r:AstRoot, st:List) (t:ITree) : AcnConstant= +let CreateNamedExpression (r:AstRoot, st:List) (t:ITree) : AcnConstant= let name = t.GetChild(0).TextL // Constanst have global scope (i.e. within all modules) and should not conflict with any type or value assigment names for m in r.Modules do @@ -643,27 +643,27 @@ let CheckCircularDependenciesInAcnConstants (constants : List) = match t.Type with | acnParser.INT -> () | acnParser.UID -> yield t.TextL - | acnParser.PLUS |acnParser.MINUS | acnParser.MULTIPLICATION | acnParser.DIVISION | acnParser.MODULO | acnParser.POWER_SYMBOL -> + | acnParser.PLUS |acnParser.MINUS | acnParser.MULTIPLICATION | acnParser.DIVISION | acnParser.MODULO | acnParser.POWER_SYMBOL -> yield! GetNamesFromExpr (t.GetChild(0)) yield! GetNamesFromExpr (t.GetChild(1)) - | acnParser.UNARY_MINUS -> yield! GetNamesFromExpr (t.GetChild(0)) + | acnParser.UNARY_MINUS -> yield! GetNamesFromExpr (t.GetChild(0)) | _ -> raise(BugErrorException("CheckCircularDependenciesInAcnConstants.HandleConstant.GetNamesFromExpr Unsupported operator")) } |> Seq.toList (t.GetChild(0).TextL, GetNamesFromExpr (t.GetChild(1))) let constantsExpanded = constants |> List.map HandleConstant let independentConstants = constantsExpanded |> List.filter(fun (nm, lst) -> lst.IsEmpty ) |> List.map fst - let dependentConstansts = constantsExpanded |> List.filter(fun (nm, lst) -> not (lst.IsEmpty) ) + let dependentConstants = constantsExpanded |> List.filter(fun (nm, lst) -> not (lst.IsEmpty) ) let comparer (s1:StringLoc) (s2:StringLoc) = s1.Value = s2.Value - let ExToThrow (cyclicDepds:List>) = + let ExToThrow (cyclicDepds:List>) = match cyclicDepds with | [] -> raise(BugErrorException("")) - | (x,_)::xs -> + | (x,_)::xs -> let names = cyclicDepds |> Seq.map (fun (n,_) -> n.Value) |> Seq.StrJoin ", " SemanticError(x.Location, sprintf "Cyclic dependencies in ACN constants: %s" names) - DoTopologicalSort2 independentConstants dependentConstansts comparer ExToThrow |> ignore + DoTopologicalSort2 independentConstants dependentConstants comparer ExToThrow |> ignore -let CreateAcnAst (allAcnFiles: AntlrParserResult list) (r0:AstRoot) : AstRoot = +let CreateAcnAst (allAcnFiles: AntlrParserResult list) (r0:AstRoot) : AstRoot = ITree.RegisterFiles(allAcnFiles|> Seq.map(fun pr -> (pr.rootItem, pr.fileName))) let constants = seq { for acnFile in allAcnFiles do @@ -674,11 +674,11 @@ let CreateAcnAst (allAcnFiles: AntlrParserResult list) (r0:AstRoot) : AstRoot = let constantNames = constants |> List.map(fun c -> c.GetChild(0).TextL) // check that all constant names are unique - constantNames |> CheckForDuplicates + constantNames |> CheckForDuplicates CheckCircularDependenciesInAcnConstants constants - let constantValues = constants |> List.map (CreateNamedExpression (r0, constantNames)) + let constantValues = constants |> List.map (CreateNamedExpression (r0, constantNames)) let acnConstantsMap = constantValues |> List.map(fun c -> c.Name.Value, EvaluateAcnIntExpression constantValues c.Value) |> Map.ofList diff --git a/FrontEndAst/LspAst.fs b/FrontEndAst/LspAst.fs index 82ab834e4..157e49af8 100644 --- a/FrontEndAst/LspAst.fs +++ b/FrontEndAst/LspAst.fs @@ -26,19 +26,19 @@ type LspFileType = type LspType = - | LspInteger - | LspReal - | LspIA5String + | LspInteger + | LspReal + | LspIA5String | LspNumericString - | LspOctetString + | LspOctetString | LspObjectIdentifier | LspRelativeObjectIdentifier - | LspTimeType - | LspNullType - | LspBitString - | LspBoolean + | LspTimeType + | LspNullType + | LspBitString + | LspBoolean | LspEnumerated of list - | LspSequenceOf of LspType + | LspSequenceOf of LspType | LspSequence of list | LspChoice of list | LspReferenceType of StringLoc*StringLoc @@ -47,10 +47,10 @@ type LspType = type LspTypeAssignment = { name : string line0 : int - charPos : int + charPos : int //lspType : LspType } -with +with override this.ToString() = sprintf "%A" this @@ -61,7 +61,7 @@ type LspError = { charPosInline : int msg : string } -with +with override this.ToString() = sprintf "%A" this type LspModule = { @@ -79,9 +79,9 @@ type LspFile = { tasList : LspTypeAssignment list lspFileType : LspFileType } -with +with override this.ToString() = sprintf "%A" this - member this.AsLines = + member this.AsLines = this.content.Split([|"\r\n";"\n"|], StringSplitOptions.None) //member this.content = String.Join(Environment.NewLine, this.lines) @@ -113,34 +113,34 @@ let defaultCommandLineSettings = generateConstInitGlobals = false icdPdus = None handleEmptySequences = false - } + } type LspWorkSpace = { logger : (string->int) files : LspFile list astRoot : Asn1AcnAst.AstRoot option } -with +with override this.ToString() = sprintf "%A" this -let private acnEncPropsPerType = +let private acnEncPropsPerType = [ (asn1Parser.INTEGER_TYPE, (acnParser.ENCODING, ["encoding pos-int"; "encoding twos-complement"; "encoding BCD"; "encoding ASCII"])) (asn1Parser.INTEGER_TYPE, (acnParser.SIZE, ["size"])) - (asn1Parser.INTEGER_TYPE, (acnParser.ENDIANNES, ["endianness big"; "endianness little"])) + (asn1Parser.INTEGER_TYPE, (acnParser.ENDIANNESS, ["endianness big"; "endianness little"])) (asn1Parser.INTEGER_TYPE, (acnParser.MAPPING_FUNCTION, ["mapping-function myFunction"])) (asn1Parser.REAL, (acnParser.ENCODING, ["encoding IEEE754-1985-32"; "encoding IEEE754-1985-32"])) - (asn1Parser.REAL, (acnParser.ENDIANNES, ["endianness big"; "endianness little"])) + (asn1Parser.REAL, (acnParser.ENDIANNESS, ["endianness big"; "endianness little"])) (asn1Parser.IA5String, (acnParser.ENCODING, ["encoding ASCII"])) (asn1Parser.IA5String, (acnParser.SIZE, ["size other-fld"; "size null-terminated"])) (asn1Parser.IA5String, (acnParser.TERMINATION_PATTERN, ["termination-pattern '00'H" ])) - (asn1Parser.OCTECT_STING, (acnParser.SIZE, ["size other-fld"; "size null-terminated"])) - (asn1Parser.OCTECT_STING, (acnParser.TERMINATION_PATTERN, ["termination-pattern '0000'H" ])) + (asn1Parser.OCTET_STRING, (acnParser.SIZE, ["size other-fld"; "size null-terminated"])) + (asn1Parser.OCTET_STRING, (acnParser.TERMINATION_PATTERN, ["termination-pattern '0000'H" ])) (asn1Parser.BIT_STRING_TYPE, (acnParser.SIZE, ["size other-fld"; "size null-terminated"])) (asn1Parser.BIT_STRING_TYPE, (acnParser.TERMINATION_PATTERN, ["termination-pattern '0000'H" ])) @@ -151,17 +151,17 @@ let private acnEncPropsPerType = (asn1Parser.ENUMERATED_TYPE, (acnParser.ENCODING, ["encoding pos-int"; "encoding twos-complement"; "encoding BCD"; "encoding ASCII"])) (asn1Parser.ENUMERATED_TYPE, (acnParser.SIZE, ["size"])) - (asn1Parser.ENUMERATED_TYPE, (acnParser.ENDIANNES, ["endianness big"; "endianness little"])) + (asn1Parser.ENUMERATED_TYPE, (acnParser.ENDIANNESS, ["endianness big"; "endianness little"])) (asn1Parser.ENUMERATED_TYPE, (acnParser.MAPPING_FUNCTION, ["mapping-function myFunction"])) (asn1Parser.ENUMERATED_TYPE, (acnParser.ENCODE_VALUES, ["encode-values"])) (asn1Parser.BOOLEAN, (acnParser.TRUE_VALUE, ["true-value '1'B"])) (asn1Parser.BOOLEAN, (acnParser.FALSE_VALUE, ["false-value '1'B"])) - + (asn1Parser.NULL, (acnParser.PATTERN, ["pattern '1'B"])) (asn1Parser.CHOICE_TYPE, (acnParser.DETERMINANT, ["determinant other-fld"])) - ] + ] let getTypeAcnProps typeKind = let actType = @@ -174,9 +174,9 @@ let getTypeAcnProps typeKind = let isAsn1File (fn:string) = fn.ToLower().EndsWith("asn1") || fn.ToLower().EndsWith("asn") -let isAcnFile (fn:string) = fn.ToLower().EndsWith("acn") +let isAcnFile (fn:string) = fn.ToLower().EndsWith("acn") -let tryGetFileType filename = +let tryGetFileType filename = match isAsn1File filename with | true -> Some LspAsn1 | false -> @@ -190,7 +190,7 @@ let isInside (range : LspRange) (pos: LspPos) = elif range.start.line <= pos.line && pos.line < range.end_.line then range.start.charPos <= pos.charPos elif range.start.line = pos.line && pos.line = range.end_.line then range.start.charPos <= pos.charPos && pos.charPos <= range.end_.charPos else false - + (* Returns the antlr tree nodes based from the leaf to the root based on the current position (line, charpos) @@ -205,11 +205,11 @@ let getTreeNodesByPosition (fn:LspFile) (lspPos:LspPos) = | false -> () | true -> yield r - for c in r.Children do + for c in r.Children do yield! getTreeNodesByPosition_aux tokens c - } |> Seq.toList + } |> Seq.toList - let ret = getTreeNodesByPosition_aux fn.tokens fn.antlrResult.rootItem + let ret = getTreeNodesByPosition_aux fn.tokens fn.antlrResult.rootItem List.rev ret @@ -263,7 +263,7 @@ let rec getAcnTypePathByITree (nodes:ITree list) = | Some lid -> [lid.Text] | None -> ["#"] // Sequence Of case - nodes |> + nodes |> List.rev |> //node are in reverse order, so reverse them List.choose(fun z -> match z.Type with @@ -272,11 +272,11 @@ let rec getAcnTypePathByITree (nodes:ITree list) = | _ -> None) |> List.collect id - + type Asn1TypeDef = Asn1TypeDef of ITree -let getAsn1Type (Asn1TypeDef typeDef:Asn1TypeDef) = +let getAsn1Type (Asn1TypeDef typeDef:Asn1TypeDef) = let children = getTreeChildren(typeDef) let typeNodes = children |> List.filter(fun x -> (not (CreateAsn1AstFromAntlrTree.ConstraintNodes |> List.exists(fun y -> y=x.Type) ) ) && (x.Type <> asn1Parser.TYPE_TAG) ) let typeNode = List.head(typeNodes) @@ -292,9 +292,9 @@ let rec getAsn1TypeDefinitionByPath (asn1Trees:AntlrParserResult list) (bResolve let typeNode = getAsn1Type typeDef match typeNode.Type with |asn1Parser.REFERENCED_TYPE -> - let refType = + let refType = match getTreeChildren(typeNode) |> List.filter(fun x -> x.Type<> asn1Parser.ACTUAL_PARAM_LIST) with - | refTypeName::[] -> + | refTypeName::[] -> let mdTree = typeNode.GetAncestor(asn1Parser.MODULE_DEF) let mdName = mdTree.GetChild(0).Text let imports = mdTree.GetChildrenByType(asn1Parser.IMPORTS_FROM_MODULE) @@ -306,10 +306,10 @@ let rec getAsn1TypeDefinitionByPath (asn1Trees:AntlrParserResult list) (bResolve | _ -> None match refType with | None -> None - | Some (x1, x2) -> + | Some (x1, x2) -> match getModuleByName x1 with | None -> None - | Some md -> + | Some md -> let tas = getTasByName md x2 match tas with | None -> None @@ -328,30 +328,30 @@ let rec getAsn1TypeDefinitionByPath (asn1Trees:AntlrParserResult list) (bResolve let typeNode = List.head(typeNodes) match path with - | [] -> + | [] -> match bResolveRefType with | true -> resolveReferenceType (Asn1TypeDef typeDef) | false -> Some (Asn1TypeDef typeDef) | x1::xs -> match typeNode.Type with - | asn1Parser.CHOICE_TYPE -> + | asn1Parser.CHOICE_TYPE -> let childItems = getChildrenByType(typeNode, asn1Parser.CHOICE_ITEM) match childItems |> Seq.tryFind(fun ch -> x1 = ch.GetChild(0).Text) with - | Some ch -> + | Some ch -> let typeDef = getChildByType(ch, asn1Parser.TYPE_DEF) getTypeByPath (Asn1TypeDef typeDef) xs | None -> None - | asn1Parser.SEQUENCE_TYPE -> + | asn1Parser.SEQUENCE_TYPE -> let childItems = match getOptionChildByType(typeNode, asn1Parser.SEQUENCE_BODY) with | Some(sequenceBody) -> getChildrenByType(sequenceBody, asn1Parser.SEQUENCE_ITEM) | None -> [] match childItems |> Seq.tryFind(fun ch -> x1 = ch.GetChild(0).Text) with - | Some ch -> + | Some ch -> let typeDef = getChildByType(ch, asn1Parser.TYPE_DEF) getTypeByPath (Asn1TypeDef typeDef) xs | None -> None - | asn1Parser.SEQUENCE_OF_TYPE when x1="#" -> + | asn1Parser.SEQUENCE_OF_TYPE when x1="#" -> let typeDef = getChildByType(typeNode, asn1Parser.TYPE_DEF) getTypeByPath (Asn1TypeDef typeDef) xs |asn1Parser.REFERENCED_TYPE -> @@ -367,9 +367,9 @@ let rec getAsn1TypeDefinitionByPath (asn1Trees:AntlrParserResult list) (bResolve | x1::x2::xs -> match getModuleByName x1 with | None -> None - | Some md -> + | Some md -> let tas = getTasByName md x2 match tas with | None -> None - | Some ts -> + | Some ts -> getTypeByPath (Asn1TypeDef (ts.GetChild 1)) xs diff --git a/FrontEndAst/MapParamAstToNonParamAst.fs b/FrontEndAst/MapParamAstToNonParamAst.fs index a406daf81..9fb39d1cf 100644 --- a/FrontEndAst/MapParamAstToNonParamAst.fs +++ b/FrontEndAst/MapParamAstToNonParamAst.fs @@ -17,9 +17,6 @@ open System.Numerics open Antlr.Runtime.Tree open Antlr.Runtime open CommonTypes -open AbstractMacros -open AbstractMacros -open AbstractMacros open FsUtils @@ -49,7 +46,7 @@ let visitRefType (md:string) (ts:string) : UserDefinedTypeScope= // {UserDefinedTypeScope.typeID=[MD md; VA vs]; asn1TypeName=None; asn1VarName=Some vs;varID=[]} let visitSeqChild (s:UserDefinedTypeScope) (ch:ParameterizedAsn1Ast.ChildInfo) : UserDefinedTypeScope= - s@[SEQ_CHILD ch.Name.Value] + s@[SEQ_CHILD (ch.Name.Value, ch.Optionality.IsSome)] let visitChoiceChild (s:UserDefinedTypeScope) (ch:ParameterizedAsn1Ast.ChildInfo) : UserDefinedTypeScope= s@[CH_CHILD (ch.Name.Value, ToC2 ch.Name.Value, "")] @@ -62,31 +59,31 @@ let visitValueVas (vs:ParameterizedAsn1Ast.ValueAssignment) : UserDefinedVarSco [VA2 vs.Name.Value] -let visitDefaultValue () : UserDefinedVarScope = +let visitDefaultValue () : UserDefinedVarScope = [DV] -let visitNamedItemValue (nm:ParameterizedAsn1Ast.NamedItem) : UserDefinedVarScope= +let visitNamedItemValue (nm:ParameterizedAsn1Ast.NamedItem) : UserDefinedVarScope= [NI nm.Name.Value] -let visitConstraint (s:UserDefinedVarScope) : UserDefinedVarScope= +let visitConstraint (s:UserDefinedVarScope) : UserDefinedVarScope= s@[CON 0] -let visitSilbingConstraint (s:UserDefinedVarScope) : UserDefinedVarScope = - let idx, xs = +let visitSiblingConstraint (s:UserDefinedVarScope) : UserDefinedVarScope = + let idx, xs = match s |> List.rev with | (CON idx)::xs -> idx, xs - | _ -> raise(BugErrorException "invalid call to visitSilbingConstraint") + | _ -> raise(BugErrorException "invalid call to visitSiblingConstraint") xs@[CON (idx+1)] -let visitValue (s:UserDefinedVarScope) :UserDefinedVarScope = +let visitValue (s:UserDefinedVarScope) :UserDefinedVarScope = s @[VL 0] -let visitSilbingValue (s:UserDefinedVarScope) :UserDefinedVarScope = - let idx, xs = +let visitSiblingValue (s:UserDefinedVarScope) :UserDefinedVarScope = + let idx, xs = match s |> List.rev with | (VL idx)::xs -> idx, xs - | _ -> raise(BugErrorException "invalid call to visitSilbingConstraint") + | _ -> raise(BugErrorException "invalid call to visitSiblingConstraint") xs@[VL (idx+1)] let visitSeqOfValue (s:UserDefinedVarScope) idx :UserDefinedVarScope = @@ -107,12 +104,12 @@ let rec getSequenceChildren (r:ParameterizedAsn1Ast.AstRoot) (input:list yield! getSequenceChildren r children - | _ -> raise(SemanticError(ts.Location, "Expecting SEQUENCE type")) + | _ -> raise(SemanticError(ts.Location, "Expecting SEQUENCE type")) }|> Seq.toList let rec getActualKind r kind = match kind with - | ParameterizedAsn1Ast.ReferenceType(md, ts,_, _) -> + | ParameterizedAsn1Ast.ReferenceType(md, ts,_, _) -> let newTas = ParameterizedAsn1Ast.getTypeAssignment r md ts getActualKind r newTas.Type.Kind | _ -> kind @@ -122,7 +119,7 @@ let rec MapAsn1Value (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.A let rec getActualKindAndModule r kind = let rec getActualaux r kind modName= match kind with - | ParameterizedAsn1Ast.ReferenceType(md, ts,_, _) -> + | ParameterizedAsn1Ast.ReferenceType(md, ts,_, _) -> let mdl = ParameterizedAsn1Ast.getModuleByName r md let newTas = ParameterizedAsn1Ast.getTypeAssignment r md ts getActualaux r newTas.Type.Kind (Some mdl.Name) @@ -134,7 +131,7 @@ let rec MapAsn1Value (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.A match vk with |ParameterizedAsn1Ast.IntegerValue(v) -> Asn1Ast.IntegerValue v |ParameterizedAsn1Ast.RealValue(v) -> Asn1Ast.RealValue v - |ParameterizedAsn1Ast.StringValue(v) -> + |ParameterizedAsn1Ast.StringValue(v) -> let actKind, mdName = getActualKindAndModule r t.Kind match actKind with | ParameterizedAsn1Ast.TimeType tmClss -> Asn1Ast.TimeValue (CommonTypes.createTimeValueFromString tmClss v) @@ -142,55 +139,55 @@ let rec MapAsn1Value (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.A |ParameterizedAsn1Ast.BooleanValue(v) -> Asn1Ast.BooleanValue v |ParameterizedAsn1Ast.BitStringValue(v) -> Asn1Ast.BitStringValue v |ParameterizedAsn1Ast.OctetStringValue v -> Asn1Ast.OctetStringValue v - |ParameterizedAsn1Ast.RefValue(v1,v2) -> + |ParameterizedAsn1Ast.RefValue(v1,v2) -> let actKind, mdName = getActualKindAndModule r t.Kind match actKind with - | ParameterizedAsn1Ast.Enumerated(items) -> + | ParameterizedAsn1Ast.Enumerated(items) -> match mdName with | None -> Asn1Ast.RefValue(v1,v2) | Some(s) -> Asn1Ast.RefValue(s,v2) | _ -> Asn1Ast.RefValue(v1,v2) - |ParameterizedAsn1Ast.SeqOfValue(vals) -> + |ParameterizedAsn1Ast.SeqOfValue(vals) -> match actKind with | ParameterizedAsn1Ast.SequenceOf(ch) -> Asn1Ast.SeqOfValue(vals |> List.mapi (fun idx v -> MapAsn1Value r ch typeScope (visitSeqOfValue variableScope idx) v)) - | ParameterizedAsn1Ast.BitString namedBits -> + | ParameterizedAsn1Ast.BitString namedBits -> let actType = ParameterizedAsn1Ast.GetActualType t r let cons = actType.Constraints |> List.map (ParameterizedAsn1Ast.getBitStringConstraint r t) let uperRange = ParameterizedAsn1Ast.getBitStringUperRange cons v.Location - let bitPos = + let bitPos = vals |> - List.map(fun chV -> + List.map(fun chV -> match chV.Kind with - | ParameterizedAsn1Ast.RefValue (_,refVal) -> + | ParameterizedAsn1Ast.RefValue (_,refVal) -> match namedBits |> Seq.tryFind(fun z -> z.Name.Value = refVal.Value) with | None -> raise (SemanticError(v.Location, (sprintf "Expecting a BIT STRING value. '%s' is not defined as a named bit" refVal.Value))) - | Some nb -> + | Some nb -> match nb._value with | CommonTypes.IDV_IntegerValue intVal -> intVal.Value | CommonTypes.IDV_DefinedValue (mdVal, refVal) -> ParameterizedAsn1Ast.GetValueAsInt (ParameterizedAsn1Ast.GetBaseValue mdVal refVal r) r | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a BIT STRING value but found a SEQUENCE OF value" ))) ) |> Set.ofList - + //printfn "uperRange = %A" uperRange - let maxValue = + let maxValue = match uperRange with - | Concrete(a, b) -> + | Concrete(a, b) -> //printf "maxValue : %A, %A\n" a b BigInteger (b-1u) | _ -> bitPos.MaximumElement //printf "maxValue : %A\n" maxValue - let bitStrVal = + let bitStrVal = [0I .. maxValue] |> List.map(fun bi -> if bitPos.Contains bi then '1' else '0') |> Seq.StrJoin "" Asn1Ast.BitStringValue ({StringLoc.Value = bitStrVal; Location = v.Location}) - | ParameterizedAsn1Ast.IA5String -> + | ParameterizedAsn1Ast.IA5String -> let partVals = - vals |> + vals |> List.map(fun v -> match v.Kind with | ParameterizedAsn1Ast.StringValue vl -> CStringValue vl.Value - | ParameterizedAsn1Ast.RefValue (_, vs) -> + | ParameterizedAsn1Ast.RefValue (_, vs) -> match vs.Value with | "cr" -> SpecialCharacter CarriageReturn | "lf" -> SpecialCharacter LineFeed @@ -198,10 +195,10 @@ let rec MapAsn1Value (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.A | "nul" -> SpecialCharacter NullCharacter | _ -> raise(SemanticError(v.Location, "Expecting a IA5String value")) | _ -> raise(SemanticError(v.Location, "Expecting a IA5String value"))) - + Asn1Ast.StringValue (partVals, v.Location) | _ -> raise(SemanticError(v.Location, "Expecting a SEQUENCE OF value")) - |ParameterizedAsn1Ast.SeqValue(vals) -> + |ParameterizedAsn1Ast.SeqValue(vals) -> match actKind with |ParameterizedAsn1Ast.Sequence(children) -> let children = getSequenceChildren r children @@ -211,14 +208,14 @@ let rec MapAsn1Value (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.A | _ -> raise(SemanticError(nm.Location, sprintf "Unknown component name '%s'" nm.Value)) Asn1Ast.SeqValue(vals |> List.map mapChildVal) | _ -> raise(SemanticError(v.Location, "Expecting a SEQUENCE value")) - |ParameterizedAsn1Ast.ChValue(n,v) -> + |ParameterizedAsn1Ast.ChValue(n,v) -> match actKind with |ParameterizedAsn1Ast.Choice(children) -> match children |> Seq.tryFind(fun x -> x.Name=n) with | Some(child) -> Asn1Ast.ChValue(n, MapAsn1Value r child.Type typeScope (visitSeqChildValue variableScope n.Value) v) | None -> raise(SemanticError(n.Location, sprintf "Unknown alternative name '%s'" n.Value)) | _ -> raise(SemanticError(v.Location, "Expecting a CHOICE value")) - + |ParameterizedAsn1Ast.NullValue -> Asn1Ast.NullValue |ParameterizedAsn1Ast.ObjOrRelObjIdValue items -> Asn1Ast.ObjOrRelObjIdValue items @@ -287,67 +284,68 @@ and MapNamedConstraint (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast | Some(child) -> child.Type | _ -> raise(SemanticError(x.Name.Location, sprintf "Unexpected constraint type" )) { - Asn1Ast.NamedConstraint.Name = x.Name; + Asn1Ast.NamedConstraint.Name = x.Name; Mark = match x.Mark with | ParameterizedAsn1Ast.NoMark -> Asn1Ast.NoMark | ParameterizedAsn1Ast.MarkPresent -> Asn1Ast.MarkPresent | ParameterizedAsn1Ast.MarkAbsent -> Asn1Ast.MarkAbsent | ParameterizedAsn1Ast.MarkOptional -> Asn1Ast.MarkOptional - Contraint = match x.Contraint with - | None -> None - | Some(cc) -> Some (MapAsn1Constraint r childType typeScope cs cc) + Constraint = + match x.Constraint with + | None -> None + | Some(cc) -> Some (MapAsn1Constraint r childType typeScope cs cc) } and MapAsn1Constraint (r:ParameterizedAsn1Ast.AstRoot) (t: ParameterizedAsn1Ast.Asn1Type) typeScope cs (c:ParameterizedAsn1Ast.Asn1Constraint) :Asn1Ast.Asn1Constraint = match c with - | ParameterizedAsn1Ast.Asn1Constraint.SingleValueContraint(s, v) -> Asn1Ast.SingleValueContraint (s, MapAsn1Value r t typeScope (visitValue cs) v) - | ParameterizedAsn1Ast.Asn1Constraint.RangeContraint(s, v1,v2,b1,b2) -> + | ParameterizedAsn1Ast.Asn1Constraint.SingleValueConstraint(s, v) -> Asn1Ast.SingleValueConstraint (s, MapAsn1Value r t typeScope (visitValue cs) v) + | ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint(s, v1,v2,b1,b2) -> let vs1 = visitValue cs - let vs2 = visitSilbingValue vs1 + let vs2 = visitSiblingValue vs1 - Asn1Ast.RangeContraint(s, MapAsn1Value r t typeScope vs1 v1, MapAsn1Value r t typeScope vs2 v2,b1,b2) - | ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_val_MAX(s, v,b) -> Asn1Ast.RangeContraint_val_MAX (s, MapAsn1Value r t typeScope (visitValue cs) v, b) - | ParameterizedAsn1Ast.Asn1Constraint.RangeContraint_MIN_val(s, v,b) -> Asn1Ast.RangeContraint_MIN_val (s, MapAsn1Value r t typeScope (visitValue cs) v, b) + Asn1Ast.RangeConstraint(s, MapAsn1Value r t typeScope vs1 v1, MapAsn1Value r t typeScope vs2 v2,b1,b2) + | ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_val_MAX(s, v,b) -> Asn1Ast.RangeConstraint_val_MAX (s, MapAsn1Value r t typeScope (visitValue cs) v, b) + | ParameterizedAsn1Ast.Asn1Constraint.RangeConstraint_MIN_val(s, v,b) -> Asn1Ast.RangeConstraint_MIN_val (s, MapAsn1Value r t typeScope (visitValue cs) v, b) | ParameterizedAsn1Ast.TypeInclusionConstraint(s, s1,s2) -> Asn1Ast.TypeInclusionConstraint(s, s1,s2) - | ParameterizedAsn1Ast.Asn1Constraint.SizeContraint(s, c) -> Asn1Ast.SizeContraint(s, MapAsn1Constraint r {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.Integer; Constraints = []; Location=emptyLocation;parameterizedTypeInstance=false;acnInfo=None;unitsOfMeasure = None; moduleName=t.moduleName} typeScope (visitConstraint cs) c) - | ParameterizedAsn1Ast.AlphabetContraint(s,c) -> Asn1Ast.AlphabetContraint(s, MapAsn1Constraint r {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.IA5String; Constraints = []; Location=emptyLocation;parameterizedTypeInstance=false;acnInfo=None;unitsOfMeasure = None; moduleName=t.moduleName} typeScope (visitConstraint cs) c) - | ParameterizedAsn1Ast.UnionConstraint(s, c1,c2, b) -> + | ParameterizedAsn1Ast.Asn1Constraint.SizeConstraint(s, c) -> Asn1Ast.SizeConstraint(s, MapAsn1Constraint r {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.Integer; Constraints = []; Location=emptyLocation;parameterizedTypeInstance=false;acnInfo=None;unitsOfMeasure = None; moduleName=t.moduleName} typeScope (visitConstraint cs) c) + | ParameterizedAsn1Ast.AlphabetConstraint(s,c) -> Asn1Ast.AlphabetConstraint(s, MapAsn1Constraint r {ParameterizedAsn1Ast.Asn1Type.Kind = ParameterizedAsn1Ast.IA5String; Constraints = []; Location=emptyLocation;parameterizedTypeInstance=false;acnInfo=None;unitsOfMeasure = None; moduleName=t.moduleName} typeScope (visitConstraint cs) c) + | ParameterizedAsn1Ast.UnionConstraint(s, c1,c2, b) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 Asn1Ast.UnionConstraint(s, MapAsn1Constraint r t typeScope cs1 c1, MapAsn1Constraint r t typeScope cs2 c2, b) - | ParameterizedAsn1Ast.IntersectionConstraint(s, c1,c2) -> + | ParameterizedAsn1Ast.IntersectionConstraint(s, c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 Asn1Ast.IntersectionConstraint(s, MapAsn1Constraint r t typeScope cs1 c1, MapAsn1Constraint r t typeScope cs2 c2) | ParameterizedAsn1Ast.AllExceptConstraint(s, c) -> Asn1Ast.AllExceptConstraint(s, MapAsn1Constraint r t typeScope (visitConstraint cs) c) - | ParameterizedAsn1Ast.ExceptConstraint(s, c1,c2) -> + | ParameterizedAsn1Ast.ExceptConstraint(s, c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 Asn1Ast.ExceptConstraint(s, MapAsn1Constraint r t typeScope cs1 c1, MapAsn1Constraint r t typeScope cs2 c2) | ParameterizedAsn1Ast.RootConstraint(s, c1) -> Asn1Ast.RootConstraint(s, MapAsn1Constraint r t typeScope (visitConstraint cs) c1) - | ParameterizedAsn1Ast.RootConstraint2(s, c1,c2) -> + | ParameterizedAsn1Ast.RootConstraint2(s, c1,c2) -> let cs1 = visitConstraint cs - let cs2 = visitSilbingConstraint cs1 + let cs2 = visitSiblingConstraint cs1 Asn1Ast.RootConstraint2(s, MapAsn1Constraint r t typeScope cs2 c1, MapAsn1Constraint r t typeScope cs2 c2) - | ParameterizedAsn1Ast.WithComponentConstraint(s, c, loc) -> + | ParameterizedAsn1Ast.WithComponentConstraint(s, c, loc) -> let akind = getActualKind r t.Kind match akind with - | ParameterizedAsn1Ast.SequenceOf(child) -> + | ParameterizedAsn1Ast.SequenceOf(child) -> Asn1Ast.WithComponentConstraint(s, (MapAsn1Constraint r child typeScope (visitConstraint cs) c), loc) | _ -> raise(SemanticError(emptyLocation,"Unexpected constraint type")) - | ParameterizedAsn1Ast.WithComponentsConstraint(s, ncs) -> - Asn1Ast.WithComponentsConstraint(s, ncs|> foldMap (fun cs c -> + | ParameterizedAsn1Ast.WithComponentsConstraint(s, ncs) -> + Asn1Ast.WithComponentsConstraint(s, ncs|> foldMap (fun cs c -> let newC = MapNamedConstraint r t typeScope (visitConstraint cs) c - let newSs = visitSilbingConstraint cs + let newSs = visitSiblingConstraint cs newC, newSs) cs |> fst ) and MapAsn1Type (r:ParameterizedAsn1Ast.AstRoot) typeScope (t:ParameterizedAsn1Ast.Asn1Type) :Asn1Ast.Asn1Type = let aux kind : Asn1Ast.Asn1Type= - let newCons = - t.Constraints |> - foldMap (fun ss c -> + let newCons = + t.Constraints |> + foldMap (fun ss c -> let newC = MapAsn1Constraint r t typeScope ss c - let newSs = visitSilbingConstraint ss + let newSs = visitSiblingConstraint ss newC, newSs) (visitConstraint []) |> fst { @@ -358,7 +356,7 @@ and MapAsn1Type (r:ParameterizedAsn1Ast.AstRoot) typeScope (t:ParameterizedAsn1A unitsOfMeasure = t.unitsOfMeasure moduleName = t.moduleName acnInfo = t.acnInfo - } + } match t.Kind with | ParameterizedAsn1Ast.Integer -> aux Asn1Ast.Integer | ParameterizedAsn1Ast.Real -> aux Asn1Ast.Real @@ -373,7 +371,7 @@ and MapAsn1Type (r:ParameterizedAsn1Ast.AstRoot) typeScope (t:ParameterizedAsn1A | ParameterizedAsn1Ast.RelativeObjectIdentifier -> aux Asn1Ast.RelativeObjectIdentifier | ParameterizedAsn1Ast.Enumerated(items)-> aux (Asn1Ast.Enumerated(items |> List.map (MapNamedItem r t.moduleName typeScope))) | ParameterizedAsn1Ast.SequenceOf(child)-> aux (Asn1Ast.SequenceOf(MapAsn1Type r (visitSeqOfChild typeScope) child)) - | ParameterizedAsn1Ast.Sequence(children) -> + | ParameterizedAsn1Ast.Sequence(children) -> let children = getSequenceChildren r children aux (Asn1Ast.Sequence(children |> List.map (MapChildInfo r typeScope true) )) | ParameterizedAsn1Ast.Choice(children) -> aux (Asn1Ast.Choice(children |> List.map (MapChildInfo r typeScope false) )) @@ -382,7 +380,7 @@ and MapAsn1Type (r:ParameterizedAsn1Ast.AstRoot) typeScope (t:ParameterizedAsn1A | [] -> aux (Asn1Ast.ReferenceType({Asn1Ast.ReferenceType.modName = mdName; tasName = ts; tabularized = false; refEnc= refEnc})) | _ -> raise(BugErrorException "") - + let MapTypeAssignment (r:ParameterizedAsn1Ast.AstRoot) (m:ParameterizedAsn1Ast.Asn1Module) (tas:ParameterizedAsn1Ast.TypeAssignment) :Asn1Ast.TypeAssignment = { @@ -405,7 +403,7 @@ let MapValueAssignment (r:ParameterizedAsn1Ast.AstRoot) (m:ParameterizedAsn1Ast. Asn1Ast.ValueAssignment.Name = vas.Name Type = MapAsn1Type r typeScope vas.Type Value = MapAsn1Value r vas.Type typeScope varScope vas.Value - //Scope = + //Scope = // match vas.Scope with // | ParameterizedAsn1Ast.GlobalScope -> Asn1Ast.GlobalScope // | ParameterizedAsn1Ast.TypeScope(m,t) -> Asn1Ast.TypeScope(m,t) @@ -427,7 +425,7 @@ let MapModule (r:ParameterizedAsn1Ast.AstRoot) (m:ParameterizedAsn1Ast.Asn1Modul | ParameterizedAsn1Ast.All -> Asn1Ast.All | ParameterizedAsn1Ast.OnlySome(lst) -> Asn1Ast.OnlySome(lst) Comments = m.Comments - postion = m.postion + position = m.position } @@ -441,10 +439,9 @@ let MapFile (r:ParameterizedAsn1Ast.AstRoot) (f:ParameterizedAsn1Ast.Asn1File) : let DoWork (r:ParameterizedAsn1Ast.AstRoot) : Asn1Ast.AstRoot = - let r = RemoveParamterizedTypes.DoWork r + let r = RemoveParameterizedTypes.DoWork r { Asn1Ast.AstRoot.Files = r.Files |> List.map (MapFile r) args = r.args - + } - \ No newline at end of file diff --git a/FrontEndAst/ParameterizedAsn1Ast.fs b/FrontEndAst/ParameterizedAsn1Ast.fs index dae994b04..3810416e7 100644 --- a/FrontEndAst/ParameterizedAsn1Ast.fs +++ b/FrontEndAst/ParameterizedAsn1Ast.fs @@ -22,7 +22,7 @@ open System -type RangeTypeConstraint<'v1,'v2> = +type RangeTypeConstraint<'v1,'v2> = | RangeUnionConstraint of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2>*bool //left,righ, virtual constraint | RangeIntersectionConstraint of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeAllExceptConstraint of RangeTypeConstraint<'v1,'v2> @@ -30,13 +30,13 @@ type RangeTypeConstraint<'v1,'v2> = | RangeRootConstraint of RangeTypeConstraint<'v1,'v2> | RangeRootConstraint2 of RangeTypeConstraint<'v1,'v2>*RangeTypeConstraint<'v1,'v2> | RangeSingleValueConstraint of 'v2 - | RangeContraint of ('v1) *('v1)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | RangeContraint_val_MAX of ('v1) *bool //min, InclusiveMin(=true) - | RangeContraint_MIN_val of ('v1) *bool //max, InclusiveMax(=true) + | RangeConstraint of ('v1) *('v1)*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | RangeConstraint_val_MAX of ('v1) *bool //min, InclusiveMin(=true) + | RangeConstraint_MIN_val of ('v1) *bool //max, InclusiveMax(=true) type PosIntTypeConstraint = RangeTypeConstraint -type SizableTypeConstraint<'v> = +type SizableTypeConstraint<'v> = | SizeUnionConstraint of SizableTypeConstraint<'v>*SizableTypeConstraint<'v>*bool //left,righ, virtual constraint | SizeIntersectionConstraint of SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeAllExceptConstraint of SizableTypeConstraint<'v> @@ -44,7 +44,7 @@ type SizableTypeConstraint<'v> = | SizeRootConstraint of SizableTypeConstraint<'v> | SizeRootConstraint2 of SizableTypeConstraint<'v>*SizableTypeConstraint<'v> | SizeSingleValueConstraint of 'v - | SizeContraint of PosIntTypeConstraint + | SizeConstraint of PosIntTypeConstraint type AstRoot = { @@ -65,7 +65,7 @@ and Asn1Module = { Imports : list Exports : Exports Comments : string array - postion : SrcLoc*SrcLoc //start pos, end pos + position : SrcLoc*SrcLoc //start pos, end pos } and Exports = @@ -108,7 +108,7 @@ and ValueAssignment = { and ValueScope = | GlobalScope - | TypeScope of StringLoc*StringLoc + | TypeScope of StringLoc*StringLoc @@ -123,19 +123,19 @@ and Asn1Type = { } and Asn1TypeKind = - | Integer - | Real - | IA5String + | Integer + | Real + | IA5String | NumericString - | OctetString + | OctetString | ObjectIdentifier | RelativeObjectIdentifier | TimeType of TimeTypeClass - | NullType + | NullType | BitString of list - | Boolean + | Boolean | Enumerated of list - | SequenceOf of Asn1Type + | SequenceOf of Asn1Type | Sequence of list | Choice of list | ReferenceType of StringLoc*StringLoc*(ContainedInOctOrBitString option)*list @@ -168,10 +168,10 @@ and ChildInfo = { } -and Asn1Optionality = +and Asn1Optionality = | AlwaysAbsent | AlwaysPresent - | Optional + | Optional | Default of Asn1Value @@ -183,7 +183,7 @@ and Asn1Value = { - + and Asn1ValueKind = | IntegerValue of IntLoc @@ -198,17 +198,17 @@ and Asn1ValueKind = | ChValue of StringLoc*Asn1Value | NullValue | EmptyList - | ObjOrRelObjIdValue of ObjectIdentifierValueCompoent list + | ObjOrRelObjIdValue of ObjectIdentifierValueComponent list -and Asn1Constraint = - | SingleValueContraint of string*Asn1Value - | RangeContraint of string*Asn1Value*Asn1Value*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) - | RangeContraint_val_MAX of string*Asn1Value*bool //min, InclusiveMin(=true) - | RangeContraint_MIN_val of string*Asn1Value*bool //max, InclusiveMax(=true) - | TypeInclusionConstraint of string*StringLoc*StringLoc - | SizeContraint of string*Asn1Constraint - | AlphabetContraint of string*Asn1Constraint +and Asn1Constraint = + | SingleValueConstraint of string*Asn1Value + | RangeConstraint of string*Asn1Value*Asn1Value*bool*bool //min, max, InclusiveMin(=true), InclusiveMax(=true) + | RangeConstraint_val_MAX of string*Asn1Value*bool //min, InclusiveMin(=true) + | RangeConstraint_MIN_val of string*Asn1Value*bool //max, InclusiveMax(=true) + | TypeInclusionConstraint of string*StringLoc*StringLoc + | SizeConstraint of string*Asn1Constraint + | AlphabetConstraint of string*Asn1Constraint | UnionConstraint of string*Asn1Constraint*Asn1Constraint*bool //left,righ, virtual constraint | IntersectionConstraint of string*Asn1Constraint*Asn1Constraint | AllExceptConstraint of string*Asn1Constraint @@ -220,7 +220,7 @@ and Asn1Constraint = and NamedConstraint = { Name:StringLoc; - Contraint:Asn1Constraint option + Constraint:Asn1Constraint option Mark:NamedConstraintMark } @@ -249,7 +249,7 @@ let getTypeAssignment r m t = m |> getModuleByName r |> getTasByName t let rec TryGetActualType (t:Asn1Type) (r:AstRoot) = match t.Kind with | ReferenceType(mn,tasname, _, _) -> - let mods = r.Files |> List.collect (fun x -> x.Modules) + let mods = r.Files |> List.collect (fun x -> x.Modules) match mods |> Seq.tryFind(fun m -> m.Name = mn) with | Some newmod -> match newmod.TypeAssignments |> Seq.tryFind(fun tas -> tas.Name.Value = tasname.Value) with @@ -265,19 +265,19 @@ let rec GetActualType (t:Asn1Type) (r:AstRoot) = match TryGetActualType t r with | Some t -> t | None -> raise(SemanticError(tasname.Location, sprintf "Reference type: %s.%s can not be resolved" mn.Value tasname.Value )) - + | _ -> t type Asn1Module with member m.GetValueAsigByName(name:StringLoc) (r:AstRoot) = let (n,loc) = name.AsTupple - let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) + let value = m.ValueAssignments |> Seq.tryFind(fun x -> x.Name = name) match value with | Some(v) -> v | None -> - let othMods = m.Imports - |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) + let othMods = m.Imports + |> Seq.filter(fun imp -> imp.Values |> Seq.exists(fun vname -> vname = name)) |> Seq.map(fun imp -> imp.Name) |> Seq.toList match othMods with | firstMod::tail -> (getModuleByName r firstMod).GetValueAsigByName name r @@ -303,36 +303,36 @@ let rec GetValueAsInt (v:Asn1Value) r= | _ -> raise(SemanticError (v.Location, sprintf "Expecting Integer value")) -let foldBConstraint - singleValueContraintFunc - rangeContraintFunc - rangeContraint_val_MAXFunc - rangeContraint_MIN_valFunc - sizeContraintFunc - alphabetContraintFunc - unionConstraintFunc - intersectionConstraintFunc - allExceptConstraintFunc - exceptConstraintFunc - rootConstraintFunc - rootConstraint2Func - typeInclusionFnc - withComponentConstraintFunc - withComponentsConstraintFunc - (c:Asn1Constraint) = +let foldBConstraint + (singleValueConstraintFunc: Asn1Value -> 'a) + (rangeConstraintFunc: Asn1Value -> Asn1Value -> bool -> bool -> 'a) + (rangeConstraint_val_MAXFunc: Asn1Value -> bool -> 'a) + (rangeConstraint_MIN_valFunc: Asn1Value -> bool -> 'a) + (sizeConstraintFunc: Asn1Constraint -> 'a) + (alphabetConstraintFunc: Asn1Constraint -> 'a) + (unionConstraintFunc: Asn1Constraint -> Asn1Constraint -> bool -> 'a) + (intersectionConstraintFunc: Asn1Constraint -> Asn1Constraint -> 'a) + (allExceptConstraintFunc: Asn1Constraint -> 'a) + (exceptConstraintFunc: Asn1Constraint -> Asn1Constraint -> 'a) + (rootConstraintFunc: Asn1Constraint -> 'a) + (rootConstraint2Func: Asn1Constraint -> Asn1Constraint -> 'a) + (typeInclusionFnc: StringLoc -> StringLoc -> 'a) + (withComponentConstraintFunc: Asn1Constraint -> SrcLoc -> 'a) + (withComponentsConstraintFunc: NamedConstraint list -> 'a) + (c:Asn1Constraint) : 'a = match c with - |Asn1Constraint.SingleValueContraint (s,rv) -> singleValueContraintFunc rv - |Asn1Constraint.RangeContraint (s, rv1,rv2,b1,b2) -> rangeContraintFunc rv1 rv2 b1 b2 - |Asn1Constraint.RangeContraint_val_MAX (s, rv,b) -> rangeContraint_val_MAXFunc rv b - |Asn1Constraint.RangeContraint_MIN_val (s, rv,b) -> rangeContraint_MIN_valFunc rv b - |Asn1Constraint.SizeContraint (s, c) -> sizeContraintFunc c - |Asn1Constraint.AlphabetContraint (s, c) -> alphabetContraintFunc c - |Asn1Constraint.UnionConstraint (s, c1,c2,b) -> unionConstraintFunc c1 c2 b - |Asn1Constraint.IntersectionConstraint (s, c1,c2) -> intersectionConstraintFunc c1 c2 - |Asn1Constraint.AllExceptConstraint (s, c) -> allExceptConstraintFunc c - |Asn1Constraint.ExceptConstraint (s, c1,c2) -> exceptConstraintFunc c1 c2 - |Asn1Constraint.RootConstraint (s, c1) -> rootConstraintFunc c1 - |Asn1Constraint.RootConstraint2 (s, c1,c2) -> rootConstraint2Func c1 c2 + |Asn1Constraint.SingleValueConstraint (s,rv) -> singleValueConstraintFunc rv + |Asn1Constraint.RangeConstraint (s, rv1,rv2,b1,b2) -> rangeConstraintFunc rv1 rv2 b1 b2 + |Asn1Constraint.RangeConstraint_val_MAX (s, rv,b) -> rangeConstraint_val_MAXFunc rv b + |Asn1Constraint.RangeConstraint_MIN_val (s, rv,b) -> rangeConstraint_MIN_valFunc rv b + |Asn1Constraint.SizeConstraint (s, c) -> sizeConstraintFunc c + |Asn1Constraint.AlphabetConstraint (s, c) -> alphabetConstraintFunc c + |Asn1Constraint.UnionConstraint (s, c1,c2,b) -> unionConstraintFunc c1 c2 b + |Asn1Constraint.IntersectionConstraint (s, c1,c2) -> intersectionConstraintFunc c1 c2 + |Asn1Constraint.AllExceptConstraint (s, c) -> allExceptConstraintFunc c + |Asn1Constraint.ExceptConstraint (s, c1,c2) -> exceptConstraintFunc c1 c2 + |Asn1Constraint.RootConstraint (s, c1) -> rootConstraintFunc c1 + |Asn1Constraint.RootConstraint2 (s, c1,c2) -> rootConstraint2Func c1 c2 |Asn1Constraint.TypeInclusionConstraint (s, md,ts) -> typeInclusionFnc md ts |Asn1Constraint.WithComponentConstraint (s, c,l) -> withComponentConstraintFunc c l //raise(BugErrorException "Unexpected constraint type") |Asn1Constraint.WithComponentsConstraint (s, ncs) -> withComponentsConstraintFunc ncs //raise(BugErrorException "Unexpected constraint type") @@ -340,38 +340,38 @@ let foldBConstraint type BitStringConstraint = SizableTypeConstraint let rec private getRangeTypeConstraint valueGetter valueGetter2 (c:Asn1Constraint) = - foldBConstraint - (fun rv -> RangeTypeConstraint.RangeSingleValueConstraint (valueGetter2 rv )) - (fun rv1 rv2 b1 b2 -> RangeTypeConstraint.RangeContraint (valueGetter rv1 ,valueGetter rv2, b1,b2) ) - (fun rv b -> RangeTypeConstraint.RangeContraint_val_MAX (valueGetter rv, b)) - (fun rv b -> RangeTypeConstraint.RangeContraint_MIN_val (valueGetter rv, b)) - (fun c -> raise(BugErrorException "SizeContraint is not expected here")) - (fun c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun c1 c2 b -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeUnionConstraint (c1,c2,b)) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeIntersectionConstraint (c1,c2)) - (fun c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c - RangeAllExceptConstraint c) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + foldBConstraint + (fun rv -> RangeTypeConstraint.RangeSingleValueConstraint (valueGetter2 rv )) + (fun rv1 rv2 b1 b2 -> RangeTypeConstraint.RangeConstraint (valueGetter rv1 ,valueGetter rv2, b1,b2) ) + (fun rv b -> RangeTypeConstraint.RangeConstraint_val_MAX (valueGetter rv, b)) + (fun rv b -> RangeTypeConstraint.RangeConstraint_MIN_val (valueGetter rv, b)) + (fun c -> raise(BugErrorException "SizeConstraint is not expected here")) + (fun c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun c1 c2 b -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeUnionConstraint (c1,c2,b)) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeIntersectionConstraint (c1,c2)) + (fun c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c + RangeAllExceptConstraint c) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 RangeExceptConstraint (c1,c2)) - (fun c -> - let c = getRangeTypeConstraint valueGetter valueGetter2 c + (fun c -> + let c = getRangeTypeConstraint valueGetter valueGetter2 c RangeRootConstraint c) - (fun c1 c2 -> - let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 - let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 - RangeRootConstraint2 (c1,c2)) - (fun md ts -> raise(BugErrorException "Unexpected constraint type")) - (fun c -> raise(BugErrorException "Unexpected constraint type")) - (fun c -> raise(BugErrorException "Unexpected constraint type")) + (fun c1 c2 -> + let c1 = getRangeTypeConstraint valueGetter valueGetter2 c1 + let c2 = getRangeTypeConstraint valueGetter valueGetter2 c2 + RangeRootConstraint2 (c1,c2)) + (fun md ts -> raise(BugErrorException "Unexpected constraint type")) + (fun c -> raise(BugErrorException "Unexpected constraint type")) + (fun c -> raise(BugErrorException "Unexpected constraint type")) c @@ -384,150 +384,150 @@ let rec private getSizeTypeConstraint (r:AstRoot) valueGetter (c:Asn1Constraint | _ -> raise(SemanticError(v.Location, "Value is not of expected type")) - foldBConstraint - (fun rv -> SizeSingleValueConstraint (valueGetter rv)) + foldBConstraint + (fun rv -> SizeSingleValueConstraint (valueGetter rv)) (fun rv1 rv2 b1 b2 -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) (fun rv b -> raise(BugErrorException "Range constraint is not expected here")) - (fun c -> + (fun c -> let posIntCon = getRangeTypeConstraint (posIntValGetter r) (posIntValGetter r) c - SizableTypeConstraint.SizeContraint posIntCon) - (fun c -> raise(BugErrorException "AlphabetContraint is not expected here")) - (fun c1 c2 b -> + SizableTypeConstraint.SizeConstraint posIntCon) + (fun c -> raise(BugErrorException "AlphabetConstraint is not expected here")) + (fun c1 c2 b -> let c1 = getSizeTypeConstraint r valueGetter c1 - let c2 = getSizeTypeConstraint r valueGetter c2 - SizeUnionConstraint (c1,c2,b)) - (fun c1 c2 -> + let c2 = getSizeTypeConstraint r valueGetter c2 + SizeUnionConstraint (c1,c2,b)) + (fun c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SizeIntersectionConstraint (c1,c2)) - (fun c -> - let c = getSizeTypeConstraint r valueGetter c - SizeAllExceptConstraint c) - (fun c1 c2 -> + SizeIntersectionConstraint (c1,c2)) + (fun c -> + let c = getSizeTypeConstraint r valueGetter c + SizeAllExceptConstraint c) + (fun c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 SizeExceptConstraint (c1,c2)) - (fun c -> - let c = getSizeTypeConstraint r valueGetter c + (fun c -> + let c = getSizeTypeConstraint r valueGetter c SizeRootConstraint c) - (fun c1 c2 -> + (fun c1 c2 -> let c1 = getSizeTypeConstraint r valueGetter c1 let c2 = getSizeTypeConstraint r valueGetter c2 - SizeRootConstraint2 (c1,c2)) - (fun md ts -> raise(BugErrorException "Unexpected constraint type")) - (fun c -> raise(BugErrorException "Unexpected constraint type")) - (fun c -> raise(BugErrorException "Unexpected constraint type")) + SizeRootConstraint2 (c1,c2)) + (fun md ts -> raise(BugErrorException "Unexpected constraint type")) + (fun c -> raise(BugErrorException "Unexpected constraint type")) + (fun c -> raise(BugErrorException "Unexpected constraint type")) c -let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc +let foldRangeTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc rangeFunc range_val_max_func range_min_val_func - (c:RangeTypeConstraint<'v,'vr>) + (c:RangeTypeConstraint<'v,'vr>) (s:'UserState) = let rec loopRecursiveConstraint (c:RangeTypeConstraint<'v,'vr>) (s0:'UserState) = match c with - | RangeUnionConstraint(c1,c2,b) -> + | RangeUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | RangeIntersectionConstraint(c1,c2) -> + | RangeIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | RangeAllExceptConstraint(c1) -> + | RangeAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | RangeExceptConstraint(c1,c2) -> + | RangeExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | RangeRootConstraint(c1) -> + | RangeRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | RangeRootConstraint2(c1,c2) -> + | RangeRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | RangeSingleValueConstraint (v) -> singleValueFunc v s0 - | RangeTypeConstraint.RangeContraint((v1), (v2), b1,b2) -> rangeFunc v1 v2 b1 b2 s - | RangeTypeConstraint.RangeContraint_val_MAX ((v), b) -> range_val_max_func v b s - | RangeTypeConstraint.RangeContraint_MIN_val ((v), b) -> range_min_val_func v b s + | RangeTypeConstraint.RangeConstraint((v1), (v2), b1,b2) -> rangeFunc v1 v2 b1 b2 s + | RangeTypeConstraint.RangeConstraint_val_MAX ((v), b) -> range_val_max_func v b s + | RangeTypeConstraint.RangeConstraint_MIN_val ((v), b) -> range_min_val_func v b s loopRecursiveConstraint c s -let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc - sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc +let foldSizableTypeConstraint unionFunc intersectionFunc allExceptFunc exceptFunc rootFunc rootFunc2 singleValueFunc + sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func - (c:SizableTypeConstraint<'v>) + (c:SizableTypeConstraint<'v>) (s:'UserState) = let rec loopRecursiveConstraint (c:SizableTypeConstraint<'v>) (s0:'UserState) = match c with - | SizeUnionConstraint(c1,c2,b) -> + | SizeUnionConstraint(c1,c2,b) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 unionFunc nc1 nc2 b s2 - | SizeIntersectionConstraint(c1,c2) -> + | SizeIntersectionConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 intersectionFunc nc1 nc2 s2 - | SizeAllExceptConstraint(c1) -> + | SizeAllExceptConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 allExceptFunc nc1 s1 - | SizeExceptConstraint(c1,c2) -> + | SizeExceptConstraint(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 exceptFunc nc1 nc2 s2 - | SizeRootConstraint(c1) -> + | SizeRootConstraint(c1) -> let nc1, s1 = loopRecursiveConstraint c1 s0 rootFunc nc1 s1 - | SizeRootConstraint2(c1,c2) -> + | SizeRootConstraint2(c1,c2) -> let nc1, s1 = loopRecursiveConstraint c1 s0 let nc2, s2 = loopRecursiveConstraint c2 s1 rootFunc2 nc1 nc2 s2 | SizeSingleValueConstraint (v) -> singleValueFunc v s0 - | SizableTypeConstraint.SizeContraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s + | SizableTypeConstraint.SizeConstraint intCon -> foldRangeTypeConstraint sunionFunc sintersectionFunc sallExceptFunc sexceptFunc srootFunc srootFunc2 ssingleValueFunc srangeFunc srange_val_max_func srange_min_val_func intCon s loopRecursiveConstraint c s let getSizeableTypeConstraintUperRange (c:SizableTypeConstraint<'v>) funcGetLength (l:SrcLoc) = foldSizableTypeConstraint (fun r1 r2 b s -> uperUnion r1 r2, s) (fun r1 r2 s -> uperIntersection r1 r2 l, s) - (fun r s -> Full, s) + (fun r s -> Full, s) (fun r1 r2 s -> r1, s) - (fun r s -> Full, s) + (fun r s -> Full, s) (fun r1 r2 s -> Full, s) (fun v s -> Concrete (funcGetLength v,funcGetLength v),s) - + (fun r1 r2 b s -> uperUnion r1 r2, s) (fun r1 r2 s -> uperIntersection r1 r2 l, s) - (fun r s -> Full, s) + (fun r s -> Full, s) (fun r1 r2 s -> r1, s) - (fun r s -> Full, s) + (fun r s -> Full, s) (fun r1 r2 s -> Full, s) (fun v s -> Concrete (v,v),s) (fun v1 v2 minIsIn maxIsIn s -> let val1 = if minIsIn then v1 else (v1+1u) let val2 = if maxIsIn then v2 else (v2-1u) Concrete(val1 , val2), s) - (fun v1 minIsIn s -> + (fun v1 minIsIn s -> let val1 = if minIsIn then v1 else (v1+1u) PosInf(val1) ,s ) - (fun v2 maxIsIn s -> + (fun v2 maxIsIn s -> let val2 = if maxIsIn then v2 else (v2-1u) NegInf(val2), s) - c + c 0 |> fst let getSizeableUperRange (cons:SizableTypeConstraint<'v> list) funcGetLength (l:SrcLoc) = let getConUperRange (c:SizableTypeConstraint<'v>) (l:SrcLoc) = - getSizeableTypeConstraintUperRange c funcGetLength l + getSizeableTypeConstraintUperRange c funcGetLength l cons |> List.fold(fun s c -> uperIntersection s (getConUperRange c l) l) Full let getBitStringUperRange (cons:BitStringConstraint list) (l:SrcLoc) = getSizeableUperRange cons (fun (x) -> uint32 x.Value.Length) l -let getBitStringConstraint (r:AstRoot) (t:Asn1Type) = +let getBitStringConstraint (r:AstRoot) (t:Asn1Type) = let rec bitGetter (r:AstRoot) (v:Asn1Value) = match v.Kind with | BitStringValue vl -> (vl) diff --git a/FrontEndAst/RemoveParamterizedTypes.fs b/FrontEndAst/RemoveParameterizedTypes.fs similarity index 87% rename from FrontEndAst/RemoveParamterizedTypes.fs rename to FrontEndAst/RemoveParameterizedTypes.fs index e3ba31660..0bbb0d7eb 100644 --- a/FrontEndAst/RemoveParamterizedTypes.fs +++ b/FrontEndAst/RemoveParameterizedTypes.fs @@ -9,7 +9,7 @@ * For more informations see License.txt file *) -module RemoveParamterizedTypes +module RemoveParameterizedTypes open System.Numerics open Antlr.Runtime.Tree @@ -22,7 +22,7 @@ open ParameterizedAsn1Ast //let rec foldMap func state lst = // match lst with // | [] -> [],state -// | h::tail -> +// | h::tail -> // let procItem, newState = func state h // let restList, finalState = tail |> foldMap func newState // procItem::restList, finalState @@ -30,7 +30,7 @@ let foldMap func state lst = let rec loop acc func state lst = match lst with | [] -> acc |> List.rev , state - | h::tail -> + | h::tail -> let procItem, newState = func state h //let restList, finalState = tail |> loop func newState //procItem::restList, finalState @@ -41,7 +41,7 @@ let foldMap func state lst = let rec CloneType (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (namedArgs:list) (old:Asn1Type) (implicitImports : List) : (Asn1Type * List) = let CloneChild (implicitImports : List) (ch:ChildInfo) = let newType, newImports = CloneType r curModule oldModName namedArgs ch.Type implicitImports - let newChildInfo = + let newChildInfo = {ch with Type = newType; Optionality = match ch.Optionality with | Some(Default(v)) -> Some(Default (CloneValue r curModule oldModName namedArgs (Some newType) v)) | _ -> ch.Optionality} @@ -51,44 +51,44 @@ let rec CloneType (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (name let cloneSeqChild (implicitImports : List) (seqChild:SequenceChild) = match seqChild with | ComponentsOf (x,y) -> ComponentsOf (x,y), [] - | ChildInfo ch -> - let newChildInfo, newImports = CloneChild implicitImports ch + | ChildInfo ch -> + let newChildInfo, newImports = CloneChild implicitImports ch ChildInfo newChildInfo, newImports - let newKind, newCons, newImports = + let newKind, newCons, newImports = let cons = old.Constraints |> List.map (CloneConstraint r curModule oldModName namedArgs (Some old)) match old.Kind with - | Sequence(children) -> + | Sequence(children) -> let newChildren, newImports = children |> foldMap (fun newState ch -> cloneSeqChild newState ch) implicitImports Sequence(newChildren), cons, newImports - | Choice(children) -> + | Choice(children) -> let newChildren, newImports = children |> foldMap (fun newState ch -> CloneChild newState ch) implicitImports Choice(newChildren), cons, newImports - | SequenceOf(child) -> + | SequenceOf(child) -> let newType, newImports = CloneType r curModule oldModName namedArgs child implicitImports SequenceOf newType, cons, newImports | ReferenceType(md,ts,refEnc, args) -> match args with - | [] -> + | [] -> match namedArgs |> Seq.tryFind (fun (nm, _) -> nm = ts) with - | Some(_,arg) -> + | Some(_,arg) -> match arg with | ArgType(x) -> x.Kind, (x.Constraints|> List.map (CloneConstraint r curModule oldModName namedArgs (Some x)))@cons, [] | _ -> raise(BugErrorException "") - | None -> + | None -> let newImports = match md.Value <> curModule.Name.Value with | true -> [(md.Value, ts.Value)] | false -> [] old.Kind, cons, newImports - | _ -> + | _ -> let specRefType, newImports2 = SpecializeRefType r curModule md ts args namedArgs implicitImports specRefType.Kind, (specRefType.Constraints|> List.map (CloneConstraint r curModule oldModName namedArgs (Some specRefType)))@cons, newImports2 | _ -> old.Kind,cons, [] - let retType = + let retType = { Asn1Type.Kind = newKind Constraints = newCons @@ -102,13 +102,13 @@ let rec CloneType (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (name and CloneConstraint (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (namedArgs:list) (t:Asn1Type option) (c:Asn1Constraint) :Asn1Constraint = match c with - | SingleValueContraint(s, v) -> SingleValueContraint(s, (CloneValue r curModule oldModName namedArgs t v)) - | RangeContraint(s, v1,v2,b1,b2) -> RangeContraint(s, CloneValue r curModule oldModName namedArgs t v1,CloneValue r curModule oldModName namedArgs t v2,b1,b2) - | RangeContraint_val_MAX(s,v,b) -> RangeContraint_val_MAX (s, CloneValue r curModule oldModName namedArgs t v,b) - | RangeContraint_MIN_val(s, v,b) -> RangeContraint_MIN_val (s, CloneValue r curModule oldModName namedArgs t v,b) + | SingleValueConstraint(s, v) -> SingleValueConstraint(s, (CloneValue r curModule oldModName namedArgs t v)) + | RangeConstraint(s, v1,v2,b1,b2) -> RangeConstraint(s, CloneValue r curModule oldModName namedArgs t v1,CloneValue r curModule oldModName namedArgs t v2,b1,b2) + | RangeConstraint_val_MAX(s,v,b) -> RangeConstraint_val_MAX (s, CloneValue r curModule oldModName namedArgs t v,b) + | RangeConstraint_MIN_val(s, v,b) -> RangeConstraint_MIN_val (s, CloneValue r curModule oldModName namedArgs t v,b) | TypeInclusionConstraint(s, s1,s2) -> TypeInclusionConstraint(s, s1,s2) - | SizeContraint(s, c) -> SizeContraint(s, CloneConstraint r curModule oldModName namedArgs None c) - | AlphabetContraint(s, c) -> AlphabetContraint(s, CloneConstraint r curModule oldModName namedArgs None c) + | SizeConstraint(s, c) -> SizeConstraint(s, CloneConstraint r curModule oldModName namedArgs None c) + | AlphabetConstraint(s, c) -> AlphabetConstraint(s, CloneConstraint r curModule oldModName namedArgs None c) | UnionConstraint(s, c1,c2,b) -> UnionConstraint(s, CloneConstraint r curModule oldModName namedArgs t c1, CloneConstraint r curModule oldModName namedArgs t c2, b) | IntersectionConstraint(s, c1,c2) -> IntersectionConstraint(s, CloneConstraint r curModule oldModName namedArgs t c1, CloneConstraint r curModule oldModName namedArgs t c2) | AllExceptConstraint(s, c) -> AllExceptConstraint(s, CloneConstraint r curModule oldModName namedArgs t c) @@ -120,27 +120,28 @@ and CloneConstraint (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (name and CloneNamedConstraint (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (namedArgs:list) (x:NamedConstraint) :NamedConstraint = { - NamedConstraint.Name = x.Name; - Mark = x.Mark - Contraint = match x.Contraint with - | None -> None - | Some(cc) -> Some (CloneConstraint r curModule oldModName namedArgs None cc) + NamedConstraint.Name = x.Name; + Mark = x.Mark + Constraint = + match x.Constraint with + | None -> None + | Some(cc) -> Some (CloneConstraint r curModule oldModName namedArgs None cc) } - + and CloneValue (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (namedArgs:list) (t:Asn1Type option) (v:Asn1Value) :Asn1Value = match v.Kind with - |RefValue(v1,v2) -> + |RefValue(v1,v2) -> match namedArgs |> Seq.tryFind (fun (nm, _) -> nm = v2) with - | Some(_,arg) -> + | Some(_,arg) -> match arg with | ArgValue(vl) -> vl | _ -> raise(BugErrorException "") - | None -> + | None -> match t with - | Some tt -> + | Some tt -> let actType = GetActualType tt r match actType.Kind with - | Enumerated enmItems when oldModName = v1.Value -> + | Enumerated enmItems when oldModName = v1.Value -> match enmItems |> Seq.tryFind (fun enmItem -> enmItem.Name.Value = v2.Value) with | None -> v | Some _ -> {v with Kind = RefValue(StringLoc.ByValue curModule.Name.Value,v2)} @@ -154,11 +155,11 @@ and CloneValue (r:AstRoot) (curModule:Asn1Module) (oldModName:string) (namedArg and SpecializeType (r:AstRoot) (curModule:Asn1Module) (implicitImports : List) (t:Asn1Type) : (Asn1Type * List) = let mergeAcnInfo (refTypeSpec:AcnGenericTypes.AcnTypeEncodingSpec option) (genTypeSpec:AcnGenericTypes.AcnTypeEncodingSpec option) = let rec mergeAcnInfo_aux (refTypeSpec:AcnGenericTypes.AcnTypeEncodingSpec ) (genTypeSpec:AcnGenericTypes.AcnTypeEncodingSpec) = - let allChildNames = + let allChildNames = //if ref refTypeSpec children is a subset of genTypeSpec return genTypeSpec children //if genTypeSpec children is a subset of of refTypeSpec children return refTypeSpec children //else emit user error. User must provide child spec in all children - let refTypeChildrenNames = refTypeSpec.children |> List.map(fun z -> z.name.Value) + let refTypeChildrenNames = refTypeSpec.children |> List.map(fun z -> z.name.Value) let getTypeChildrenNames = genTypeSpec.children |> List.map(fun z -> z.name.Value) let refTypeSet = Set.ofList refTypeChildrenNames let genTypeSet = Set.ofList getTypeChildrenNames @@ -168,7 +169,7 @@ and SpecializeType (r:AstRoot) (curModule:Asn1Module) (implicitImports : List List.distinct let combinedChildren = - allChildNames |> + allChildNames |> List.map(fun name -> let refTypeChild = refTypeSpec.children |> Seq.tryFind (fun c -> c.name.Value = name) let genTypeChild = genTypeSpec.children |> Seq.tryFind (fun c -> c.name.Value = name) @@ -176,7 +177,7 @@ and SpecializeType (r:AstRoot) (curModule:Asn1Module) (implicitImports : List raise(BugErrorException(sprintf "SpecializeType no child with name :%s found" name)) | None, Some a -> a | Some a, None -> a //reference type wins over generalized type - | Some refChild, Some genChild -> + | Some refChild, Some genChild -> let childEncodingSpec = mergeAcnInfo_aux refChild.childEncodingSpec genChild.childEncodingSpec {refChild with childEncodingSpec = childEncodingSpec}) //reference type properties wins over generalized type (put at before genType properties) @@ -188,10 +189,10 @@ and SpecializeType (r:AstRoot) (curModule:Asn1Module) (implicitImports : List Some a2 | Some refTypeSpec, Some genTypeSpec -> Some (mergeAcnInfo_aux refTypeSpec genTypeSpec) match t.Kind with - | ReferenceType(md,ts, refEnc, args) when args.Length>0 -> + | ReferenceType(md,ts, refEnc, args) when args.Length>0 -> let (newType, implImps) = SpecializeRefType r curModule md ts args [] implicitImports ({newType with Constraints = newType.Constraints@t.Constraints; acnInfo=mergeAcnInfo t.acnInfo newType.acnInfo}, implImps) - | ReferenceType(md,ts, refEnc, args) -> + | ReferenceType(md,ts, refEnc, args) -> let parmTas = getModuleByName r md |> getTasByName ts match parmTas.Parameters with | [] -> t, implicitImports @@ -203,20 +204,20 @@ and SpecializeRefType (r:AstRoot) (curModule:Asn1Module) (mdName:StringLoc) (tsN let SpecializeTemplatizedArgument (implicitImports : List) (arg:TemplateArgument) = match arg with | ArgValue(_) -> arg, implicitImports - | ArgType(tp) -> + | ArgType(tp) -> let newType, newImports = SpecializeType r curModule implicitImports tp ArgType newType, newImports - | TemplateParameter prmName -> + | TemplateParameter prmName -> match resolvedTeplateParams |> Seq.tryFind (fun (prm,templArg) -> prm.Value = prmName.Value) with | Some (prm, templArg) -> templArg, implicitImports - | None -> + | None -> raise (SemanticError(tsName.Location, sprintf "Template argument %s cannot be resolved" (prmName.Value) )) let args, newImports = args |> foldMap SpecializeTemplatizedArgument implicitImports match parmTas.Parameters.Length = args.Length with | true -> () | false -> raise (SemanticError(tsName.Location, sprintf "The number of template arguments do not match the number of parameter in the type assignment")) - + let getNameArg (arg:TemplateArgument, prm:TemplateParameter) = match prm, arg with | TypeParameter(s), ArgType(_) -> (s, arg) @@ -234,18 +235,18 @@ and SpecializeRefType (r:AstRoot) (curModule:Asn1Module) (mdName:StringLoc) (tsN and DoAsn1Type (r:AstRoot) (curModule:Asn1Module) (implicitImports : List) (t:Asn1Type) : (Asn1Type * List) = let DoChildInfo (r:AstRoot) (implicitImports : List) (c:ChildInfo) :ChildInfo * List = - let newType, newImports = DoAsn1Type r curModule implicitImports c.Type + let newType, newImports = DoAsn1Type r curModule implicitImports c.Type { ChildInfo.Name = c.Name Type = newType - Optionality = c.Optionality + Optionality = c.Optionality AcnInsertedField = c.AcnInsertedField Comments = c.Comments }, newImports let DoSeqChildInof r (implicitImports : List) ch : (SequenceChild*List)= match ch with - | ChildInfo ch -> + | ChildInfo ch -> let newType, newImports = DoChildInfo r implicitImports ch ChildInfo newType, newImports | ComponentsOf (m,t) -> ComponentsOf (m,t), implicitImports @@ -253,30 +254,30 @@ and DoAsn1Type (r:AstRoot) (curModule:Asn1Module) (implicitImports : List - let newType, newImports = DoAsn1Type r curModule implicitImports child + | SequenceOf(child) -> + let newType, newImports = DoAsn1Type r curModule implicitImports child aux (SequenceOf(newType)) t.acnInfo , newImports - | Sequence(children)-> + | Sequence(children)-> let newChildren, newImports = children |> foldMap (DoSeqChildInof r) implicitImports aux (Sequence(newChildren)) t.acnInfo , newImports - | Choice(children) -> + | Choice(children) -> let newChildren, newImports = children |> foldMap (DoChildInfo r) implicitImports aux (Choice(newChildren)) t.acnInfo , newImports | ReferenceType(_) -> SpecializeType r curModule implicitImports t | _ -> aux t.Kind t.acnInfo , implicitImports - + let DoTypeAssignment (r:AstRoot) (curModule:Asn1Module) (implicitImports : List) (tas:TypeAssignment) : (TypeAssignment*List) = - let newType, newImports = DoAsn1Type r curModule implicitImports tas.Type + let newType, newImports = DoAsn1Type r curModule implicitImports tas.Type { TypeAssignment.Name = tas.Name Type = newType @@ -286,7 +287,7 @@ let DoTypeAssignment (r:AstRoot) (curModule:Asn1Module) (implicitImports : List< }, newImports let DoValueAssignment (r:AstRoot) (curModule:Asn1Module) (implicitImports : List) (vas:ValueAssignment) :(ValueAssignment*List) = - let newType, newImports = DoAsn1Type r curModule implicitImports vas.Type + let newType, newImports = DoAsn1Type r curModule implicitImports vas.Type { ValueAssignment.Name = vas.Name Type = newType @@ -300,25 +301,25 @@ let DoValueAssignment (r:AstRoot) (curModule:Asn1Module) (implicitImports : List let DoModule (r:AstRoot) (m:Asn1Module) :Asn1Module = let DoImportedModule (x:ImportedModule) : ImportedModule option = - let types = x.Types |> List.choose(fun ts -> + let types = x.Types |> List.choose(fun ts -> let tas = getModuleByName r x.Name |> getTasByName ts match tas.Parameters with | [] -> Some ts - | _ -> None //Paramterized Import, so remove it + | _ -> None //Parameterized Import, so remove it ) match types, x.Values with | [],[] -> None | _ -> Some { ImportedModule.Name = x.Name; Types = types; Values = x.Values} - + let newTypeAssignments, newImports = m.TypeAssignments |> List.filter(fun x -> x.Parameters.Length = 0) |> foldMap (DoTypeAssignment r m) [] let newValueAssignments, newImports = m.ValueAssignments |> foldMap (DoValueAssignment r m) newImports - let addionalImports = newImports |> Seq.distinct |> Seq.toList + let additionalImports = newImports |> Seq.distinct |> Seq.toList let existingImports = m.Imports |> List.choose DoImportedModule let newImports = - addionalImports |> - List.fold (fun (newCurImports:list) (impMod, impTas) -> + additionalImports |> + List.fold (fun (newCurImports:list) (impMod, impTas) -> match newCurImports |> Seq.tryFind (fun imp -> imp.Name.Value = impMod) with - | None -> ({ImportedModule.Name = StringLoc.ByValue impMod; Types = [StringLoc.ByValue impTas]; Values = []})::newCurImports + | None -> ({ImportedModule.Name = StringLoc.ByValue impMod; Types = [StringLoc.ByValue impTas]; Values = []})::newCurImports | Some imp -> match imp.Types |> Seq.tryFind(fun x -> x.Value = impTas) with | None -> @@ -326,7 +327,7 @@ let DoModule (r:AstRoot) (m:Asn1Module) :Asn1Module = newImp::(newCurImports|>List.filter(fun imp -> imp.Name.Value <> impMod)) | Some _ -> newCurImports ) existingImports - + { m with TypeAssignments = newTypeAssignments diff --git a/FrontEndAst/ValuesMapping.fs b/FrontEndAst/ValuesMapping.fs index 677a5eb28..b0df346b9 100644 --- a/FrontEndAst/ValuesMapping.fs +++ b/FrontEndAst/ValuesMapping.fs @@ -7,7 +7,7 @@ open Asn1AcnAst let getBaseValue (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = match v.Kind with - | Asn1Ast.RefValue(md,ts) -> + | Asn1Ast.RefValue(md,ts) -> match r.Modules |> Seq.tryFind(fun m -> m.Name = md) with | Some m -> match m.ValueAssignments |> Seq.tryFind (fun v -> v.Name = ts) with @@ -18,7 +18,7 @@ let getBaseValue (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = let rec getActualBaseValue (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = match v.Kind with - | Asn1Ast.RefValue(md,ts) -> + | Asn1Ast.RefValue(md,ts) -> match r.Modules |> Seq.tryFind(fun m -> m.Name = md) with | Some m -> match m.ValueAssignments |> Seq.tryFind (fun v -> v.Name = ts) with @@ -28,41 +28,41 @@ let rec getActualBaseValue (r:Asn1Ast.AstRoot) (v:Asn1Ast.Asn1Value) = | _ -> v -let rec mapValue +let rec mapValue (r:Asn1Ast.AstRoot) (t:Asn1Ast.Asn1Type) (v:Asn1Ast.Asn1Value) = let actualType = Asn1Ast.GetActualType t r - let valueKind = + let valueKind = match v.Kind with - | Asn1Ast.IntegerValue v -> + | Asn1Ast.IntegerValue v -> match actualType.Kind with | Asn1Ast.Integer -> IntegerValue v | Asn1Ast.Real -> RealValue ({ Value = (double v.Value); Location = v.Location}) | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found an INTEGER value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.RealValue v -> + | Asn1Ast.RealValue v -> match actualType.Kind with | Asn1Ast.Real -> RealValue v | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a REAL value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.StringValue v -> + | Asn1Ast.StringValue v -> let (_,l) = v match actualType.Kind with | Asn1Ast.IA5String -> StringValue v | Asn1Ast.NumericString -> StringValue v | _ -> raise (SemanticError(l, (sprintf "Expecting a %s value but found a STRING value" (Asn1Ast.getASN1Name r actualType)))) | Asn1Ast.TimeValue v -> TimeValue v - | Asn1Ast.BooleanValue v -> + | Asn1Ast.BooleanValue v -> match actualType.Kind with | Asn1Ast.Boolean -> BooleanValue v | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a BOOLEAN value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.BitStringValue v -> + | Asn1Ast.BitStringValue v -> match actualType.Kind with | Asn1Ast.BitString _ -> BitStringValue v - | Asn1Ast.OctetString -> + | Asn1Ast.OctetString -> let arBytes = bitStringValueToByteArray v |> Seq.map(fun curByte -> {ByteLoc.Value = curByte; Location = v.Location}) |> Seq.toList OctetStringValue arBytes | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a BIT STRING value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.OctetStringValue bv -> + | Asn1Ast.OctetStringValue bv -> match actualType.Kind with | Asn1Ast.OctetString -> OctetStringValue bv | Asn1Ast.BitString _ -> @@ -70,7 +70,7 @@ let rec mapValue let location = match bv with [] -> emptyLocation | b1::_ -> b1.Location BitStringValue ({StringLoc.Value = bitStrVal; Location = location}) | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found an OCTET STRING value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.RefValue (md,ts) -> + | Asn1Ast.RefValue (md,ts) -> let resolveReferenceValue md ts = let newVal = mapValue r t (getBaseValue r v) RefValue ((md,ts), newVal) @@ -81,38 +81,38 @@ let rec mapValue | Some ni -> EnumValue ni.Name | _ -> resolveReferenceValue md ts | _ -> resolveReferenceValue md ts - | Asn1Ast.SeqOfValue chVals -> + | Asn1Ast.SeqOfValue chVals -> match actualType.Kind with | Asn1Ast.SequenceOf chType -> let chValue = chVals |> List.map (mapValue r chType) SeqOfValue chValue | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a SEQUENCE OF value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.SeqValue chVals -> + | Asn1Ast.SeqValue chVals -> match actualType.Kind with | Asn1Ast.Sequence children -> - let chValue = - chVals |> - List.map (fun (cnm, chv) -> + let chValue = + chVals |> + List.map (fun (cnm, chv) -> match children |> Seq.tryFind (fun c -> c.Name = cnm) with - | Some chType -> + | Some chType -> let chValue = mapValue r chType.Type chv {NamedValue.name = cnm; Value = chValue} | None -> raise (SemanticError(v.Location, (sprintf "No child exists with name '%s' " cnm.Value))) ) SeqValue chValue | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a SEQUENCE value" (Asn1Ast.getASN1Name r actualType)))) - | Asn1Ast.ChValue (cnm, chv) -> + | Asn1Ast.ChValue (cnm, chv) -> match actualType.Kind with | Asn1Ast.Choice children -> match children |> Seq.tryFind (fun c -> c.Name = cnm) with - | Some chType -> + | Some chType -> let chValue = mapValue r chType.Type chv ChValue ({NamedValue.name = cnm; Value = chValue}) - | None -> raise (SemanticError(v.Location, (sprintf "No child exists with name %s" cnm.Value))) + | None -> raise (SemanticError(v.Location, (sprintf "No child exists with name %s" cnm.Value))) | _ -> raise (SemanticError(v.Location, (sprintf "Expecting a %s value but found a SEQUENCE value" (Asn1Ast.getASN1Name r actualType)))) | Asn1Ast.NullValue -> NullValue () - | Asn1Ast.ObjOrRelObjIdValue comps -> - let rec mapComponents (comps:CommonTypes.ObjectIdentifierValueCompoent list) = - let mapComponent (c:CommonTypes.ObjectIdentifierValueCompoent)= + | Asn1Ast.ObjOrRelObjIdValue comps -> + let rec mapComponents (comps:CommonTypes.ObjectIdentifierValueComponent list) = + let mapComponent (c:CommonTypes.ObjectIdentifierValueComponent)= match c with | CommonTypes.ObjInteger o -> [CommonTypes.ResObjInteger o] | CommonTypes.ObjNamedIntValue(nm,vl) -> [CommonTypes.ResObjNamedIntValue (nm, vl)] @@ -128,9 +128,9 @@ let rec mapValue | Asn1Ast.ObjOrRelObjIdValue comps -> mapComponents comps | _ -> raise(SemanticError (ts.Location, "Expecting OBJECT IDENTIFIER or RELATIVE-OID value or OBJECT IDENTIFIER or RELATIVE-OID value assignment")) - + comps |> List.collect mapComponent ObjOrRelObjIdValue (mapComponents comps, comps ) - {Asn1Value.kind = valueKind; id = v.id; loc = v.Location; moduleName=v.moduleName} + {Asn1Value.kind = valueKind; id = v.id; loc = v.Location; moduleName=v.moduleName} diff --git a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/README.md b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/README.md index 5cd9a0692..6f9e67c2d 100644 --- a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/README.md +++ b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/README.md @@ -9,7 +9,7 @@ See [ECSS-E-ST-70-41C](http://ecss.nl/standard/ecss-e-st-70-41c-space-engineerin See [ASN1SCC](https://github.com/maxime-esa/asn1scc) for details about ACN encoding. -ASN.1 components are ment to work with any ASN.1 based tool, +ASN.1 components are meant to work with any ASN.1 based tool, but project itself is prepared to be included as "ASN.1 Components Library" in [QtCreator](https://www.qt.io/download)'s plugin [asn1scc.IDE](https://github.com/n7space/asn1scc.IDE). diff --git a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/service-12/PUS-12-8.asn1 b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/service-12/PUS-12-8.asn1 index 81fe37df1..abc31ea14 100644 --- a/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/service-12/PUS-12-8.asn1 +++ b/PUSCScalaTest/asn1-pusc-lib-asn1CompilerTestInput/service-12/PUS-12-8.asn1 @@ -26,9 +26,9 @@ EXPORTS ALL; IMPORTS PMON-ID FROM PMON; -TC-12-8-ReportParameterMonitoringDefintions ::= TC-12-8-ReportParameterMonitoringDefintionsGeneric {PMON-ID} +TC-12-8-ReportParameterMonitoringDefinitions ::= TC-12-8-ReportParameterMonitoringDefinitionsGeneric {PMON-ID} -TC-12-8-ReportParameterMonitoringDefintionsGeneric {PMON-ID-Type} ::= SEQUENCE +TC-12-8-ReportParameterMonitoringDefinitionsGeneric {PMON-ID-Type} ::= SEQUENCE { --! n UnsignedInteger, pmon-ID PMON-ID-Type diff --git a/StgAda/LangGeneric_a.fs b/StgAda/LangGeneric_a.fs index bd1207fdd..53170811c 100644 --- a/StgAda/LangGeneric_a.fs +++ b/StgAda/LangGeneric_a.fs @@ -8,11 +8,17 @@ open System.IO (****** Ada Implementation ******) -let getAccess_a (_:FuncParamType) = "." + +let getAccess2_a (acc: Accessor) = + match acc with + | ValueAccess (sel, _, _) -> $".{sel}" + | PointerAccess (sel, _, _) -> $".{sel}" + | ArrayAccess (ix, _) -> $"({ix})" + #if false -let createBitStringFunction_funcBody_Ada handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = - let ii = id.SeqeuenceOfLevel + 1; - let i = sprintf "i%d" (id.SeqeuenceOfLevel + 1) +let createBitStringFunction_funcBody_Ada handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = + let ii = id.SequenceOfLevel + 1; + let i = sprintf "i%d" (id.SequenceOfLevel + 1) let typeDefinitionName = match typeDefinition with @@ -23,28 +29,28 @@ let createBitStringFunction_funcBody_Ada handleFragmentation (codec:CommonTypes. | Some pu -> pu + "." + ref.typedefName | None -> ref.typedefName - let funcBodyContent, localVariables = - let nStringLength = - match isFixedSize with - | true -> [] - | false -> + let funcBodyContent, localVariables = + let nStringLength = + match isFixedSize with + | true -> [] + | false -> match codec with | Encode -> [] | Decode -> [IntegerLocalVariable ("nStringLength", None)] - let iVar = SequenceOfIndex (id.SeqeuenceOfLevel + 1, None) + let iVar = SequenceOfIndex (id.SequenceOfLevel + 1, None) let nBits = 1I - let internalItem = uper_a.InternalItem_bit_str p.arg.p i errCode.errCodeName codec + let internalItem = uper_a.InternalItem_bit_str p.arg.p i errCode.errCodeName codec let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (maxSize - minSize)) match minSize with - | _ when maxSize < 65536I && isFixedSize -> uper_a.octect_FixedSize p.arg.p typeDefinitionName i internalItem (minSize) nBits nBits 0I codec, iVar::nStringLength - | _ when maxSize < 65536I && (not isFixedSize) -> uper_a.octect_VarSize p.arg.p "." typeDefinitionName i internalItem ( minSize) (maxSize) nSizeInBits nBits nBits 0I errCode.errCodeName codec , iVar::nStringLength - | _ -> + | _ when maxSize < 65536I && isFixedSize -> uper_a.octet_FixedSize p.arg.p typeDefinitionName i internalItem (minSize) nBits nBits 0I codec, iVar::nStringLength + | _ when maxSize < 65536I && (not isFixedSize) -> uper_a.octet_VarSize p.arg.p "." typeDefinitionName i internalItem ( minSize) (maxSize) nSizeInBits nBits nBits 0I errCode.errCodeName codec , iVar::nStringLength + | _ -> let funcBodyContent, fragmentationLvars = handleFragmentation p codec errCode ii (uperMaxSizeInBits) minSize maxSize internalItem nBits true false let fragmentationLvars = fragmentationLvars |> List.addIf (not isFixedSize) (iVar) (funcBodyContent,fragmentationLvars) - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} #endif @@ -59,7 +65,7 @@ let createBitStringFunction_funcBody_Ada handleFragmentation (codec:CommonTypes. type LangGeneric_a() = inherit ILangGeneric() override _.ArrayStartIndex = 1 - override this.getEmptySequenceInitExpression () = "(null record)" + override this.getEmptySequenceInitExpression _ = "(null record)" override this.callFuncWithNoArgs () = "" override this.rtlModuleName = "adaasn1rtl." @@ -69,8 +75,8 @@ type LangGeneric_a() = override this.hasModules = true override this.allowsSrcFilesWithNoFunctions = false override this.requiresValueAssignmentsInSrcFile = false - override this.supportsStaticVerification = true - override this.emtyStatement = "null;" + override this.supportsStaticVerification = true + override this.emptyStatement = "null;" override this.bitStreamName = "adaasn1rtl.encoding.BitStreamPtr" override this.unaryNotOperator = "not" override this.modOp = "mod" @@ -78,80 +84,61 @@ type LangGeneric_a() = override this.neqOp = "<>" override this.andOp = "and" override this.orOp = "or" - override this.initMetod = InitMethod.Function - + override this.initMethod = InitMethod.Function + override _.decodingKind = InPlace + override _.usesWrappedOptional = false override this.castExpression (sExp:string) (sCastType:string) = sprintf "%s(%s)" sCastType sExp override this.createSingleLineComment (sText:string) = sprintf "--%s" sText override _.SpecNameSuffix = "" - override _.SpecExtention = "ads" - override _.BodyExtention = "adb" - override _.Keywords = CommonTypes.ada_keyworkds + override _.SpecExtension = "ads" + override _.BodyExtension = "adb" + override _.Keywords = CommonTypes.ada_keywords override _.isCaseSensitive = false - override _.doubleValueToString (v:double) = + override _.doubleValueToString (v:double) = v.ToString(FsUtils.doubleParseString, System.Globalization.NumberFormatInfo.InvariantInfo) override _.intValueToString (i:BigInteger) _ = i.ToString() override _.initializeString (_) = "(others => adaasn1rtl.NUL)" - + override _.supportsInitExpressions = true - override _.getPointer (fpt:FuncParamType) = - match fpt with - | VALUE x -> x - | POINTER x -> x - | FIXARRAY x -> x - - override this.getValue (fpt:FuncParamType) = - match fpt with - | VALUE x -> x - | POINTER x -> x - | FIXARRAY x -> x - override this.getAccess (fpt:FuncParamType) = getAccess_a fpt - - override this.getPtrPrefix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "" - | FIXARRAY x -> "" - - override this.getPtrSuffix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "" - | FIXARRAY x -> "" - - override this.getStar (fpt:FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "" - | FIXARRAY x -> "" - - override this.getArrayItem (fpt:FuncParamType) (idx:string) (childTypeIsString: bool) = - let newPath = sprintf "%s.Data(%s)" fpt.p idx - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - override this.ArrayAccess idx = "(" + idx + ")" - - override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = + override this.getPointer (sel: Selection) = sel.joined this + + override this.getValue (sel: Selection) = sel.joined this + override this.getAccess (sel: Selection) = "." + + override this.getAccess2 (acc: Accessor) = getAccess2_a acc + + override this.getPtrPrefix _ = "" + + override this.getPtrSuffix _ = "" + + override this.getStar _ = "" + + override this.getArrayItem (sel: Selection) (idx:string) (childTypeIsString: bool) = + (sel.appendSelection "Data" FixArray false).append (ArrayAccess (idx, if childTypeIsString then FixArray else Value)) + + override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = let prefix = ToC (id.AcnAbsPath.Tail.StrJoin("_").Replace("#","elem")) prefix + "_NONE" - override this.getNamedItemBackendName (defOrRef:TypeDefintionOrReference option) (nm:Asn1AcnAst.NamedItem) = + override this.getNamedItemBackendName (defOrRef:TypeDefinitionOrReference option) (nm:Asn1AcnAst.NamedItem) = match defOrRef with | Some (ReferenceToExistingDefinition r) when r.programUnit.IsSome -> r.programUnit.Value + "." + nm.ada_name | Some (TypeDefinition td) when td.baseType.IsSome && td.baseType.Value.programUnit.IsSome -> td.baseType.Value.programUnit.Value + "." + nm.ada_name | _ -> ToC nm.ada_name - + override this.setNamedItemBackendName0 (nm:Asn1Ast.NamedItem) (newValue:string) : Asn1Ast.NamedItem = {nm with ada_name = newValue} override this.getNamedItemBackendName0 (nm:Asn1Ast.NamedItem) = nm.ada_name - - override this.getNamedItemBackendName2 (defModule:string) (curProgamUnitName:string) (itm:Asn1AcnAst.NamedItem) = - - match (ToC defModule) = ToC curProgamUnitName with + + override this.getNamedItemBackendName2 (defModule:string) (curProgramUnitName:string) (itm:Asn1AcnAst.NamedItem) = + + match (ToC defModule) = ToC curProgramUnitName with | true -> ToC itm.ada_name | false -> ((ToC defModule) + "." + (ToC itm.ada_name)) @@ -161,7 +148,7 @@ type LangGeneric_a() = override this.typeDef (ptd:Map) = ptd.[Ada] override this.getTypeDefinition (td:Map) = td.[Ada] - override this.getEnmTypeDefintion (td:Map) = td.[Ada] + override this.getEnumTypeDefinition (td:Map) = td.[Ada] override this.getStrTypeDefinition (td:Map) = td.[Ada] override this.getChoiceTypeDefinition (td:Map) = td.[Ada] override this.getSequenceTypeDefinition (td:Map) = td.[Ada] @@ -179,7 +166,7 @@ type LangGeneric_a() = override this.getRtlFiles (encodings:Asn1Encoding list) (arrsTypeAssignments :string list) = let uperRtl = match encodings |> Seq.exists(fun e -> e = UPER || e = ACN) with true -> ["adaasn1rtl.encoding.uper"] | false -> [] - let acnRtl = + let acnRtl = match arrsTypeAssignments |> Seq.exists(fun s -> s.Contains "adaasn1rtl.encoding.acn") with true -> ["adaasn1rtl.encoding.acn"] | false -> [] let xerRtl = match encodings |> Seq.exists(fun e -> e = XER) with true -> ["adaasn1rtl.encoding.xer"] | false -> [] @@ -188,43 +175,40 @@ type LangGeneric_a() = encRtl@uperRtl@acnRtl@xerRtl |> List.distinct - override this.getSeqChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) (removeDots: bool) = - let newPath = sprintf "%s.%s" fpt.p childName - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - override this.getChChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) : FuncParamType = - let newPath = sprintf "%s.%s" fpt.p childName - //let newPath = sprintf "%s%su.%s" fpt.p (this.getAccess fpt) childName - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) + override this.getSeqChild (sel: Selection) (childName:string) (childTypeIsString: bool) (childIsOptional: bool) = + sel.appendSelection childName (if childTypeIsString then FixArray else Value) childIsOptional + override this.getChChild (sel: Selection) (childName:string) (childTypeIsString: bool) : Selection = + sel.appendSelection childName (if childTypeIsString then FixArray else Value) false - override this.presentWhenName (defOrRef:TypeDefintionOrReference option) (ch:ChChildInfo) : string = + override this.presentWhenName (defOrRef:TypeDefinitionOrReference option) (ch:ChChildInfo) : string = match defOrRef with | Some (ReferenceToExistingDefinition r) when r.programUnit.IsSome -> r.programUnit.Value + "." + ((ToC ch._present_when_name_private) + "_PRESENT") | _ -> (ToC ch._present_when_name_private) + "_PRESENT" override this.getParamTypeSuffix (t:Asn1AcnAst.Asn1Type) (suf:string) (c:Codec) : CallerScope = - {CallerScope.modName = t.id.ModName; arg= VALUE ("val" + suf) } + {CallerScope.modName = t.id.ModName; arg = Selection.emptyPath ("val" + suf) Value} override this.getLocalVariableDeclaration (lv:LocalVariable) : string = match lv with | SequenceOfIndex (i,None) -> sprintf "i%d:Integer;" i - | SequenceOfIndex (i,Some iv) -> sprintf "i%d:Integer:=%d;" i iv + | SequenceOfIndex (i,Some iv) -> sprintf "i%d:Integer:=%s;" i iv | IntegerLocalVariable (name,None) -> sprintf "%s:Integer;" name - | IntegerLocalVariable (name,Some iv) -> sprintf "%s:Integer:=%d;" name iv + | IntegerLocalVariable (name,Some iv) -> sprintf "%s:Integer:=%s;" name iv | Asn1SIntLocalVariable (name,None) -> sprintf "%s:adaasn1rtl.Asn1Int;" name - | Asn1SIntLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.Asn1Int:=%d;" name iv + | Asn1SIntLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.Asn1Int:=%s;" name iv | Asn1UIntLocalVariable (name,None) -> sprintf "%s:adaasn1rtl.Asn1UInt;" name - | Asn1UIntLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.Asn1UInt:=%d;" name iv + | Asn1UIntLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.Asn1UInt:=%s;" name iv | FlagLocalVariable (name,None) -> sprintf "%s:adaasn1rtl.BIT;" name - | FlagLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.BIT:=%d;" name iv + | FlagLocalVariable (name,Some iv) -> sprintf "%s:adaasn1rtl.BIT:=%s;" name iv | BooleanLocalVariable (name,None) -> sprintf "%s:Boolean;" name - | BooleanLocalVariable (name,Some iv) -> sprintf "%s:Boolean:=%s;" name (if iv then "True" else "False") + | BooleanLocalVariable (name,Some iv) -> sprintf "%s:Boolean:=%s;" name iv | AcnInsertedChild(name, vartype, initVal) -> sprintf "%s:%s;" name vartype | GenericLocalVariable lv -> match lv.initExp with | Some initExp -> sprintf "%s : %s := %s;" lv.name lv.varType initExp - | None -> sprintf "%s : %s;" lv.name lv.varType + | None -> sprintf "%s : %s;" lv.name lv.varType - override this.getLongTypedefName (tdr:TypeDefintionOrReference) : string = + override this.getLongTypedefName (tdr:TypeDefinitionOrReference) : string = match tdr with | TypeDefinition td -> td.typedefName | ReferenceToExistingDefinition ref -> @@ -237,12 +221,12 @@ type LangGeneric_a() = - override this.getParamValue (t:Asn1AcnAst.Asn1Type) (p:FuncParamType) (c:Codec) = - p.p + override this.getParamValue (t:Asn1AcnAst.Asn1Type) (sel: Selection) (c:Codec) = + sel.joined this override this.toHex n = sprintf "16#%x#" n - override this.bitStringValueToByteArray (v : BitStringValue) = + override this.bitStringValueToByteArray (v : BitStringValue) = v.ToCharArray() |> Array.map(fun c -> if c = '0' then 0uy else 1uy) override this.uper = @@ -257,17 +241,17 @@ type LangGeneric_a() = catd = false //createBitStringFunction = createBitStringFunction_funcBody_Ada seqof_lv = - (fun id minSize maxSize -> - if maxSize >= 65536I && maxSize = minSize then + (fun id minSize maxSize -> + if maxSize >= 65536I && maxSize = minSize then [] else - [SequenceOfIndex (id.SeqeuenceOfLevel + 1, None)]) + [SequenceOfIndex (id.SequenceOfLevel + 1, None)]) } - override this.acn = + override this.acn = { Acn_parts.null_valIsUnReferenced = false checkBitPatternPresentResult = false - getAcnDepSizeDeterminantLocVars = + getAcnDepSizeDeterminantLocVars = fun sReqBytesForUperEncoding -> [ GenericLocalVariable {GenericLocalVariable.name = "tmpBs"; varType = "adaasn1rtl.encoding.BitStream"; arrSize = None; isStatic = false;initExp = Some (sprintf "adaasn1rtl.encoding.BitStream_init(%s)" sReqBytesForUperEncoding)} @@ -275,7 +259,7 @@ type LangGeneric_a() = choice_handle_always_absent_child = true choice_requires_tmp_decoding = false } - override this.init = + override this.init = { Initialize_parts.zeroIA5String_localVars = fun ii -> [SequenceOfIndex (ii, None)] choiceComponentTempInit = false @@ -292,10 +276,10 @@ type LangGeneric_a() = override _.getBoardNames (target:Targets option) = match target with | None -> ["x86"] //default board - | Some X86 -> ["x86"] - | Some Stm32 -> ["stm32"] - | Some Msp430 -> ["msp430"] - | Some AllBoards -> ["x86";"stm32";"msp430"] + | Some X86 -> ["x86"] + | Some Stm32 -> ["stm32"] + | Some Msp430 -> ["msp430"] + | Some AllBoards -> ["x86";"stm32";"msp430"] override this.getBoardDirs (target:Targets option) = let boardsDirName = match target with None -> "" | Some _ -> "boards" @@ -304,7 +288,7 @@ type LangGeneric_a() = override this.CreateMakeFile (r:AstRoot) (di:DirInfo) = let boardNames = this.getBoardNames r.args.target - let writeBoard boardName = + let writeBoard boardName = let mods = aux_a.rtlModuleName()::(r.programUnits |> List.map(fun pu -> pu.name.ToLower() )) let content = aux_a.PrintMakeFile boardName (sprintf "asn1_%s.gpr" boardName) mods let fileName = if boardNames.Length = 1 || boardName = "x86" then "Makefile" else ("Makefile." + boardName) @@ -315,9 +299,9 @@ type LangGeneric_a() = override this.getDirInfo (target:Targets option) rootDir = match target with | None -> {rootDir = rootDir; srcDir=rootDir;asn1rtlDir=rootDir;boardsDir=rootDir} - | Some _ -> + | Some _ -> { - rootDir = rootDir; + rootDir = rootDir; srcDir=Path.Combine(rootDir, "src"); asn1rtlDir=Path.Combine(rootDir, "asn1rtl"); boardsDir=Path.Combine(rootDir, "boards") diff --git a/StgAda/acn_a.stg b/StgAda/acn_a.stg index a5d99590a..8e1abccdd 100644 --- a/StgAda/acn_a.stg +++ b/StgAda/acn_a.stg @@ -30,7 +30,7 @@ procedure _aux( : ; bs : in out > -EmitTypeAssignment_primitive_encodeMain(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace) ::= /*nogen*/<< +EmitTypeAssignment_primitive_encodeMain(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace) ::= /*nogen*/<< procedure ( : ; Stream : out _ACN_Stream; result : out .ASN1_RESULT) is begin @@ -39,7 +39,7 @@ begin end ; >> -EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << procedure _aux( : ; bs : in out .encoding.Bitstream; result : OUT .ASN1_RESULT) is @@ -62,7 +62,7 @@ begin end _aux; - + >> @@ -76,7 +76,7 @@ procedure _aux(:out ; bs : in out > -EmitTypeAssignment_primitive_decodeMain(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace) ::= /*nogen*/<< +EmitTypeAssignment_primitive_decodeMain(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace) ::= /*nogen*/<< PROCEDURE (: out ; Stream : in out _ACN_Stream; result : OUT .ASN1_RESULT; ) is begin @@ -91,7 +91,7 @@ begin end ; >> -EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << pragma Warnings (Off, "unused initial value of """""); @@ -112,7 +112,7 @@ pragma Warnings (On, "unused initial value of """""); - + >> @@ -121,7 +121,7 @@ with Pre => bs.Current_Bit_Pos \< Natural'Last - _REQUIRED_BITS_FOR_ACN_ENCODING and then bs.Size_In_Bytes \< Positive'Last / 8 and then bs.Current_Bit_Pos + _REQUIRED_BITS_FOR_ACN_ENCODING \<= bs.Size_In_Bytes * 8, - Post => + Post => (result.Success and bs.Current_Bit_Pos \>= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos \<= bs'Old.Current_Bit_Pos + _REQUIRED_BITS_FOR_ACN_ENCODING) or not result.Success @@ -132,7 +132,7 @@ with Pre => bs.Current_Bit_Pos \< Natural'Last - _REQUIRED_BITS_FOR_ACN_ENCODING and then bs.Size_In_Bytes \< Positive'Last / 8 and then bs.Current_Bit_Pos + _REQUIRED_BITS_FOR_ACN_ENCODING \<= bs.Size_In_Bytes * 8, - Post => + Post => (result.Success and bs.Current_Bit_Pos \>= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos \<= bs'Old.Current_Bit_Pos + _REQUIRED_BITS_FOR_ACN_ENCODING) or not result.Success @@ -154,19 +154,19 @@ end if; MFen(soMF, soMFM, p) /*nogen*/ ::= "._encode(

)

" -alignToNext_encode(sMainBody, sAligmentValue, nAligmentValue) ::= << ---align to next -if (bs.Current_Bit_Pos mod ) /= 0 then - bs.Current_Bit_Pos := bs.Current_Bit_Pos + ( - (bs.Current_Bit_Pos mod )); +alignToNext_encode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +--align to next +if (bs.Current_Bit_Pos mod ) /= 0 then + bs.Current_Bit_Pos := bs.Current_Bit_Pos + ( - (bs.Current_Bit_Pos mod )); end if; >> -alignToNext_decode(sMainBody, sAligmentValue, nAligmentValue) ::= << ---align to next -if (bs.Current_Bit_Pos mod ) /= 0 then - bs.Current_Bit_Pos := bs.Current_Bit_Pos + ( - (bs.Current_Bit_Pos mod )); +alignToNext_decode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +--align to next +if (bs.Current_Bit_Pos mod ) /= 0 then + bs.Current_Bit_Pos := bs.Current_Bit_Pos + ( - (bs.Current_Bit_Pos mod )); end if; >> @@ -613,6 +613,7 @@ adaasn1rtl.encoding.acn.Acn_Dec_Boolean_false_pattern(bs,

, BitArray'(; >> +Null_declare(p) ::= "" Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << adaasn1rtl.encoding.acn.Acn_Enc_NullType_pattern(bs,

, BitArray'()); @@ -662,7 +663,7 @@ Enumerated_item_encode(p, sName, sEnumHolder, nItemIdxOrVal, sIntVal) ::= "when Enumerated_item_decode(p, sName, sEnumHolder, nItemIdxOrVal, sIntVal) ::= "when =>

:= ;" EnumeratedEncIdx_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActualCodecFunc, sIntVal) ::= << -case

is +case

is end case; @@ -709,9 +710,9 @@ adaasn1rtl.encoding.acn.Acn_Dec_String_Ascii_FixSize(bs,

, result); result.ErrorCode := ; >> -Acn_String_Ascii_Null_Teminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= "adaasn1rtl.encoding.acn.Acn_Enc_String_Ascii_Null_Teminated(bs, adaasn1rtl.OctetBuffer'(=>}; separator=\", \">),

);" -Acn_String_Ascii_Null_Teminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -adaasn1rtl.encoding.acn.Acn_Dec_String_Ascii_Null_Teminated(bs, adaasn1rtl.OctetBuffer'(=>}; separator=", ">),

, result); +Acn_String_Ascii_Null_Terminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= "adaasn1rtl.encoding.acn.Acn_Enc_String_Ascii_Null_Terminated(bs, adaasn1rtl.OctetBuffer'(=>}; separator=\", \">),

);" +Acn_String_Ascii_Null_Terminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << +adaasn1rtl.encoding.acn.Acn_Dec_String_Ascii_Null_Terminated(bs, adaasn1rtl.OctetBuffer'(=>}; separator=", ">),

, result); result.ErrorCode := ; >> @@ -765,7 +766,7 @@ result.ErrorCode := ; -loopFixedItem_enc (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< +loopFixedItem_enc (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< := 1; while \<= loop pragma Loop_Invariant ( >=1 and \<=); @@ -776,7 +777,7 @@ while \<= loop end loop; >> -loopFixedItem_dec (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< +loopFixedItem_dec (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< := 1; while \<= AND result.Success loop pragma Loop_Invariant ( >=1 and \<=); @@ -798,12 +799,12 @@ end loop; -sqf_external_field_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then

.Length := Integer(); @@ -812,12 +813,12 @@ end if; >> -sqf_external_field_fix_size_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_fix_size_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_fix_size_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_fix_size_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then @@ -843,7 +844,7 @@ end loop; if result.Success and = +1 then -- maximum number of elements was decoded. Makesure that the following bits is the termination pattern - result.Success := .encoding.BitStream_bitPatternMatches(bs,.OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), ); + result.Success := .encoding.BitStream_bitPatternMatches(bs,.OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), ); if result.Success then .encoding.BitStream_SkipBits(bs, );

.Length := -1; @@ -877,35 +878,37 @@ ReferenceType1_decode(p, sName, bAcnEncodeFuncRequiresResult, arrsArgs, arrsLoca /* SEQUENCE*/ -sequence_presense_optChild_encode(p, sAcc, sChName, sErrCode) ::= ".encoding.BitStream_AppendBit(bs,

.Exist.);" -sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << +sequence_presence_optChild_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= ".encoding.BitStream_AppendBit(bs,

.Exist.);" +sequence_presence_optChild_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << result.ErrorCode := ; -.encoding.BitStream_ReadBit(bs,

.Exist., result.Success); +.encoding.BitStream_ReadBit(bs, , result.Success); +

.Exist. := ; >> -sequence_presense_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << +sequence_presence_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << result := .ASN1_RESULT'(Success =>

.Exist. = (if () then 1 else 0), ErrorCode => ); >> -sequence_presense_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << -

.Exist. := (if () then 1 else 0); +sequence_presence_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << + := (if () then 1 else 0); +

.Exist. := ; result.Success := true; >> -sequence_presense_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" -sequence_presense_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= << +sequence_presence_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" +sequence_presence_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= <<

.Exist. := (if then 1 else 0); result.Success := true; >> -sequence_presense_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" -sequence_presense_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= << +sequence_presence_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" +sequence_presence_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= <<

.Exist. := (if = then 1 else 0); result.Success := true; >> -sequence_presense_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" -sequence_presense_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= << +sequence_presence_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" +sequence_presence_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= <<

.Exist. := (if = "" then 1 else 0); result.Success := true; >> @@ -934,7 +937,7 @@ sequence_save_bitstream_decode(sBitStreamPositionsLocalVar, sChName) ::=<< sequence_acn_child_encode(sChName, sChildContent, sErrCode, soSaveBitStrmPosStatement) ::= << ---Encode +--Encode if _is_initialized then result := .ASN1_RESULT'(Success => True, ErrorCode => 0); @@ -944,39 +947,39 @@ else end if; >> sequence_acn_child_decode(sChName, sChildContent, sErrCode, soSaveBitStrmPosStatement) ::= << ---Decode +--Decode >> sequence_mandatory_child_encode(sChName, sChildContent, soSaveBitStrmPosStatement) ::= << --- Encode +-- Encode >> sequence_mandatory_child_decode(sChName, sChildContent, soSaveBitStrmPosStatement) ::= << --- Decode +-- Decode >> -sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << -- Encode -- marked as ALWAYS PRESENT, so do not look in exist null; >> -sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << -- Decode -- marked as ALWAYS PRESENT, so do not look in exist -

.Exist. := 1; +

.Exist. := 1; >> -sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << -- Encode -- marked as ALWAYS ABSENT, so do not encode anything @@ -984,7 +987,7 @@ null; >> -sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << -- Decode -- marked as ALWAYS ABSENT, so do not decode anything

.Exist. := 0; @@ -993,7 +996,7 @@ result := .ASN1_RESULT'(Success => true, ErrorCode => 0); >> -sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << -- Encode if

.Exist. = 1 then @@ -1001,7 +1004,7 @@ if

.Exist. = 1 then end if; >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << -- Decode if

.Exist. = 1 then @@ -1009,27 +1012,12 @@ if

.Exist. = 1 then end if; >> - -sequence_optional_always_present_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << --- Encode (always present, do not check for presence) - - ->> - -sequence_optional_always_present_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << --- Decode (always present, do not check for presence) - -

.Exist. := 1; - ->> - - -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << - +sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << + >> -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << +sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << -- Decode if

.Exist. = 1 then @@ -1129,7 +1117,7 @@ end case; -/* Choice with presense determinants */ +/* Choice with presence determinants */ ChoiceChild_preWhen_bool_condition(sExtFld) ::= "" @@ -1176,28 +1164,28 @@ ChoiceChild_preWhen_decode(p, sAcc, sChildID, sChildBody, arrsConditions, bFirst MultiAcnUpdate_checkEqual_pri0(p1,p2) ::= "( = )" MultiAcnUpdate_checkEqual_str0(p1,p2) ::= "( = )" -MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, bIsFirst) ::= << +MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << ifelsif _is_initialized then --COVERAGE_IGNORE := ; --COVERAGE_IGNORE >> -MultiAcnUpdate_get_first_init_value_str(sV0, sVi, bIsFirst) ::= << - +MultiAcnUpdate_get_first_init_value_str(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << + >> -MultiAcnUpdate_checkEqual_pri(sV0, sVi) ::= "((_is_initialized and = ) or not _is_initialized)" -MultiAcnUpdate_checkEqual_str(sV0, sVi) ::= "((_is_initialized and = ) or not _is_initialized)" +MultiAcnUpdate_checkEqual_pri(sV0, sVi, sChPath, bIsAlwaysInit) ::= "((_is_initialized and = ) or not _is_initialized)" +MultiAcnUpdate_checkEqual_str(sV0, sVi, sChPath, bIsAlwaysInit) ::= "((_is_initialized and = ) or not _is_initialized)" -MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, arrsLocalCheckEquality) ::= << +MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, bIsFirstIntValueSingle, arrsLocalCheckEquality, sDefaultExpr) ::= << declare begin - + - - - else - result := .ASN1_RESULT'(Success => False, ErrorCode => ); --COVERAGE_IGNORE + + + else + result := .ASN1_RESULT'(Success => False, ErrorCode => ); --COVERAGE_IGNORE end if; result := .ASN1_RESULT'(Success => result.Success and (), ErrorCode => ); @@ -1236,7 +1224,7 @@ getSizeableSize(p, sAcc) ::= "

.Length" -ChoiceDependencyPres(sChPath, sAcc, arrsChoiceItems) ::= << +ChoiceDependencyPres(v, sChPath, sAcc, arrsChoiceItems) ::= << case kind is end case; @@ -1245,24 +1233,24 @@ end case; ChoiceDependencyIntPres_child(v, sChildNamePrese, nChildRetVal) ::= << when => _is_initialized := True; - := ; + := ; >> ChoiceDependencyStrPres_child(v, sChildNamePrese, sChildRetVal, arrsNullChars) ::= << when => _is_initialized := True; - := "" & ; + := "" & ; >> -ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName) ::= << +ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName, bIsOptional) ::= << when => _is_initialized := True; - := ; + := ; >> -ChoiceDependencyEnum(sChPath, sAcc, arrsChoiceEnumItems) ::= << +ChoiceDependencyEnum(sV, sChPath, sAcc, arrsChoiceEnumItems, bIsOptional, sDefaultExpr) ::= << case kind is end case; @@ -1270,7 +1258,7 @@ end case; -checkAccessPath(arrsCheckPaths, sUpdateStatement) ::= << +checkAccessPath(arrsCheckPaths, sUpdateStatement, v, sInitExpr) ::= << if () then end if; @@ -1349,15 +1337,15 @@ begin end if; end; - + >> -oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << adaasn1rtl.encoding.uper.BitStream_EncodeOctetString_no_length(bs,

Data, Integer(

Length)); >> -oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then

.Length := Integer(); @@ -1365,12 +1353,12 @@ if result.Success then end if; >> -oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_fix_size_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << adaasn1rtl.encoding.uper.BitStream_EncodeOctetString_no_length(bs,

Data, Integer()); >> -oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_fix_size_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then adaasn1rtl.encoding.uper.BitStream_DecodeOctetString_no_length(bs,

Data, Integer(), result.success); @@ -1378,11 +1366,11 @@ end if; >> -bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << adaasn1rtl.encoding.BitStream_AppendBitArray(bs,

Data, Integer()); >> -bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then

.Length := Integer(); @@ -1390,23 +1378,23 @@ if result.Success then end if; >> -bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_fixed_size_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << adaasn1rtl.encoding.BitStream_AppendBitArray(bs,

Data, Integer()); >> -bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_fixed_size_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << result := .ASN1_RESULT'(Success => \<= AND \<=, ErrorCode => ); if result.Success then adaasn1rtl.encoding.BitStream_ReadBitArray(bs,

Data, Integer(), result.success); end if; >> -bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +bit_string_null_terminated_encode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << adaasn1rtl.encoding.BitStream_AppendBitArray(bs,

Data,

Length); .encoding.BitStream_AppendBits(bs, .OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), ); >> -bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +bit_string_null_terminated_decode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << .encoding.BitStream_ReadBits_nullterminated(bs,

Data,

Length, .OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), , result.Success); if not result.Success then result.errorcode := ; -- COVERAGE_IGNORE @@ -1428,8 +1416,8 @@ while result.Success and then \<= and then not .e end loop; if result.Success and = +1 then - -- maximum number of elements was decoded. Makesure that the following bits is the termination pattern - result.Success := .encoding.BitStream_bitPatternMatches(bs,.OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), ); + -- maximum number of elements was decoded. Make sure that the following bits is the termination pattern + result.Success := .encoding.BitStream_bitPatternMatches(bs,.OctetBuffer'(=>16##}; wrap, anchor, separator=", ">), ); if result.Success then .encoding.BitStream_SkipBits(bs, );

.Length := -1; diff --git a/StgAda/equal_a.stg b/StgAda/equal_a.stg index cdb4b01b1..1f7aeb4bf 100644 --- a/StgAda/equal_a.stg +++ b/StgAda/equal_a.stg @@ -27,17 +27,17 @@ end if; >> -PrintEqualDefintionPrimitive(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionPrimitive(sFuncName, sTypeDefName) ::= << function (val1, val2 : ) return Boolean; >> -PrintEqualDefintionComposite(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionComposite(sFuncName, sTypeDefName) ::= << function (val1, val2 : ) return Boolean; >> PrintEqualPrimitive(sFuncName, sTypeDefName, sContent) ::= << - function (val1, val2 : ) + function (val1, val2 : ) return Boolean is begin return ; @@ -45,11 +45,11 @@ PrintEqualPrimitive(sFuncName, sTypeDefName, sContent) ::= << >> PrintEqualComposite(sFuncName, sTypeDefName, sContent, arrsLocalVars) ::= << - function (val1, val2 : ) return Boolean + function (val1, val2 : ) return Boolean is - pragma Warnings (Off, "initialization of ""ret"" has no effect"); + pragma Warnings (Off, "initialization of ""ret"" has no effect"); ret : Boolean := True; - pragma Warnings (On, "initialization of ""ret"" has no effect"); + pragma Warnings (On, "initialization of ""ret"" has no effect"); begin @@ -165,7 +165,7 @@ end if; >> -isEqual_Choice_Child(choiceTypeDefName, sNamePresent, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << +isEqual_Choice_Child(sChoiceTypeDefName, sNamePresent, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << when => >> diff --git a/StgAda/init_a.stg b/StgAda/init_a.stg index 715def5ba..ff2118254 100644 --- a/StgAda/init_a.stg +++ b/StgAda/init_a.stg @@ -27,7 +27,7 @@ initInteger(p, nValue) ::= "

:= ;" initReal(p, dValue) ::= "

:= ;" initBoolean(p, bValue) ::= "

:= TrueFALSE;" -initIA5String(sPtr, sValue) ::= " := ;" +initIA5String(sPtr, sValue) ::= " := ;" initEnumerated(sVal, sValue, sEnum) ::= " := ;" initNull(sVal) ::= " := 0;" @@ -35,9 +35,9 @@ initNull(sVal) ::= " := 0;" initTestCaseIA5String(p, sAcc, nSize, nMaxSizePlusOne, i, td/*:FE_StringTypeDefinition*/, bAlpha, arrnAlphabetAsciiCodes, nAlphabetLength, bZero) ::= << := 1; while \<= loop - -- commented because it casues this warning + -- commented because it casues this warning -- warning: condition can only be False if invalid values present - pragma Loop_Invariant ( >=1 and \<=); + pragma Loop_Invariant ( >=1 and \<=);

() := .NUL; @@ -59,7 +59,7 @@ while \<= loop end loop; >> -initObjectIdentifier_vali(p, sAcc, sI, nIntVal) ::= "

values() := ;" +initObjectIdentifier_valid(p, sAcc, sI, nIntVal) ::= "

values() := ;" initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= <<

length := ; @@ -68,14 +68,14 @@ initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= << init_Asn1LocalTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours := ;

mins := ; -

sec := ; +

sec := ;

fraction := ; >> init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours := ;

mins := ; -

sec := ; +

sec := ;

fraction := ; >> @@ -83,7 +83,7 @@ init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= << init_Asn1LocalTimeWithTimeZone(p, sAcc, tv/*:Asn1TimeValue*/, tz/*:Asn1TimeZoneValue*/) ::= <<

hours := ;

mins := ; -

sec := ; +

sec := ;

fraction := ;

tz.sign := ;

tz.hours := ; @@ -93,7 +93,7 @@ init_Asn1LocalTimeWithTimeZone(p, sAcc, tv/*:Asn1TimeValue*/, tz/*:Asn1TimeZoneV init_Asn1Date(p, sAcc, dt/*:Asn1DateValue*/) ::= <<

years := ;

months := ; -

days := ; +

days := ; >> init_Asn1Date_LocalTime(p, sAcc, dt/*:Asn1DateValue*/, tv/*:Asn1TimeValue*/) ::= << @@ -129,7 +129,7 @@ initFixVarSizeBitOrOctString(p, sAcc, nSize, arrsBytes) ::= << initTestCaseOctetString(p, sAcc, sArrayHolderName, nSize, i, bIsFixedSize, bZero, nMinSize, bZeroSizedArray) ::= << := 1; while \<= loop - -- commented because it casues this warning + -- commented because it casues this warning -- warning: condition can only be False if invalid values present pragma Loop_Invariant ( >=1 and \<=);

Data() := .Asn1Byte(0(-1) mod 256); @@ -141,7 +141,7 @@ end loop; initTestCaseBitString(p, sAcc, sArrayHolderName, nSize, nSizeCeiled, i, bIsFixedSize, bZero, nMinSize) ::= << := 1; while \<= loop - -- commented because it casues this warning + -- commented because it casues this warning -- warning: condition can only be False if invalid values present pragma Loop_Invariant ( >=1 and \<=);

Data() := .BIT(0(-1) mod 2); @@ -158,13 +158,13 @@ pragma Annotate (GNATprove, False_Positive,"""

.Data"" might not be initialize >> initFixedSequenceOf(arrsInnerValues) ::= << - + >> initVarSizeSequenceOf(p, sAcc, nSize, arrsInnerValues) ::= <<

Length := ; - + >> initTestCaseSizeSequenceOf_innerItem(bFirst, bLastItem, nCaseIdx, sChildCaseInit, i, nCaseLen) ::= << @@ -175,11 +175,11 @@ initTestCaseSizeSequenceOf_innerItem(bFirst, bLastItem, nCaseIdx, sChildCaseInit initTestCaseSizeSequenceOf(p, sAcc, noMinSize, nSize, bIsFixedSize, arrsInnerItems, bMultiCases, i) ::= << := 1; while \<= loop - -- commented because it casues this warning + -- commented because it casues this warning -- warning: condition can only be False if invalid values present pragma Loop_Invariant ( >=1 and \<=); - + end if; @@ -200,12 +200,12 @@ initSequence_optionalChild(p, sAcc, sChName, sPresentFlag, sChildContent) ::=<< >> initSequence(arrsInnerValues) ::= << - + >> initTestCase_sequence_child(p, sAcc, sChName, sChildContent, bOptional) ::= << ---set +--set

exist. := 1; >> @@ -219,14 +219,14 @@ initChoice(p, sAcc, sChildContent, sChildID, sChildName, sChildTypeName, sChoice declare : ; begin - +

:= '(kind => , => ); pragma Annotate (GNATprove, False_Positive,"discriminant check might fail", "reviewed by GM"); end;

:= '(kind => , => \<\>); - + >> @@ -257,18 +257,18 @@ procedure _set_( : in out ); -initFixSizeOctetString(nMax, bZeroSizedArray) ::= "(Data => (others => 0))" -initVarSizeOctetString(nMin, nMax) ::= "(Length => , Data => (others => 0))" +initFixSizeOctetString(sTypeDefName, nMax, bZeroSizedArray) ::= "(Data => (others => 0))" +initVarSizeOctetString(sTypeDefName, nMin, nMax) ::= "(Length => , Data => (others => 0))" -initFixSizeBitString(nMax, nMaxOctets) ::= "(Data => (others => 0))" -initVarSizeBitString(nMin, nMax, nMaxOctets) ::= "(Length => , Data => (others => 0))" +initFixSizeBitString(sTypeDefName, nMax, nMaxOctets) ::= "(Data => (others => 0))" +initVarSizeBitString(sTypeDefName, nMin, nMax, nMaxOctets) ::= "(Length => , Data => (others => 0))" initObjectIdentifierAsExpr() ::= << (length => 0, values => (others => 0)) >> -initFixSizeSequenceOfExpr(nMax, sChildExp) ::= "(Data => (others => ))" -initVarSizeSequenceOfExpr(nMin, nMax, sChildExp) ::= "(Length => , Data => (others => ))" +initFixSizeSequenceOfExpr(sTypeDefName, nMax, sChildExp) ::= "(Data => (others => ))" +initVarSizeSequenceOfExpr(sTypeDefName, nMin, nMax, sChildExp) ::= "(Length => , Data => (others => ))" initTypeConstant_def(sTypeDecl, sConstantName, sValue) ::= << @@ -308,9 +308,9 @@ init_Asn1Date_LocalTimeWithTimeZoneExpr() ::= << >> -initSequenceChildExpr(sChildName, sChildExpr) ::= " => " +initSequenceChildExpr(sChildName, sChildExpr, bIsOptional) ::= " => " initSequenceOptionalChildExpr(sChildName, nPresenceBit) ::= " => " -initSequenceExpr(arrsChildren, arrsOptionalChildren) ::= << +initSequenceExpr(sTypeDefName, sTypeDefNameExist, arrsChildren, arrsOptionalChildren) ::= << (, Exist => ()) >> diff --git a/StgAda/isvalid_a.stg b/StgAda/isvalid_a.stg index 8b04f474d..18073c7fe 100644 --- a/StgAda/isvalid_a.stg +++ b/StgAda/isvalid_a.stg @@ -52,7 +52,7 @@ ExpLt(sExp1, sExp2) ::= "( \< )" ExpLte(sExp1, sExp2) ::= "( \<= )" ExpOr(sExp1, sExp2) ::= "(() OR ())" ExpAnd(sExp1, sExp2) ::= "( AND )" -ExpAndMulit(arrsExp) ::= << +ExpAndMulti(arrsExp) ::= << >> ExpNot(sExp) ::= "(NOT )" @@ -60,19 +60,19 @@ StrLen(sExp) ::= ".getStringSize()" ArrayLen(sExp, sAcc) ::= "Length" -ExpressionToStament(sExp1) ::=<< +ExpressionToStatement(sExp1) ::=<< ret.Success := ; >> -StatementOrStament(sStat1, sStat2) ::= << +StatementOrStatement(sStat1, sStat2) ::= << if not ret.Success then end if; >> -ExpressionOrStament(sExp1, sStat2) ::= << +ExpressionOrStatement(sExp1, sStat2) ::= << ret := ; if not ret.Success then @@ -86,14 +86,14 @@ if not ret.Success then end if; >> -StatementAndStament(sStat1, sStat2) ::= << +StatementAndStatement(sStat1, sStat2) ::= << if ret.Success then end if; >> -ExpressionAndStament(sExp1, sStat2) ::= << +ExpressionAndStatement(sExp1, sStat2) ::= << ret.Success := ; if ret.Success then @@ -112,7 +112,7 @@ StatementNot(sStat) ::= << ret.Success := not ret.Success; >> -StatementExceptStament(sStat1, sStat2) ::= << +StatementExceptStatement(sStat1, sStat2) ::= << if ret.Success then @@ -120,7 +120,7 @@ if ret.Success then end if; >> -ExpressionExceptStament(sExp1, sStat2) ::= << +ExpressionExceptStatement(sExp1, sStat2) ::= << ret.Success := ; if ret.Success then @@ -165,9 +165,9 @@ is pragma Unreferenced (); - pragma Warnings (Off, "initialization of ""ret"" has no effect"); + pragma Warnings (Off, "initialization of ""ret"" has no effect"); ret : .ASN1_RESULT := .ASN1_RESULT'(Success => true, ErrorCode => 0); - pragma Warnings (On, "initialization of ""ret"" has no effect"); + pragma Warnings (On, "initialization of ""ret"" has no effect"); begin @@ -179,7 +179,7 @@ end ; Print_AlphabetCheckFunc(sFuncName, arrsAlphaConBody) ::= << -function (str : String) return boolean +function (str : String) return boolean with pre =\> STR'First=1 AND STR'Last\>=STR'First AND STR'Last\<=Integer'LAST-1 is @@ -203,8 +203,6 @@ PrintMultipleConstraints(arrsConstraints) ::= ",

)" @@ -214,13 +212,13 @@ call_base_type_func(p, sFuncName, soTypeCasting) ::= "ret := (kind = then end if; diff --git a/StgAda/spec_a.stg b/StgAda/spec_a.stg index 196b1c8b9..ccf6dbd20 100644 --- a/StgAda/spec_a.stg +++ b/StgAda/spec_a.stg @@ -50,7 +50,7 @@ use type .BIT; pragma Warnings (On, "use clause for type"); pragma Warnings (On, "is already use-visible through package use clause at line"); -"" are referenced"); pragma Warnings (Off, "use clause for package """" has no effect"); with ; use ; @@ -65,7 +65,7 @@ is }; separator="\n"> pragma Warnings (Off, "there are no others"); -}; separator="\n"> +}; separator="\n"> pragma Warnings (On, "there are no others"); private --# hide ; @@ -269,10 +269,10 @@ Define_subType_bit_string(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTy /*********************************** SEQUENCE OF ************************************************************/ -Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefintion) ::= << +Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefinition) ::= << -- -------------------------------------------- - + subtype is Integer range 1..; type is array () of ; @@ -283,8 +283,8 @@ type is record end record; >> -Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefintion) ::= << - +Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefinition) ::= << + @@ -299,12 +299,12 @@ Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableT Define_new_sequence_child_bit(sName) ::= ":.bit;" -Define_new_sequence_child(sName, sType) ::= " : ;" +Define_new_sequence_child(sName, sType, bIsOptional) ::= " : ;" Define_new_sequence_save_pos_child(td/*:FE_SequenceTypeDefinition*/, sName, nMaxBytesInACN) ::= " : .encoding.BitstreamPtr;" -Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildldrenDefintions, arrsNullFieldsSavePos) ::= << +Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildrenDefinitions, arrsNullFieldsSavePos) ::= << -- -------------------------------------------- - + @@ -316,22 +316,22 @@ for 'Size use (( - 1) / System.Word_Size -type is record +type is record end record; -type is record +type is record - + Exist : ; end record; -type is record +type is record null; end record; @@ -345,7 +345,7 @@ Define_subType_sequence(td/*:FE_SequenceTypeDefinition*/, prTd/*:FE_SequenceType - + @@ -359,9 +359,9 @@ when => : ; >> -Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildldrenDefintions) ::= << +Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildrenDefinitions) ::= << -- -------------------------------------------- - + subtype is Integer range 0..; @@ -370,14 +370,14 @@ for use ( => }; separator=", ">); for 'Size use 32; -type (kind : := ) is +type (kind : := ) is record case kind is end case; end record; -for use +for use record kind at 0 range 0..31; end record; diff --git a/StgAda/uper_a.stg b/StgAda/uper_a.stg index b64dcc426..ea4142971 100644 --- a/StgAda/uper_a.stg +++ b/StgAda/uper_a.stg @@ -8,7 +8,7 @@ call_base_type_func_decode(p, sFuncName) ::= "_aux(

, bs, result);" EmitTypeAssignment_def_err_code(sErrCode, nErrValue) ::= << -:constant Integer := ; +:constant Integer := ; >> EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInPER, nMaxBitsInPER, soSparkAnnotations, bReqBytesForEncodingIsZero) ::= << @@ -38,7 +38,7 @@ with Pre => bs.Current_Bit_Pos \< Natural'Last - _REQUIRED_BITS_FOR_ENCODING and then bs.Size_In_Bytes \< Positive'Last / 8 and then bs.Current_Bit_Pos + _REQUIRED_BITS_FOR_ENCODING \<= bs.Size_In_Bytes * 8, - Post => + Post => bs.Current_Bit_Pos \>= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos \<= bs'Old.Current_Bit_Pos + _REQUIRED_BITS_FOR_ENCODING >> @@ -47,7 +47,7 @@ with Pre => bs.Current_Bit_Pos \< Natural'Last - _REQUIRED_BITS_FOR_ENCODING and then bs.Size_In_Bytes \< Positive'Last / 8 and then bs.Current_Bit_Pos + _REQUIRED_BITS_FOR_ENCODING \<= bs.Size_In_Bytes * 8, - Post => + Post => bs.Current_Bit_Pos \>= bs'Old.Current_Bit_Pos and bs.Current_Bit_Pos \<= bs'Old.Current_Bit_Pos + _REQUIRED_BITS_FOR_ENCODING >> @@ -60,7 +60,7 @@ begin end ; >> -EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << procedure _aux( : ; bs : in out .encoding.Bitstream; result : OUT .ASN1_RESULT) is @@ -90,7 +90,7 @@ end _aux; >> -TasDecodeMain(sVarName, sFuncName, sTypeDefName, sInitilialExp) ::= /*nogen*/<< +TasDecodeMain(sVarName, sFuncName, sTypeDefName, sInitialExp) ::= /*nogen*/<< procedure (:out ; Stream : IN OUT _uPER_Stream; result : OUT .ASN1_RESULT) is begin @@ -104,7 +104,7 @@ begin end ; >> -EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << pragma Warnings (Off, "unused initial value of """""); @@ -133,19 +133,17 @@ pragma Warnings (On, "unused initial value of """""); - + >> - - +Null_declare(p) ::= "" decode_nullType(p) ::= <<

:= 0; result := .ASN1_RESULT'(Success => true, ErrorCode => 0); >> - /*case: A:: = INTEGER (5..5) */ IntNoneRequired_encode(p, nConst, sErrCode) ::= << -- No need to encode value since it will always be -- @@ -154,7 +152,7 @@ null; IntNoneRequired_decode(p, nConst, sErrCode) ::= << result := .ASN1_RESULT'(Success => true, ErrorCode => 0); -

:= ; +

:= ; >> @@ -172,15 +170,15 @@ adaasn1rtl.encoding.uper.UPER_Dec_ConstraintPosWholeNumber(bs,

, > /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "adaasn1rtl.encoding.uper.UPER_Enc_UnConstraintWholeNumber(bs,

);" -IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << +IntUnconstrained_encode(p, sErrCode, bCoverageIgnore) ::= "adaasn1rtl.encoding.uper.UPER_Enc_UnConstraintWholeNumber(bs,

);" +IntUnconstrained_decode(p, sErrCode, bCoverageIgnore) ::= << result.ErrorCode := ; adaasn1rtl.encoding.uper.UPER_Dec_UnConstraintWholeNumber(bs,

, result.Success); >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "adaasn1rtl.encoding.uper.UPER_Enc_UnConstraintWholeNumber(bs,

);" -IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << +IntUnconstrainedMax_encode(p, nMax, soCheckExp, sErrCode) ::= "adaasn1rtl.encoding.uper.UPER_Enc_UnConstraintWholeNumber(bs,

);" +IntUnconstrainedMax_decode(p, nMax, soCheckExp, sErrCode) ::= << result.ErrorCode := ; adaasn1rtl.encoding.uper.UPER_Dec_UnConstraintWholeNumberMax(bs,

, , result.Success); --result.Success := result.Success and then (); @@ -218,10 +216,10 @@ declare begin .encoding.BitStream_ReadBit(bs, extBit, result.Success); -- read extension bit if result.Success then - if extBit=0 then --extBit is zero ==> value is expecteted within root range + if extBit=0 then --extBit is zero ==> value is expected within root range else - + end if; end if; end; @@ -234,9 +232,9 @@ if then .encoding.BitStream_AppendBit(bs, 0); -- value within root range, so ext bit is zero else - -- value is not within root range, so ext bit is one and value is encoded as uncostraint + -- value is not within root range, so ext bit is one and value is encoded as unconstrained .encoding.BitStream_AppendBit(bs, 1); - + end if; >> @@ -285,7 +283,7 @@ Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, n declare intVal:Asn1Int; begin - case

is + case

is end case; adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, intVal, , ); @@ -320,52 +318,52 @@ result := .ASN1_RESULT'(Success => true, ErrorCode => 0); -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= ".encoding.BitStream_AppendBit(bs,

.Exist.);" -sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << +sequence_presence_bit_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= ".encoding.BitStream_AppendBit(bs,

.Exist.);" +sequence_presence_bit_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << result.ErrorCode := ; .encoding.BitStream_ReadBit(bs,

.Exist., result.Success); >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= ".encoding.BitStream_AppendBit(bs, );" -sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << - +sequence_presence_bit_fix_encode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= ".encoding.BitStream_AppendBit(bs, );" +sequence_presence_bit_fix_decode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= << + >> sequence_mandatory_child_encode(sChName, sChildContent) ::= << ---Encode +--Encode >> sequence_mandatory_child_decode(sChName, sChildContent) ::= << ---Decode +--Decode >> -sequence_optional_child_encode(p, sAcc, sChName, sChildContent) ::= << ---Encode +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << +--Encode if

.Exist. = 1 then end if; >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent) ::= << ---Decode +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << +--Decode if

.Exist. = 1 then end if; >> -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << - +sequence_default_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << + >> -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << ---Decode +sequence_default_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << +--Decode if

.Exist. = 1 then else @@ -383,9 +381,7 @@ end if; >> - - - +sequence_build(p, sTypeDefName, arrsChildren) ::= "" /* SEQUENCE end */ @@ -431,7 +427,7 @@ end if; -loopFixedItem_enc (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< +loopFixedItem_enc (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< while \<= loop pragma Loop_Invariant ( >=1 and \<=); pragma Loop_Invariant (bs.Current_Bit_Pos \>= bs.Current_Bit_Pos'Loop_Entry); @@ -442,7 +438,7 @@ end loop; >> -loopFixedItem_dec (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< +loopFixedItem_dec (i, fixedSize, nfixedSizeUperLimit, sInternalItem, nCurOffset, nAlignSize, nIntItemMinSize, nIntItemMaxSize)::= /*nogen*/<< while \<= AND result.Success loop pragma Loop_Invariant ( >=1 and \<=); pragma Loop_Invariant (bs.Current_Bit_Pos \>= bs.Current_Bit_Pos'Loop_Entry); @@ -493,34 +489,34 @@ result.ErrorCode := ; -str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << - := 1; +str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << + := 1; >> -str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << --val := _Init; result := .ASN1_RESULT'(Success => True, ErrorCode => 0); - := 1; + := 1;

( + 1) := adaasn1rtl.NUL; >> -str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << nStringLength := .getStringSize(

); result.Success := nStringLength >= AND nStringLength \<= ; - := 1; + := 1; if result.Success then adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, .Asn1Int(nStringLength), , ); end if; >> -str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << --val := _Init; -result.ErrorCode := .ERR_INSUFFICIENT_DATA; +result.ErrorCode := .ERR_INSUFFICIENT_DATA; adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, nStringLength, , , , result.Success); - := 1; + := 1; --add nulls until the end @@ -559,16 +555,16 @@ if not result.Success then end if; >> -octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << +octet_FixedSize_encode(sTypeDefName, p, sAcc, nFixedSize) ::= << adaasn1rtl.encoding.uper.BitStream_EncodeOctetString_no_length(bs,

Data, Integer()); >> -octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << +octet_FixedSize_decode(sTypeDefName, p, sAcc, nFixedSize) ::= << result := .ASN1_RESULT'(Success => True, ErrorCode => 0); adaasn1rtl.encoding.uper.BitStream_DecodeOctetString_no_length(bs,

Data, Integer(), result.success); >> -octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << result.Success :=

Length >= AND

Length \<= ; result.errorCode := ; if result.Success then @@ -577,7 +573,7 @@ if result.Success then end if; >> -octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, nStringLength, , , , result.Success); result.errorCode := ;

.Length := nStringLength; @@ -586,31 +582,31 @@ if result.Success then end if; >> -seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << - := 1; +seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << + := 1; >> -seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << result := .ASN1_RESULT'(Success => True, ErrorCode => 0); - := 1; + := 1; >> -seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << +seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << result.Success :=

Length >= AND

Length \<= ; result.errorCode := ; - := 1; + := 1; if result.Success then adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, .Asn1Int(

Length), , ); end if; >> -seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << +seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, nStringLength, , , , result.Success); result.errorCode := ; - := 1; + := 1;

.Length := nStringLength; >> @@ -681,7 +677,7 @@ while >= 16#4000# and \< elsif >= 16#8000# then := 16#8000#; adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, 16#C2#, 0, 8); - else + else := 16#4000#; adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, 16#C1#, 0, 8); end if; @@ -738,7 +734,7 @@ FixedSize_Fragmentation_sqf_64K_decode(p, sAcc,sCurOffset, sCurBlockSize, sBlock --we expect to decode Blocks and each block must contain 64K elements. Each block must begin with the byte 0xC4 := 16#10000#; := 1; -result.ErrorCode := ; +result.ErrorCode := ; for in 1 .. loop adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, , 0, 255, 8, result.Success); result.Success := result.Success AND ( = 16#C4#); @@ -794,7 +790,7 @@ end if; Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSizeMax, nRequiredBitsForUPerEncoding, bIsVariableSize, sErrCodeName, sRemainingItemsVar, sCurBlockSize, sBlockIndex, sCurOffset, sBLJ, sBLI, sLengthTmp, bIsBitStringType, bIsAsciiString) ::= << := 0; := 0; -result.ErrorCode := ; +result.ErrorCode := ; -- decode blockSize adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, , 0, 255, 8, result.Success); := 1; @@ -807,13 +803,13 @@ while result.Success AND ( = 16#C4# OR := 16#C000#; elsif = 16#C2# then := 16#8000#; - else + else := 16#4000#; end if; := ; while \<= + - 1 AND result.Success loop - --# assert >= and \<= + and + --# assert >= and \<= + and --# K.K>=K~.K and K.K\<=K~.K+8+ *(-1); := + 1; @@ -838,7 +834,7 @@ end if; if + -1 \<= then := ; while \<= + -1 loop - --# assert >= and \<= + and + --# assert >= and \<= + and --# K.K>=K~.K and K.K\<=K~.K+8+ *(-1); := + 1; @@ -847,7 +843,7 @@ if + -1 \<= then end if; - + if >= and \<= then

Length := ; @@ -873,7 +869,7 @@ end if;

( + 1) := adaasn1rtl.NUL; - + >> @@ -942,32 +938,32 @@ end; /* BIT STRING*/ -bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << +bitString_FixSize_encode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= << adaasn1rtl.encoding.BitStream_AppendBitArray(bs,

Data, Integer()); >> -bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << +bitString_FixSize_decode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= << adaasn1rtl.encoding.BitStream_ReadBitArray(bs,

Data, Integer(), result.success); if not result.Success then result.errorcode := ; -- COVERAGE_IGNORE end if; >> -bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +bitString_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << result.Success :=

Length >= AND

Length \<= ; result.errorCode := ; if result.Success then adaasn1rtl.encoding.uper.UPER_Enc_ConstraintWholeNumber(bs, .Asn1Int(

Length), , ); - + end if; >> -bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +bitString_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << adaasn1rtl.encoding.uper.UPER_Dec_ConstraintWholeNumberInt(bs, nStringLength, , , , result.Success); result.errorCode := ; if result.Success then

Length := nStringLength; - + end if; >> diff --git a/StgAda/variables_a.stg b/StgAda/variables_a.stg index ac04f634b..0a4b7e806 100644 --- a/StgAda/variables_a.stg +++ b/StgAda/variables_a.stg @@ -45,32 +45,32 @@ PrintBooleanValue(bValue) ::= "TrueFALSE" PrintNullValue() ::= "0" PrintOctetStringValue(td/*:FE_SizeableTypeDefinition*/,bIsFixedSize, arruBytes, nCount) ::= << -'(Length => ,Data => '(=>16##}; wrap, anchor, separator=", ">, others=> 16#0#)) +'(Length => ,Data => '(=>16##}; wrap, anchor, separator=", ">, others=> 16#0#)) >> -PrintBitOrOctetStringValueAsCompoundLitteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << +PrintBitOrOctetStringValueAsCompoundLiteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << >> -PrintOctetArrayAsCompoundLitteral(arruBytes) ::= << +PrintOctetArrayAsCompoundLiteral(arruBytes) ::= << .OctetBuffer'(=>16##}; wrap, anchor, separator=", ">) >> -PrintBitArrayAsCompoundLitteral(arruBits) ::= << +PrintBitArrayAsCompoundLiteral(arruBits) ::= << .BitArray'(=>16##}; wrap, anchor, separator=", ">) >> PrintBitStringValue(td/*:FE_SizeableTypeDefinition*/,bIsFixedSize, arrsBits, nCount, arruBytes, nBytesCount) ::= << -'(Length => ,Data => '(=>}; wrap, anchor, separator=", ">, others=> 0)) +'(Length => ,Data => '(=>}; wrap, anchor, separator=", ">, others=> 0)) >> PrintObjectIdentifierValue(td/*:FE_PrimitiveTypeDefinition*/, arrnValues, nCount) ::= << -'(Length => , values => .ObjectIdentifier_array'(, others=> 0)) +'(Length => , values => .ObjectIdentifier_array'(, others=> 0)) >> PrintObjectIdentifierValueAsCompoundLiteral(arrnValues, nCount) ::= << -.Asn1ObjectIdentifier'(Length => , values => .ObjectIdentifier_array'(, others=> 0)) +.Asn1ObjectIdentifier'(Length => , values => .ObjectIdentifier_array'(, others=> 0)) >> diff --git a/StgAda/xer_a.stg b/StgAda/xer_a.stg index 48f3b0771..16ab58426 100644 --- a/StgAda/xer_a.stg +++ b/StgAda/xer_a.stg @@ -4,7 +4,7 @@ rtlModuleName() ::= "adaasn1rtl" EmitTypeAssignment_def_err_code(sErrCode, nErrValue) ::= << -:constant Integer := ; +:constant Integer := ; >> EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInXER, soSparkAnnotations) ::= << @@ -21,7 +21,7 @@ procedure _aux( : ; xmlTag : ; >> -EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp) ::= << +EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp) ::= << procedure _aux( : ; xmlTag : .encoding.xer.XString; bs : in out .encoding.xer.CharStream; ret : OUT .ASN1_RESULT) is @@ -59,7 +59,7 @@ procedure _aux(: out ; xmlTag : _aux(: out ; xmlTag : .encoding.xer.XString; bs : in out .encoding.xer.CharStream; ret : OUT .ASN1_RESULT) is @@ -163,13 +163,13 @@ ret.ErrorCode := (if ret.Success then 0 else ); Enumerated_item_encode(p, sTag, nLevel, sItemID, sXerValue, sErrCode, bFirst) ::= << -when => +when => adaasn1rtl.encoding.xer.Xer_EncodeEnumerated(bs, , "", ret, ); ret.ErrorCode := ; >> Enumerated_encode(p, sTag, nLevel, arrsItems, soCheckExp, sErrCode) ::= << -case

is +case

is end case; >> @@ -187,7 +187,7 @@ begin adaasn1rtl.encoding.xer.Xer_DecodeEnumerated(bs, , enmLabel, ret); if ret.Success then - else + else ret.ErrorCode := ; end if; else @@ -308,12 +308,12 @@ ret.ErrorCode := (if ret.Success then 0 else ); /* SEQUENCE Start*/ Sequence_mandatory_child_encode(sChName, sChildContent, sChildTag) ::= << ---Encode +--Encode >> Sequence_mandatory_child_decode(sChName, sChildContent, sChildTag) ::= << ---Decode +--Decode ret.Success := adaasn1rtl.encoding.xer.Xer_NextStartElementIs(bs, ""); if ret.Success then @@ -321,14 +321,14 @@ end if; >> Sequence_optional_child_encode(p, sAcc, sChName, sChildContent, sChildTag) ::= << ---Encode +--Encode if

.Exist. = 1 then end if; >> Sequence_optional_child_decode(p, sAcc, sChName, sChildContent, sChildTag) ::= << ---Decode +--Decode

.Exist. := 0; if adaasn1rtl.encoding.xer.Xer_NextStartElementIs(bs, "") then

.Exist. := 1; @@ -342,7 +342,7 @@ Sequence_default_child_encode(p, sAcc, sChName, sChildContent, sChildTag, sInitW Sequence_default_child_decode(p, sAcc, sChName, sChildContent, sChildTag, sInitWithDefaultValue) ::= << ---Decode +--Decode

.Exist. := 0; if adaasn1rtl.encoding.xer.Xer_NextStartElementIs(bs, "") then

.Exist. := 1; @@ -414,7 +414,7 @@ begin adaasn1rtl.encoding.xer.Xer_LA_NextElementTag(bs, nextTag, ret); ret.ErrorCode := (if ret.Success then 0 else ); if ret.Success then - + else ret.Success := False; ret.ErrorCode := ; diff --git a/StgC/LangGeneric_c.fs b/StgC/LangGeneric_c.fs index 307db7cf0..20c3388f5 100644 --- a/StgC/LangGeneric_c.fs +++ b/StgC/LangGeneric_c.fs @@ -6,19 +6,24 @@ open FsUtils open Language open System.IO -let getAccess_c (fpt:FuncParamType) = - match fpt with - | VALUE x -> "." - | POINTER x -> "->" - | FIXARRAY x -> "" +let getAccess_c (sel: Selection) = + match sel.selectionType with + | Pointer -> "->" + | _ -> "." + +let getAccess2_c (acc: Accessor) = + match acc with + | ValueAccess (sel, _, _) -> $".{sel}" + | PointerAccess (sel, _, _) -> $"->{sel}" + | ArrayAccess (ix, _) -> $"[{ix}]" #if false -let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = - let ii = id.SeqeuenceOfLevel + 1; - let i = sprintf "i%d" (id.SeqeuenceOfLevel + 1) +let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = + let ii = id.SequenceOfLevel + 1; + let i = sprintf "i%d" (id.SequenceOfLevel + 1) let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (maxSize - minSize)) - let funcBodyContent, localVariables = + let funcBodyContent, localVariables = let nStringLength = match isFixedSize, codec with | true , _ -> [] @@ -28,9 +33,9 @@ let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Co match minSize with | _ when maxSize < 65536I && isFixedSize -> uper_c.bitString_FixSize p.arg.p (getAccess_c p.arg) (minSize) errCode.errCodeName codec , nStringLength | _ when maxSize < 65536I && (not isFixedSize) -> uper_c.bitString_VarSize p.arg.p (getAccess_c p.arg) (minSize) (maxSize) errCode.errCodeName nSizeInBits codec, nStringLength - | _ -> + | _ -> handleFragmentation p codec errCode ii (uperMaxSizeInBits) minSize maxSize "" 1I true false - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} #endif @@ -51,61 +56,53 @@ type LangGeneric_c() = | Asn1AcnAst.ASN1SCC_UInt64 _ -> sprintf "%sUL" (i.ToString()) | Asn1AcnAst.ASN1SCC_UInt _ -> sprintf "%sUL" (i.ToString()) - override _.doubleValueToString (v:double) = + override _.doubleValueToString (v:double) = v.ToString(FsUtils.doubleParseString, System.Globalization.NumberFormatInfo.InvariantInfo) override _.initializeString stringSize = sprintf "{ [0 ... %d] = 0x0 }" stringSize - + override _.supportsInitExpressions = false override _.requiresHandlingOfEmptySequences = true override _.requiresHandlingOfZeroArrays = true - override _.getPointer (fpt:FuncParamType) = - match fpt with - |VALUE x -> sprintf "(&(%s))" x - |POINTER x -> x - |FIXARRAY x -> x - - override this.getValue (fpt:FuncParamType) = - match fpt with - | VALUE x -> x - | POINTER x -> sprintf "(*(%s))" x - | FIXARRAY x -> x - - override this.getAccess (fpt:FuncParamType) = getAccess_c fpt - - override this.ArrayAccess idx = "[" + idx + "]" - - override this.getPtrPrefix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "" - | FIXARRAY x -> "" - - override this.getPtrSuffix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "*" - | FIXARRAY x -> "" - - override this.getStar (fpt:FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "*" - | FIXARRAY x -> "" - - override this.getArrayItem (fpt:FuncParamType) (idx:string) (childTypeIsString: bool) = - let newPath = sprintf "%s%sarr[%s]" fpt.p (this.getAccess fpt) idx - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - + override this.getPointer (sel: Selection) = + let str = sel.joined this + match sel.selectionType with + | Value -> $"(&({str}))" + | _ -> str + + override this.getValue (sel: Selection) = + let str = sel.joined this + match sel.selectionType with + | Pointer -> $"(*({str}))" + | _ -> str + + override this.getAccess (sel: Selection) = getAccess_c sel + + override this.getAccess2 (acc: Accessor) = getAccess2_c acc + override this.getPtrPrefix _ = "" + + override this.getPtrSuffix (sel: Selection) = + match sel.selectionType with + | Pointer -> "*" + | _ -> "" + + override this.getStar (sel: Selection) = + match sel.selectionType with + | Pointer -> "*" + | _ -> "" + override this.setNamedItemBackendName0 (nm:Asn1Ast.NamedItem) (newValue:string) : Asn1Ast.NamedItem = {nm with c_name = newValue} override this.getNamedItemBackendName0 (nm:Asn1Ast.NamedItem) = nm.c_name - override this.getNamedItemBackendName (defOrRef:TypeDefintionOrReference option) (nm:Asn1AcnAst.NamedItem) = + override this.getArrayItem (sel: Selection) (idx:string) (childTypeIsString: bool) = + (sel.appendSelection "arr" FixArray false).append (ArrayAccess (idx, if childTypeIsString then FixArray else Value)) + + override this.getNamedItemBackendName (defOrRef:TypeDefinitionOrReference option) (nm:Asn1AcnAst.NamedItem) = ToC nm.c_name - override this.getNamedItemBackendName2 (_:string) (_:string) (nm:Asn1AcnAst.NamedItem) = + override this.getNamedItemBackendName2 (_:string) (_:string) (nm:Asn1AcnAst.NamedItem) = ToC nm.c_name override this.decodeEmptySeq _ = None override this.decode_nullType _ = None @@ -115,7 +112,7 @@ type LangGeneric_c() = override this.typeDef (ptd:Map) = ptd.[C] override this.getTypeDefinition (td:Map) = td.[C] - override this.getEnmTypeDefintion (td:Map) = td.[C] + override this.getEnumTypeDefinition (td:Map) = td.[C] override this.getStrTypeDefinition (td:Map) = td.[C] override this.getChoiceTypeDefinition (td:Map) = td.[C] override this.getSequenceTypeDefinition (td:Map) = td.[C] @@ -134,32 +131,33 @@ type LangGeneric_c() = let acnRtl = match encodings |> Seq.exists(fun e -> e = ACN) with true -> ["asn1crt_encoding_acn"] | false -> [] let xerRtl = match encodings |> Seq.exists(fun e -> e = XER) with true -> ["asn1crt_encoding_xer"] | false -> [] encRtl@uperRtl@acnRtl@xerRtl - - override this.getEmptySequenceInitExpression () = "{}" + + override this.getEmptySequenceInitExpression _ = "{}" override this.callFuncWithNoArgs () = "()" override this.rtlModuleName = "" override this.AssignOperator = "=" override this.TrueLiteral = "TRUE" override this.FalseLiteral = "FALSE" - override this.emtyStatement = "" + override this.emptyStatement = "" override this.bitStreamName = "BitStream" - override this.unaryNotOperator = "!" - override this.modOp = "%" - override this.eqOp = "==" - override this.neqOp = "!=" - override this.andOp = "&&" - override this.orOp = "||" - override this.initMetod = InitMethod.Procedure - + override this.unaryNotOperator = "!" + override this.modOp = "%" + override this.eqOp = "==" + override this.neqOp = "!=" + override this.andOp = "&&" + override this.orOp = "||" + override this.initMethod = InitMethod.Procedure + override _.decodingKind = InPlace + override _.usesWrappedOptional = false override this.castExpression (sExp:string) (sCastType:string) = sprintf "(%s)(%s)" sCastType sExp override this.createSingleLineComment (sText:string) = sprintf "/*%s*/" sText - + override _.SpecNameSuffix = "" - override _.SpecExtention = "h" - override _.BodyExtention = "c" - override _.Keywords = CommonTypes.c_keyworkds + override _.SpecExtension = "h" + override _.BodyExtension = "c" + override _.Keywords = CommonTypes.c_keywords override _.getValueAssignmentName (vas: ValueAssignment) = vas.c_name @@ -168,111 +166,62 @@ type LangGeneric_c() = override this.allowsSrcFilesWithNoFunctions = true override this.requiresValueAssignmentsInSrcFile = true override this.supportsStaticVerification = false - - override this.getSeqChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) (removeDots: bool) = - let newPath = sprintf "%s%s%s" fpt.p (this.getAccess fpt) childName - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - override this.getChChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) : FuncParamType = - let newPath = sprintf "%s%su.%s" fpt.p (this.getAccess fpt) childName - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - - override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = + + override this.getSeqChild (sel: Selection) (childName:string) (childTypeIsString: bool) (childIsOptional: bool) = + sel.appendSelection childName (if childTypeIsString then FixArray else Value) childIsOptional + + override this.getChChild (sel: Selection) (childName:string) (childTypeIsString: bool) : Selection = + (sel.appendSelection "u" Value false).appendSelection childName (if childTypeIsString then FixArray else Value) false + + override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = let prefix = ToC (id.AcnAbsPath.Tail.StrJoin("_").Replace("#","elem")) match typeIdsSet.TryFind prefix with - | None -> prefix + "_NONE" - | Some a when a = 1 -> prefix + "_NONE" - | Some a -> ToC (id.AcnAbsPath.StrJoin("_").Replace("#","elem")) + "_NONE" + | None -> prefix + "_NONE" + | Some a when a = 1 -> prefix + "_NONE" + | Some a -> ToC (id.AcnAbsPath.StrJoin("_").Replace("#","elem")) + "_NONE" - override this.presentWhenName (defOrRef:TypeDefintionOrReference option) (ch:ChChildInfo) : string = + override this.presentWhenName (defOrRef:TypeDefinitionOrReference option) (ch:ChChildInfo) : string = (ToC ch._present_when_name_private) + "_PRESENT" override this.getParamTypeSuffix (t:Asn1AcnAst.Asn1Type) (suf:string) (c:Codec) : CallerScope = - match c with - | Encode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Real _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.IA5String _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("val" + suf) } - | Asn1AcnAst.NumericString _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("val" + suf) } - | Asn1AcnAst.OctetString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.NullType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.BitString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Boolean _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Enumerated _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.SequenceOf _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Sequence _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Choice _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ObjectIdentifier _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.TimeType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ReferenceType r -> - this.getParamTypeSuffix r.resolvedType suf c - | Decode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Real _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.IA5String _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("val" + suf) } - | Asn1AcnAst.NumericString _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("val" + suf) } - | Asn1AcnAst.OctetString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.NullType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.BitString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Boolean _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Enumerated _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.SequenceOf _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Sequence _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Choice _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ObjectIdentifier _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.TimeType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ReferenceType r -> this.getParamTypeSuffix r.resolvedType suf c - - override this.getParamValue (t:Asn1AcnAst.Asn1Type) (p:FuncParamType) (c:Codec) = - match c with - | Encode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> this.getPointer p - | Asn1AcnAst.Real _ -> this.getPointer p - | Asn1AcnAst.IA5String _ -> this.getValue p //FIXARRAY "val" - | Asn1AcnAst.NumericString _-> this.getValue p// FIXARRAY "val" - | Asn1AcnAst.OctetString _ -> this.getPointer p - | Asn1AcnAst.NullType _ -> this.getPointer p - | Asn1AcnAst.BitString _ -> this.getPointer p - | Asn1AcnAst.Boolean _ -> this.getPointer p - | Asn1AcnAst.Enumerated _ -> this.getPointer p - | Asn1AcnAst.SequenceOf _ -> this.getPointer p - | Asn1AcnAst.Sequence _ -> this.getPointer p - | Asn1AcnAst.Choice _ -> this.getPointer p - | Asn1AcnAst.ObjectIdentifier _ -> this.getPointer p - | Asn1AcnAst.TimeType _ -> this.getPointer p - | Asn1AcnAst.ReferenceType r -> this.getParamValue r.resolvedType p c - | Decode -> - match t.Kind with - | Asn1AcnAst.IA5String _ -> this.getValue p //FIXARRAY "val" - | Asn1AcnAst.NumericString _ -> this.getValue p// FIXARRAY "val" - | Asn1AcnAst.ReferenceType r -> this.getParamValue r.resolvedType p c - | _ -> this.getPointer p + let rec getRecvType (kind: Asn1AcnAst.Asn1TypeKind) = + match kind with + | Asn1AcnAst.NumericString _ | Asn1AcnAst.IA5String _ -> FixArray + | Asn1AcnAst.ReferenceType r -> getRecvType r.resolvedType.Kind + | _ -> Pointer + let recvId = "pVal" + suf + {CallerScope.modName = t.id.ModName; arg = Selection.emptyPath recvId (getRecvType t.Kind) } + + override this.getParamValue (t:Asn1AcnAst.Asn1Type) (sel: Selection) (c:Codec) = + match t.Kind with + | Asn1AcnAst.IA5String _ -> this.getValue sel //FIXARRAY "val" + | Asn1AcnAst.NumericString _ -> this.getValue sel// FIXARRAY "val" + | Asn1AcnAst.ReferenceType r -> this.getParamValue r.resolvedType sel c + | _ -> this.getPointer sel override this.getLocalVariableDeclaration (lv:LocalVariable) : string = match lv with | SequenceOfIndex (i,None) -> sprintf "int i%d;" i - | SequenceOfIndex (i,Some iv) -> sprintf "int i%d=%d;" i iv + | SequenceOfIndex (i,Some iv) -> sprintf "int i%d=%s;" i iv | IntegerLocalVariable (name,None) -> sprintf "int %s;" name - | IntegerLocalVariable (name,Some iv) -> sprintf "int %s=%d;" name iv + | IntegerLocalVariable (name,Some iv) -> sprintf "int %s=%s;" name iv | Asn1SIntLocalVariable (name,None) -> sprintf "asn1SccSint %s;" name - | Asn1SIntLocalVariable (name,Some iv) -> sprintf "asn1SccSint %s=%d;" name iv + | Asn1SIntLocalVariable (name,Some iv) -> sprintf "asn1SccSint %s=%s;" name iv | Asn1UIntLocalVariable (name,None) -> sprintf "asn1SccUint %s;" name - | Asn1UIntLocalVariable (name,Some iv) -> sprintf "asn1SccUint %s=%d;" name iv + | Asn1UIntLocalVariable (name,Some iv) -> sprintf "asn1SccUint %s=%s;" name iv | FlagLocalVariable (name,None) -> sprintf "flag %s;" name - | FlagLocalVariable (name,Some iv) -> sprintf "flag %s=%d;" name iv + | FlagLocalVariable (name,Some iv) -> sprintf "flag %s=%s;" name iv | BooleanLocalVariable (name,None) -> sprintf "flag %s;" name - | BooleanLocalVariable (name,Some iv) -> sprintf "flag %s=%s;" name (if iv then "TRUE" else "FALSE") + | BooleanLocalVariable (name,Some iv) -> sprintf "flag %s=%s;" name iv | AcnInsertedChild(name, vartype, initVal) -> sprintf "%s %s;" vartype name | GenericLocalVariable lv -> sprintf "%s%s %s%s;" (if lv.isStatic then "static " else "") lv.varType lv.name (if lv.arrSize.IsNone then "" else "["+lv.arrSize.Value+"]") - - override this.getLongTypedefName (tdr:TypeDefintionOrReference) : string = + + override this.getLongTypedefName (tdr:TypeDefinitionOrReference) : string = match tdr with | TypeDefinition td -> td.typedefName | ReferenceToExistingDefinition ref -> ref.typedefName - + //override this.getEnmLongTypedefName (td:FE_EnumeratedTypeDefinition) _ = td; override this.toHex n = sprintf "0x%x" n @@ -291,13 +240,13 @@ type LangGeneric_c() = catd = false //createBitStringFunction = createBitStringFunction_funcBody_c seqof_lv = - (fun id minSize maxSize -> [SequenceOfIndex (id.SeqeuenceOfLevel + 1, None)]) + (fun id minSize maxSize -> [SequenceOfIndex (id.SequenceOfLevel + 1, None)]) } - override this.acn = + override this.acn = { Acn_parts.null_valIsUnReferenced = true checkBitPatternPresentResult = true - getAcnDepSizeDeterminantLocVars = + getAcnDepSizeDeterminantLocVars = fun sReqBytesForUperEncoding -> [ GenericLocalVariable {GenericLocalVariable.name = "arr"; varType = "byte"; arrSize = Some sReqBytesForUperEncoding; isStatic = true; initExp = None} @@ -306,7 +255,7 @@ type LangGeneric_c() = choice_handle_always_absent_child = false choice_requires_tmp_decoding = false } - override this.init = + override this.init = { Initialize_parts.zeroIA5String_localVars = fun _ -> [] choiceComponentTempInit = false @@ -327,30 +276,30 @@ type LangGeneric_c() = override this.CreateAuxFiles (r:AstRoot) (di:DirInfo) (arrsSrcTstFiles : string list, arrsHdrTstFiles:string list) = let CreateCMainFile (r:AstRoot) outDir = - //Main file for test cass + //Main file for test cass let printMain = test_cases_c.PrintMain //match l with C -> test_cases_c.PrintMain | Ada -> test_cases_c.PrintMain let content = printMain "testsuite" let outFileName = Path.Combine(outDir, "mainprogram.c") File.WriteAllText(outFileName, content.Replace("\r","")) - let generateVisualStudtioProject (r:DAst.AstRoot) outDir (arrsSrcTstFilesX, arrsHdrTstFilesX) = - let extrSrcFiles, extrHdrFiles = - r.args.encodings |> - List.collect(fun e -> + let generateVisualStudioProject (r:DAst.AstRoot) outDir (arrsSrcTstFilesX, arrsHdrTstFilesX) = + let extrSrcFiles, extrHdrFiles = + r.args.encodings |> + List.collect(fun e -> match e with | Asn1Encoding.UPER -> ["asn1crt_encoding";"asn1crt_encoding_uper"] | Asn1Encoding.ACN -> ["asn1crt_encoding";"asn1crt_encoding_uper"; "asn1crt_encoding_acn"] | Asn1Encoding.BER -> ["asn1crt_encoding";"asn1crt_encoding_ber"] | Asn1Encoding.XER -> ["asn1crt_encoding";"asn1crt_encoding_xer"] - ) |> + ) |> List.distinct |> List.map(fun a -> a + ".c", a + ".h") |> List.unzip let arrsSrcTstFiles = (r.programUnits |> List.map (fun z -> z.testcase_bodyFileName)) let arrsHdrTstFiles = (r.programUnits |> List.map (fun z -> z.testcase_specFileName)) - let vcprjContent = xml_outputs.emitVisualStudioProject + let vcprjContent = xml_outputs.emitVisualStudioProject ((r.programUnits |> List.map (fun z -> z.bodyFileName))@extrSrcFiles) ((r.programUnits |> List.map (fun z -> z.specFileName))@extrHdrFiles) (arrsSrcTstFiles@arrsSrcTstFilesX) @@ -363,7 +312,7 @@ type LangGeneric_c() = CreateCMainFile r di.srcDir - generateVisualStudtioProject r di.srcDir (arrsSrcTstFiles, arrsHdrTstFiles) + generateVisualStudioProject r di.srcDir (arrsSrcTstFiles, arrsHdrTstFiles) //AlwaysPresentRtlFuncNames override this.AlwaysPresentRtlFuncNames : string list = [ @@ -593,8 +542,8 @@ type LangGeneric_c() = "Acn_Dec_Real_IEEE754_32_big_endian_fp32" "Acn_Dec_Real_IEEE754_32_little_endian_fp32" "Acn_Enc_String_Ascii_FixSize" - "Acn_Enc_String_Ascii_Null_Teminated" - "Acn_Enc_String_Ascii_Null_Teminated_mult" + "Acn_Enc_String_Ascii_Null_Terminated" + "Acn_Enc_String_Ascii_Null_Terminated_mult" "Acn_Enc_String_Ascii_External_Field_Determinant" "Acn_Enc_String_Ascii_Internal_Field_Determinant" "Acn_Enc_String_CharIndex_FixSize" @@ -603,8 +552,8 @@ type LangGeneric_c() = "Acn_Enc_IA5String_CharIndex_External_Field_Determinant" "Acn_Enc_IA5String_CharIndex_Internal_Field_Determinant" "Acn_Dec_String_Ascii_FixSize" - "Acn_Dec_String_Ascii_Null_Teminated" - "Acn_Dec_String_Ascii_Null_Teminated_mult" + "Acn_Dec_String_Ascii_Null_Terminated" + "Acn_Dec_String_Ascii_Null_Terminated_mult" "Acn_Dec_String_Ascii_External_Field_Determinant" "Acn_Dec_String_Ascii_Internal_Field_Determinant" "Acn_Dec_String_CharIndex_FixSize" @@ -636,7 +585,7 @@ type LangGeneric_c() = "ObjectIdentifier_subidentifiers_uper_decode" "ObjectIdentifier_subidentifiers_uper_encode" "BitStream_DecodeNonNegativeInteger32Neg" - ] + ] override this.detectFunctionCalls (sourceCode: string) (functionName: string) : string list = let knownCases = [ @@ -691,12 +640,10 @@ type LangGeneric_c() = newLines |> String.concat "\n" override this.removeFunctionFromBody (sourceCode: string) (functionName: string) : string = - //if functionName = "BitStream_DecodeNonNegativeInteger32Neg" then - // printfn "debug" let pattern = @"[^\s]+\s+" + functionName + @"\s*\([^\)]*\)\s*\{" let regex = System.Text.RegularExpressions.Regex(pattern) let matches = regex.Matches(sourceCode) - + if matches.Count = 0 then sourceCode else @@ -721,5 +668,5 @@ type LangGeneric_c() = override this.getDirInfo (target:Targets option) rootDir = {rootDir = rootDir; srcDir=rootDir;asn1rtlDir=rootDir;boardsDir=rootDir} - + override this.getTopLevelDirs (target:Targets option) = [] diff --git a/StgC/acn_c.stg b/StgC/acn_c.stg index 3793246b7..0b8152a84 100644 --- a/StgC/acn_c.stg +++ b/StgC/acn_c.stg @@ -17,13 +17,13 @@ EmitAcnParameter(sName, sType) ::= " " EmitTypeAssignment_primitive_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInACN, nMaxBitsInACN, arrsAcnPrms, soSparkAnnotations) ::= << -#define _REQUIRED_BYTES_FOR_ACN_ENCODING +#define _REQUIRED_BYTES_FOR_ACN_ENCODING #define _REQUIRED_BITS_FOR_ACN_ENCODING flag (const , BitStream* pBitStrm, int* pErrCode, flag bCheckConstraints); >> -EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << flag (const , BitStream* pBitStrm, int* pErrCode, flag bCheckConstraints) { flag ret = TRUE; @@ -51,7 +51,7 @@ flag (const , BitStream* pBitStrm, in - + return ret; } >> @@ -61,7 +61,7 @@ EmitTypeAssignment_primitive_def_decode(sVarName, sStar, sFuncName, sTypeDefName flag ( , BitStream* pBitStrm, int* pErrCode, ); >> -EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << flag ( , BitStream* pBitStrm, int* pErrCode, ) { flag ret = TRUE; @@ -109,8 +109,8 @@ if (ret) { -loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< -for(=0; ( \< (int)) && ret; ++) +loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< +for(=0; ( \< (int)) && ret; ++) { } @@ -118,14 +118,14 @@ for(=0; ( \< (int)) && ret; ++) -alignToNext_encode(sMainBody, sAligmentValue, nAligmentValue) ::= << -Acn_AlignTo(pBitStrm, TRUE); +alignToNext_encode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +Acn_AlignTo(pBitStrm, TRUE); >> -alignToNext_decode(sMainBody, sAligmentValue, nAligmentValue) ::= << -Acn_AlignTo(pBitStrm, FALSE); +alignToNext_decode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +Acn_AlignTo(pBitStrm, FALSE); >> @@ -347,7 +347,7 @@ Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse { static byte true_data[] = {}; separator=",">}; static byte false_data[] = {}; separator=",">}; - byte* tmp =

? true_data : false_data; + byte* tmp =

? true_data : false_data; BitStream_AppendBits(pBitStrm, tmp, ); } >> @@ -368,7 +368,7 @@ Boolean_decode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalse - +Null_declare(p) ::= "" Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << @@ -435,7 +435,7 @@ EnumeratedEncIdx_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActual EnumeratedEncValues_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActualCodecFunc, sErrCode, sFirstItemName, sIntVal) ::= << -switch(

) { +switch(

) { default: /*COVERAGE_IGNORE*/ ret = FALSE; /*COVERAGE_IGNORE*/ @@ -467,9 +467,9 @@ ret = Acn_Dec_String_Ascii_FixSize(pBitStrm, ,

); >> -Acn_String_Ascii_Null_Teminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= "Acn_Enc_String_Ascii_Null_Teminated_mult(pBitStrm, , (byte[]){}, ,

);" -Acn_String_Ascii_Null_Teminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -ret = Acn_Dec_String_Ascii_Null_Teminated_mult(pBitStrm, , (byte[]){}, ,

); +Acn_String_Ascii_Null_Terminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= "Acn_Enc_String_Ascii_Null_Terminated_mult(pBitStrm, , (byte[]){}, ,

);" +Acn_String_Ascii_Null_Terminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << +ret = Acn_Dec_String_Ascii_Null_Terminated_mult(pBitStrm, , (byte[]){}, ,

); >> @@ -486,7 +486,7 @@ ret = Acn_Dec_String_Ascii_Internal_Field_Determinant(pBitStrm, , > PrintAlphabet2(arrnCharSet) /*nogen*/ ::= << -static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; +static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; >> Acn_String_CharIndex_FixSize_encode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << @@ -522,12 +522,12 @@ ret = Acn_Dec_IA5String_CharIndex_External_Field_Determinant(pBitStrm, > -oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << ret = BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount); >> -oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << ret = ((\<=) && (\<=)); if (ret) {

nCount = (int); @@ -535,12 +535,12 @@ if (ret) { } >> -oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_fix_size_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << ret = BitStream_EncodeOctetString_no_length(pBitStrm,

arr, ); >> -oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_fix_size_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << ret = ((\<=) && (\<=)); if (ret) { ret = BitStream_DecodeOctetString_no_length(pBitStrm,

arr, ); @@ -548,13 +548,13 @@ if (ret) { >> - -sqf_external_field_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << + +sqf_external_field_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << ret = ((\<=) && (\<=)); if (ret) {

nCount = (int); @@ -562,12 +562,12 @@ if (ret) { } >> -sqf_external_field_fix_size_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_fix_size_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_fix_size_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_fix_size_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << ret = ((\<=) && (\<=)); if (ret) { @@ -605,11 +605,11 @@ if (ret && (checkBitPatternPresentResult == 0)) { >> -bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << BitStream_AppendBits(pBitStrm,

arr,

nCount); >> -bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << ret = ((\<=) && (\<=)); if (ret) {

nCount = (int); @@ -618,11 +618,11 @@ if (ret) { } >> -bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_fixed_size_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << BitStream_AppendBits(pBitStrm,

arr, ); >> -bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_fixed_size_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << ret = ((\<=) && (\<=)); if (ret) { ret = BitStream_ReadBits(pBitStrm,

arr, ); @@ -630,12 +630,12 @@ if (ret) { } >> -bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +bit_string_null_terminated_encode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << BitStream_AppendBits(pBitStrm,

arr,

nCount); BitStream_AppendBits(pBitStrm, (byte[]){}, ); >> -bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +bit_string_null_terminated_decode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << ret = BitStream_ReadBits_nullterminated(pBitStrm, (byte[]){}, ,

arr, , &

nCount); *pErrCode = ret ? 0 : ; >> @@ -660,38 +660,39 @@ ret = _ACN_Decode(

, pBitStrm, pErrCode, exist. = presenceBit == 0 ? 0 : 1; +sequence_presence_optChild_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= "BitStream_AppendBit(pBitStrm,

exist.);" +sequence_presence_optChild_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << +ret = BitStream_ReadBit(pBitStrm, &); +

exist. = == 0 ? 0 : 1; *pErrCode = ret ? 0 : ; >> -sequence_presense_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << +sequence_presence_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << ret =

exist. == (() ? 1 : 0); *pErrCode = ret ? 0 : ; >> -sequence_presense_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << -

exist. = () ? 1 : 0; +sequence_presence_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << + = () ? 1 : 0; +

exist. = ; >> -sequence_presense_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" -sequence_presense_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= << +sequence_presence_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" +sequence_presence_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= <<

exist. = ? 1 : 0; >> -sequence_presense_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" -sequence_presense_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= << +sequence_presence_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" +sequence_presence_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= <<

exist. = ( == ) ? 1 : 0; >> -sequence_presense_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" -sequence_presense_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= << +sequence_presence_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" +sequence_presence_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= <<

exist. = (strcmp(, "") == 0) ? 1 : 0; >> sequence_save_bitStream_start_encode(sBitStreamPositionsLocalVar) ::=<< - = *pBitStrm; //save the initial position of the bit stream at + = *pBitStrm; //save the initial position of the bit stream at >> sequence_save_bitStream_start_decode(sBitStreamPositionsLocalVar) ::=<< @@ -736,13 +737,13 @@ sequence_mandatory_child_decode(sChName, sChildContent, soSaveBitStrmPosStatemen >> -sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << /*Encode */ /* marked as ALWAYS PRESENT, so do not look in exist */ >> -sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << /*Decode */ /* marked as ALWAYS PRESENT */

exist. = 1; @@ -750,14 +751,14 @@ sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soSaveBit >> -sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << /*Encode */ /* marked as ALWAYS ABSENT, so do not encode anything */ (void)

; (void)pBitStrm; >> -sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << /*Decode */ /* marked as ALWAYS ABSENT, so do not decode anything */ @@ -766,7 +767,7 @@ sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, soSaveBitSt >> -sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /*Encode */ if (

exist.) { @@ -774,7 +775,7 @@ if (

exist.) { } >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /*Decode */ if (

exist.) { @@ -782,28 +783,13 @@ if (

exist.) { } >> - -sequence_optional_always_present_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << -/*Encode */ +sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << - + >> -sequence_optional_always_present_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << -/*Decode (always present) */ - -

exist. = 1; - ->> - -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << - - ->> - - -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << +sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /*Decode */ if (

exist.) { @@ -813,7 +799,6 @@ if (

exist.) { } >> - sequence_call_post_encoding_function(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << (

, &, &, pBitStrm); >> @@ -854,7 +839,7 @@ case : >> Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << -switch(

kind) +switch(

kind) { }; separator="\n"> default: /*COVERAGE_IGNORE*/ @@ -867,17 +852,17 @@ Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_C ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &, 0, ); *pErrCode = ret ? 0 : ; if (ret) { - switch() + switch() { }; separator="\n"> default: /*COVERAGE_IGNORE*/ *pErrCode = ; /*COVERAGE_IGNORE*/ ret = FALSE; /*COVERAGE_IGNORE*/ - } + } } /*COVERAGE_IGNORE*/ >> -/* Choice with presense determinants */ +/* Choice with presence determinants */ ChoiceChild_preWhen_encode(p, sAcc, sChildID, sChildBody, arrsConditions, bFirst, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case : @@ -898,7 +883,7 @@ ChoiceChild_preWhen_decode(p, sAcc, sChildID, sChildBody, arrsConditions, bFirst Choice_preWhen_encode(p, sAcc, arrsChildren, sErrCode) ::= << -switch(

kind) +switch(

kind) { default: @@ -922,7 +907,7 @@ else { ChoiceChild_Enum_encode(p, sAcc, sEnmName, sChildID, sChildBody, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << -case : +case : break; >> @@ -936,7 +921,7 @@ case : Choice_Enum_encode(p, sAcc, arrsChildren, sEnmExtFld, sErrCode) ::= << -switch(

kind) +switch(

kind) { default: @@ -975,14 +960,14 @@ SizeDependencyFixedSize(v, nFixedSize) ::= << -ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName) ::= << +ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName, bIsOptional) ::= << case : _is_initialized = TRUE; - = ; + = ; break; >> -ChoiceDependencyEnum(sChPath, sAcc, arrsChoiceEnumItems) ::= << +ChoiceDependencyEnum(sV, sChPath, sAcc, arrsChoiceEnumItems, bIsOptional, sDefaultExpr) ::= << switch (kind) { default: @@ -999,19 +984,19 @@ PresenceDependency(v, sSeqPath, sAcc, sChildName) ::= << ChoiceDependencyIntPres_child(v, sChildNamePrese, nChildRetVal) ::= << case : - _is_initialized = TRUE; - = ; + _is_initialized = TRUE; + = ; break; >> ChoiceDependencyStrPres_child(v, sChildNamePrese, sChildRetVal, arrsNullChars) ::= << case : _is_initialized = TRUE; - strcpy(, ""); + strcpy(, ""); break; >> -ChoiceDependencyPres(sChPath, sAcc, arrsChoiceItems) ::= << +ChoiceDependencyPres(v, sChPath, sAcc, arrsChoiceItems) ::= << switch (kind) { default: @@ -1024,30 +1009,30 @@ switch (kind) { MultiAcnUpdate_checkEqual_pri0(p1,p2) ::= "( == )" MultiAcnUpdate_checkEqual_str0(p1,p2) ::= "(strcmp(,) == 0)" -MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, bIsFirst) ::= << +MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << else if (_is_initialized) { /*COVERAGE_IGNORE*/ = ; /*COVERAGE_IGNORE*/ } /*COVERAGE_IGNORE*/ >> -MultiAcnUpdate_get_first_init_value_str(sV0, sVi, bIsFirst) ::= << +MultiAcnUpdate_get_first_init_value_str(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << else if (_is_initialized) { /*COVERAGE_IGNORE*/ strcpy(, ); /*COVERAGE_IGNORE*/ } /*COVERAGE_IGNORE*/ >> -MultiAcnUpdate_checkEqual_pri(sV0, sVi) ::= "((_is_initialized && == ) || !_is_initialized)" -MultiAcnUpdate_checkEqual_str(sV0, sVi) ::= "((_is_initialized && strcmp(,) == 0) || !_is_initialized)" +MultiAcnUpdate_checkEqual_pri(sV0, sVi, sChPath, bIsAlwaysInit) ::= "((_is_initialized && == ) || !_is_initialized)" +MultiAcnUpdate_checkEqual_str(sV0, sVi, sChPath, bIsAlwaysInit) ::= "((_is_initialized && strcmp(,) == 0) || !_is_initialized)" -MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, arrsLocalCheckEquality) ::= << +MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, bIsFirstIntValueSingle, arrsLocalCheckEquality, sDefaultExpr) ::= << { - + - + if (ret) { - + *pErrCode = ; else { ret = FALSE; /*COVERAGE_IGNORE*/ @@ -1065,7 +1050,7 @@ MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatement -checkAccessPath(arrsCheckPaths, sUpdateStatement) ::= << +checkAccessPath(arrsCheckPaths, sUpdateStatement, v, sInitExpr) ::= << if () { } @@ -1173,7 +1158,7 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, nBits octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits, nMinSize, nMaxSize, bFixedSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; @@ -1223,12 +1208,12 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBitsForUperEncoding, nBits, nMinSize, nMaxSize, bFixedSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; BitStream_Init(&bitStrm, arr, sizeof(arr)); - + ret = BitStream_ReadBits(pBitStrm, arr, ); if (ret) { diff --git a/StgC/equal_c.stg b/StgC/equal_c.stg index a3616ad7d..d6ab528ea 100644 --- a/StgC/equal_c.stg +++ b/StgC/equal_c.stg @@ -32,11 +32,11 @@ if (ret) { E Q U A L F U N C T I O N S ***************************************************************************************** */ -PrintEqualDefintionPrimitive(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionPrimitive(sFuncName, sTypeDefName) ::= << flag (const val1, const val2); >> -PrintEqualDefintionComposite(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionComposite(sFuncName, sTypeDefName) ::= << flag (const * pVal1, const * pVal2); >> @@ -108,8 +108,8 @@ isEqual_NullType()/*nogen*/ ::= "ret = TRUE;" isEqual_BitString(p1,p2,bIsFixedSize, nFixedSize) ::= << - (nCount == nCount) && - (memcmp(arr, arr, nCount/8) == 0) && + (nCount == nCount) && + (memcmp(arr, arr, nCount/8) == 0) && (nCount % 8 > 0 ? (arr[nCount/8] \>> (8-nCount % 8) == arr[nCount/8]\>>(8-nCount % 8) ) : TRUE) @@ -126,7 +126,7 @@ isEqual_OctetString(p1,p2, bIsFixedSize, nFixedSize) ::= << (nCount == nCount) && (memcmp(arr, arr, nCount) ==0) memcmp(arr, arr, ) ==0 - + >> isObjectIdentifier_equal(p1, p2) ::= << @@ -135,7 +135,7 @@ ObjectIdentifier_equal(, ) -isEqual_Choice_Child(choiceTypeDefName, sCid, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << +isEqual_Choice_Child(sChoiceTypeDefName, sCid, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << case : break; @@ -144,7 +144,7 @@ case : isEqual_Choice(p1,p2, sAccess, arrsChildren) ::= << ret = (kind == kind); if (ret) { - switch(kind) + switch(kind) { }; separator="\n"> default: /*COVERAGE_IGNORE*/ @@ -174,7 +174,7 @@ if (ret && exist.) { isEqual_SequenceOf_var_size(p1,p2, sAcc, i, soInnerStatement) ::= << ret = (nCount == nCount); -for( = 0; ret && \< nCount; ++) +for( = 0; ret && \< nCount; ++) { } @@ -183,7 +183,7 @@ for( = 0; ret && \< nCount; ++) >> isEqual_SequenceOf_fix_size(p1,p2, sAcc, i, nFixedSize, sInnerStatement) ::= << -for( = 0; ret && \< ; ++) +for( = 0; ret && \< ; ++) { } diff --git a/StgC/header_c.stg b/StgC/header_c.stg index 603b1fdba..947d043c1 100644 --- a/StgC/header_c.stg +++ b/StgC/header_c.stg @@ -27,14 +27,14 @@ extern "C" { }; separator="\n"> -}; separator="\n"> +}; separator="\n"> /* ================= Encoding/Decoding function prototypes ================= * These functions are placed at the end of the file to make sure all types * have been declared first, in case of parameterized ACN encodings * ========================================================================= */ -}; separator="\n"> +}; separator="\n"> #ifdef __cplusplus @@ -57,7 +57,7 @@ PrintValueAssignment(sName, sTypeDecl, sValue) ::= "extern const ; Define_new_octet_string(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize) ::= << typedef struct { - int nCount; + int nCount; - + byte arr[]; } ; @@ -180,7 +180,7 @@ typedef struct { int nCount; /*Number of bits in the array. Max value is : */ - + byte arr[]; } ; >> @@ -192,24 +192,24 @@ typedef ; /*********************************** SEQUENCE OF ************************************************************/ -Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefintion) ::= << +Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefinition) ::= << - + typedef struct { - int nCount; + int nCount; - + arr[]; } ; >> -Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefintion) ::= << +Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefinition) ::= << - + typedef ; >> @@ -218,17 +218,17 @@ typedef ; /*********************************** SEQUENCE ************************************************************/ Define_new_sequence_child_bit(sName) ::= "unsigned long :1;" -Define_new_sequence_child(sName, sType) ::= " ;" +Define_new_sequence_child(sName, sType, bIsOptional) ::= " ;" Define_new_sequence_save_pos_child(td/*:FE_SequenceTypeDefinition*/, sName, nMaxBytesInACN) ::= "BitStream ;" -Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildldrenDefintions, arrsNullFieldsSavePos) ::= << +Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildrenDefinitions, arrsNullFieldsSavePos) ::= << /*-- --------------------------------------------*/ - + typedef struct { -} ; +} ; @@ -250,7 +250,7 @@ typedef struct { Define_subType_sequence(td/*:FE_SequenceTypeDefinition*/, prTd/*:FE_SequenceTypeDefinition*/, soParentTypePackage, arrsOptionalChildren) ::= << typedef ; -typedef ; +typedef ; >> @@ -262,23 +262,23 @@ Define_new_choice_child(sName, sType, sPresent) ::=<< ; >> -Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildldrenDefintions) ::= << +Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildrenDefinitions) ::= << /*-- --------------------------------------------*/ - + typedef enum { , - }; separator=",\n"> + }; separator=",\n"> } ; typedef union { }; separator="\n"> -} ; +} ; typedef struct { kind; - - u; + + u; } ; >> diff --git a/StgC/init_c.stg b/StgC/init_c.stg index 6bcb5a21a..ed9109c2a 100644 --- a/StgC/init_c.stg +++ b/StgC/init_c.stg @@ -12,7 +12,7 @@ initTypeAssignment(sVarName, sPtrPrefix, sPtrSuffix, sFuncName, sTypeDefName, sC void ( ) { (void); - + @@ -24,7 +24,7 @@ initInteger(sVal, nValue) ::= " = ;" initReal(sVal, dValue) ::= " = ;" initBoolean(sVal, bValue) ::= " = TRUEFALSE;" -initObjectIdentifier_vali(p, sAcc, sI, nIntVal) ::= "

values[] = ;" +initObjectIdentifier_valid(p, sAcc, sI, nIntVal) ::= "

values[] = ;" initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= <<

nCount = ; @@ -33,14 +33,14 @@ initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= << init_Asn1LocalTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours = ;

mins = ; -

sec = ; +

sec = ;

fraction = ; >> init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours = ;

mins = ; -

sec = ; +

sec = ;

fraction = ; >> @@ -48,7 +48,7 @@ init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= << init_Asn1LocalTimeWithTimeZone(p, sAcc, tv/*:Asn1TimeValue*/, tz/*:Asn1TimeZoneValue*/) ::= <<

hours = ;

mins = ; -

sec = ; +

sec = ;

fraction = ;

tz.sign = ;

tz.hours = ; @@ -58,7 +58,7 @@ init_Asn1LocalTimeWithTimeZone(p, sAcc, tv/*:Asn1TimeValue*/, tz/*:Asn1TimeZoneV init_Asn1Date(p, sAcc, dt/*:Asn1DateValue*/) ::= <<

years = ;

months = ; -

days = ; +

days = ; >> init_Asn1Date_LocalTime(p, sAcc, dt/*:Asn1DateValue*/, tv/*:Asn1TimeValue*/) ::= << @@ -93,7 +93,7 @@ memset(

, 0x0, ); memset(

, 0x0, ); while (\< ) { - static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; + static byte allowedCharSet[] = {}; wrap, anchor, separator=",">};

[] = allowedCharSet[ % ]; @@ -162,13 +162,13 @@ initSequence_pragma(p) ::= "" initFixedSequenceOf(arrsInnerValues) ::= << - + >> initVarSizeSequenceOf(p, sAcc, nSize, arrsInnerValues) ::= <<

nCount = ; - + >> @@ -195,7 +195,7 @@ initSequence_optionalChild(p, sAcc, sChName, sPresentFlag, sChildContent) ::=<< >> initSequence(arrsInnerValues) ::= << - + >> initSequence_emptySeq(p) ::= "" @@ -213,7 +213,7 @@ initTestCase_sequence_child_opt(p, sAcc, sChName) ::= << initChoice(p, sAcc, sChildContent, sChildID, sChildName, sChildTypeName, sChoiceTypeName, sChildTempVarName, sChildTempDefaultInit, bComponentTempInit) ::= <<

kind = ; - + >> @@ -255,14 +255,14 @@ const = ; #endif >> -initFixSizeOctetString(nMax, bZeroSizedArray) ::= "{.arr = {[0 ... -1] = 0 }}" -initVarSizeOctetString(nMin, nMax) ::= "{.nCount = , .arr = {[0 ... -1] = 0 }}" +initFixSizeOctetString(sTypeDefName, nMax, bZeroSizedArray) ::= "{.arr = {[0 ... -1] = 0 }}" +initVarSizeOctetString(sTypeDefName, nMin, nMax) ::= "{.nCount = , .arr = {[0 ... -1] = 0 }}" -initFixSizeBitString(nMax, nMaxOctets) ::= "{.arr = {[0 ... -1] = 0 }}" -initVarSizeBitString(nMin, nMax, nMaxOctets) ::= "{.nCount = , .arr = {[0 ... -1] = 0 }}" +initFixSizeBitString(sTypeDefName, nMax, nMaxOctets) ::= "{.arr = {[0 ... -1] = 0 }}" +initVarSizeBitString(sTypeDefName, nMin, nMax, nMaxOctets) ::= "{.nCount = , .arr = {[0 ... -1] = 0 }}" -initFixSizeSequenceOfExpr(nMax, sChildExp) ::= "{.arr = {[0 ... -1] = }}" -initVarSizeSequenceOfExpr(nMin, nMax, sChildExp) ::= "{.nCount = , .arr = {[0 ... -1] = }}" +initFixSizeSequenceOfExpr(sTypeDefName, nMax, sChildExp) ::= "{.arr = {[0 ... -1] = }}" +initVarSizeSequenceOfExpr(sTypeDefName, nMin, nMax, sChildExp) ::= "{.nCount = , .arr = {[0 ... -1] = }}" initObjectIdentifierAsExpr() ::= << @@ -298,9 +298,9 @@ init_Asn1Date_LocalTimeWithTimeZoneExpr() ::= << {.years = 0, .months = 0, .days = 0, .hours = 0, .mins = 0, .sec = 0, .fraction = 0, .tz.sign = 0, .tz.hours = 0, .tz.mins = 0 } >> -initSequenceChildExpr(sChildName, sChildExpr) ::= ". = " +initSequenceChildExpr(sChildName, sChildExpr, bIsOptional) ::= ". = " initSequenceOptionalChildExpr(sChildName, nPresenceBit) ::= ". = " -initSequenceExpr(arrsChildren, arrsOptionalChildren) ::= << +initSequenceExpr(sTypeDefName, sTypeDefNameExist, arrsChildren, arrsOptionalChildren) ::= << {, .exist = {}} >> diff --git a/StgC/isvalid_c.stg b/StgC/isvalid_c.stg index 7837704a4..64dec7bc9 100644 --- a/StgC/isvalid_c.stg +++ b/StgC/isvalid_c.stg @@ -3,10 +3,6 @@ rtlModuleName() ::= "" -getStringSize(p) ::= "strlen(

)" - - - JoinItems(sPart, soNestedPart) ::= << @@ -42,20 +38,20 @@ always_false_statement(sErrorCodeName)::= << ret = FALSE; /*COVERAGE_IGNORE*/ *pErrCode = ; /*COVERAGE_IGNORE*/ >> - + makeExpressionToStatement0(sIsValidExp) ::= << ret = ; >> convertVCBExpressionToStatementAndUpdateErrCode(sIsValidExp, sErrCode) ::= << -ret = ; -*pErrCode = ret ? 0 : ; +ret = ; +*pErrCode = ret ? 0 : ; >> convertVCBStatementToStatementAndUpdateErrCode(sStatement, sErrCode) ::= << -*pErrCode = ret ? 0 : ; +*pErrCode = ret ? 0 : ; >> convertVCBTRUEToStatementAndUpdateErrCode() ::= << @@ -117,7 +113,7 @@ ExpLt(sExp1, sExp2) ::= "( \< )" ExpLte(sExp1, sExp2) ::= "( \<= )" ExpOr(sExp1, sExp2) ::= "(() || ())" ExpAnd(sExp1, sExp2) ::= "( && )" -ExpAndMulit(arrsExp) ::= << +ExpAndMulti(arrsExp) ::= << >> ExpNot(sExp) ::= "(!)" @@ -125,11 +121,11 @@ StrLen(sExp) ::= "strlen()" ArrayLen(sExp, sAcc) ::= "nCount" -ExpressionToStament(sExp1) ::=<< +ExpressionToStatement(sExp1) ::=<< ret = ; >> -StatementOrStament(sStat1, sStat2) ::= << +StatementOrStatement(sStat1, sStat2) ::= << if (!ret) { @@ -137,8 +133,8 @@ if (!ret) { >> -ExpressionOrStament(sExp1, sStat2) ::= << -ret = ; +ExpressionOrStatement(sExp1, sStat2) ::= << +ret = ; if (!ret) { } @@ -151,14 +147,14 @@ if (!ret) { } >> -StatementAndStament(sStat1, sStat2) ::= << +StatementAndStatement(sStat1, sStat2) ::= << if (ret) { } >> -ExpressionAndStament(sExp1, sStat2) ::= << +ExpressionAndStatement(sExp1, sStat2) ::= << ret = ; if (ret) { @@ -177,7 +173,7 @@ StatementNot(sStat) ::= << ret = !ret; >> -StatementExceptStament(sStat1, sStat2) ::= << +StatementExceptStatement(sStat1, sStat2) ::= << if (ret) { @@ -185,7 +181,7 @@ if (ret) { } >> -ExpressionExceptStament(sExp1, sStat2) ::= << +ExpressionExceptStatement(sExp1, sStat2) ::= << ret = ; if (ret) { @@ -201,7 +197,7 @@ if (ret) { >> StatementForLoop(p, sAcc, i, bIsFixedSize, nFixedSize, sInnerStatement) ::= << -for( = 0; ret && \<

nCount; ++) +for( = 0; ret && \<

nCount; ++) { } @@ -210,7 +206,7 @@ for( = 0; ret && \<

nCount< Print_AlphabetCheckFunc(sFuncName, arrsAlphaConBody) ::= << -flag (const char* str) +flag (const char* str) { flag ret=TRUE; int i=0; @@ -225,7 +221,7 @@ flag (const char* str) -SingleValContraint(p, v) ::= "(

== )" +SingleValConstraint(p, v) ::= "(

== )" @@ -233,11 +229,11 @@ SingleValContraint(p, v) ::= "(

== )" stringContainsChar(sStrVal, p) ::= "strchr(,

)" -RangeContraint(p, v1, v2, bMin, bMax) ::= "( \<=

&&

\<= )" +RangeConstraint(p, v1, v2, bMin, bMax) ::= "( \<=

&&

\<= )" -RangeContraint_val_MAX(p, v, bMin) ::= "(

>= )" +RangeConstraint_val_MAX(p, v, bMin) ::= "(

>= )" -RangeContraint_MIN_val(p, v, bMax) ::= "(

\<= )" +RangeConstraint_MIN_val(p, v, bMax) ::= "(

\<= )" AND_Constraint(sCon1, sCon2) ::= "( && )" @@ -296,7 +292,7 @@ Sequence_optional_child_always_present_or_absent_expr(p, sAcc, sChName, sPresOr /* CHOICE start*/ -Choice_OptionalChild(p, pLocal, sAcc, sChPresent, sInnerStatement) ::= << +Choice_OptionalChild(p, sPLocal, sAcc, sChPresent, sInnerStatement) ::= << if (

kind == ) { } @@ -341,7 +337,7 @@ ret = ; -for( = 0; ret && \<

nCount; ++) +for( = 0; ret && \<

nCount; ++) { } @@ -350,7 +346,7 @@ for( = 0; ret && \<

nCount< >> sequenceOf2(p,sAcc, i, bIsFixedSize, nFixedSize, sInnerStatement) ::= << -for( = 0; ret && \<

nCount; ++) +for( = 0; ret && \<

nCount; ++) { } diff --git a/StgC/test_cases_c.stg b/StgC/test_cases_c.stg index c3734ba65..bdffc7d9a 100644 --- a/StgC/test_cases_c.stg +++ b/StgC/test_cases_c.stg @@ -242,13 +242,13 @@ PrintSuite_call_codec_generate_dat_file(sModName, sTasName, sAmber, sEnc, sStrea result = _Encode(tmp, &bitStrm, &errCode, TRUE); fp = fopen("asn1scc_.dat","wb"); - if (fp==NULL) + if (fp==NULL) { printf("fopen failed !!!\n"); return 2; } - + fwrite(encBuff,1,(size_t)Stream_GetLength(&bitStrm),fp); fclose(fp); }; @@ -435,7 +435,7 @@ extern "C" { >> - + printTestCaseFileBody(sThisFile, arrsIncludedModules, arrsTestFunctionBodies) ::= << /* Code automatically generated by asn1scc tool (stg macro : printTestCaseFileBody) */ diff --git a/StgC/uper_c.stg b/StgC/uper_c.stg index 84078e5d3..6d86b7fdb 100644 --- a/StgC/uper_c.stg +++ b/StgC/uper_c.stg @@ -28,13 +28,13 @@ EmitTypeAssignment_def_err_code(sErrCode, nErrValue) ::= << EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInPER, nMaxBitsInPER, soSparkAnnotations, bReqBytesForEncodingIsZero) ::= << -#define _REQUIRED_BYTES_FOR_ENCODING +#define _REQUIRED_BYTES_FOR_ENCODING #define _REQUIRED_BITS_FOR_ENCODING flag (const , BitStream* pBitStrm, int* pErrCode, flag bCheckConstraints); >> -EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << flag (const , BitStream* pBitStrm, int* pErrCode, flag bCheckConstraints) { flag ret = TRUE; @@ -63,7 +63,7 @@ flag (const , BitStream* pBitStrm, in - + return ret; } >> @@ -73,7 +73,7 @@ EmitTypeAssignment_def_decode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrc flag ( , BitStream* pBitStrm, int* pErrCode); >> -EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << flag ( , BitStream* pBitStrm, int* pErrCode) { flag ret = TRUE; @@ -107,12 +107,12 @@ BitStream_AppendByte0(pBitStrm,

arr[]); >> InternalItem_oct_str_decode(p, sAcc, i, sErrCode) ::=<< -ret = BitStream_ReadByte(pBitStrm, &(

arr[])); +ret = BitStream_ReadByte(pBitStrm, &(

arr[])); *pErrCode = ret ? 0 : ; >> PrintAlphabet2(arrnCharSet) /*nogen*/::= << -static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; +static byte allowedCharSet[] = {}; wrap, anchor, separator=",">}; >> InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< @@ -159,15 +159,15 @@ ret = BitStream_DecodeConstraintPosWholeNumber(pBitStrm,

, , /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" -IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << +IntUnconstrained_encode(p, sErrCode, bCoverageIgnore) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" +IntUnconstrained_decode(p, sErrCode, bCoverageIgnore) ::= << ret = BitStream_DecodeUnConstraintWholeNumber(pBitStrm,

); /*COVERAGE_IGNORE*/ *pErrCode = ret ? 0 : ; /*COVERAGE_IGNORE*/ >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" -IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << +IntUnconstrainedMax_encode(p, nMax, soCheckExp, sErrCode) ::= "BitStream_EncodeUnConstraintWholeNumber(pBitStrm,

);" +IntUnconstrainedMax_decode(p, nMax, soCheckExp, sErrCode) ::= << ret = BitStream_DecodeUnConstraintWholeNumber(pBitStrm,

); *pErrCode = (ret &&()) ? 0 : ; >> @@ -196,9 +196,9 @@ IntNoneRequired_encode(p, nConst, sErrCode) ::=<< (void)pBitStrm; >> IntNoneRequired_decode(p, nConst, sErrCode) ::= << -

=; +

=; (void)pBitStrm; -ret = TRUE; +ret = TRUE; *pErrCode = 0; >> @@ -217,10 +217,10 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< ret = BitStream_ReadBit(pBitStrm, &extBit); *pErrCode = ret ? 0 : ; if (ret) { - if (extBit==0) { /* ext bit is zero ==> value is expecteted with root range*/ + if (extBit==0) { /* ext bit is zero ==> value is expected with root range*/ } else { - + } } } @@ -233,9 +233,9 @@ if () { BitStream_AppendBitZero(pBitStrm); /* write extension bit, value within root range, so ext bit is zero */ } else { - /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ + /* value is not within root range, so ext bit is one and value is encoded as unconstrained */ BitStream_AppendBitOne(pBitStrm); - + }; >> @@ -281,19 +281,19 @@ ret = _uper_decode(pBitStrm,

); Enumerated_item_encode(p, sName, nIndex, nLastItemIndex) ::= << -case : +case : BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, ); break; >> Enumerated_item_decode(p, sName, nIndex, nLastItemIndex) ::= << -case : +case :

= ; break; >> Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -switch(

) +switch(

) { default: /*COVERAGE_IGNORE*/ @@ -308,7 +308,7 @@ Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, n ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &enumIndex, 0, ); *pErrCode = ret ? 0 : ; if (ret) { - switch(enumIndex) + switch(enumIndex) { default: /*COVERAGE_IGNORE*/ @@ -340,7 +340,7 @@ case : >> choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -switch(

kind) +switch(

kind) { }; separator="\n"> default: /*COVERAGE_IGNORE*/ @@ -353,7 +353,7 @@ choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &, 0, ); *pErrCode = ret ? 0 : ; if (ret) { - switch() + switch() { }; separator="\n"> default: /*COVERAGE_IGNORE*/ @@ -368,17 +368,17 @@ if (ret) { /* SEQUENCE START */ -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= "BitStream_AppendBit(pBitStrm,

exist.);" -sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << +sequence_presence_bit_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= "BitStream_AppendBit(pBitStrm,

exist.);" +sequence_presence_bit_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << ret = BitStream_ReadBit(pBitStrm, &presenceBit);

exist. = presenceBit == 0 ? 0 : 1; *pErrCode = ret ? 0 : ; >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= "BitStream_AppendBit(pBitStrm, );" +sequence_presence_bit_fix_encode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= "BitStream_AppendBit(pBitStrm, );" -sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << - +sequence_presence_bit_fix_decode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= << + >> @@ -393,14 +393,14 @@ sequence_mandatory_child_decode(sChName, sChildContent) ::= << >> -sequence_optional_child_encode(p, sAcc, sChName, sChildContent) ::= << +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << /*Encode */ if (

exist.) { } >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent) ::= << +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << /*Decode */ if (

exist.) { @@ -408,12 +408,12 @@ if (

exist.) { >> -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << - +sequence_default_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << + >> -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << +sequence_default_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << /*Decode */ if (

exist.) { @@ -422,13 +422,13 @@ if (

exist.) { } >> - +sequence_build(p, sTypeDefName, arrsChildren) ::= "" /* SEQUENCE END */ -loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< -for(=0; ( \< (int)) && ret; ++) +loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< +for(=0; ( \< (int)) && ret; ++) { } @@ -437,16 +437,16 @@ for(=0; ( \< (int)) && ret; ++) /* IA5String & Numeric String */ -str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << >> -str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= <<

[] = 0x0; >> -str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << nStringLength = strlen(

); /*ret = nStringLength >= && nStringLength \<= ;*/ BitStream_EncodeConstraintWholeNumber(pBitStrm, nStringLength, , ); @@ -454,7 +454,7 @@ BitStream_EncodeConstraintWholeNumber(pBitStrm, nStringLength, , > -str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nStringLength, , );

[nStringLength] = 0x0; @@ -463,20 +463,20 @@ ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nStringLength, /* SEQUENCE OF & OCTET STRING*/ -seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << >> -seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << >> -seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << +seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ); >> -seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << +seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nCount, , ); *pErrCode = ret ? 0 : ;

nCount = (long)nCount; @@ -485,20 +485,20 @@ ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nCount, , arr, ); >> -octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << +octet_FixedSize_decode(sTypeDefName, p, sAcc, nFixedSize) ::= << ret = BitStream_DecodeOctetString_no_length(pBitStrm,

arr, ); >> -octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ); ret = BitStream_EncodeOctetString_no_length(pBitStrm,

arr,

nCount); >> -octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nCount, , ); *pErrCode = ret ? 0 : ;

nCount = (long)nCount; @@ -511,22 +511,22 @@ ret = BitStream_DecodeOctetString_no_length(pBitStrm,

arr,

nCo /* BIT STRING*/ -bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= "BitStream_AppendBits(pBitStrm,

arr, );" -bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << +bitString_FixSize_encode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= "BitStream_AppendBits(pBitStrm,

arr, );" +bitString_FixSize_decode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= << ret = BitStream_ReadBits(pBitStrm,

arr, ); *pErrCode = ret ? 0 : ; >> -bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +bitString_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << BitStream_EncodeConstraintWholeNumber(pBitStrm,

nCount, , ); - + >> -bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +bitString_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &nCount, , ); if (ret) {

nCount = (long)nCount; - + } >> @@ -536,7 +536,7 @@ FixedSize_Fragmentation_sqf_64K_encode(p, sAcc,sCurOffset, sCurBlockSize, sBlock = 0x10000; = 0; for( = 0; \< ; ++) { - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF); + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF); BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); @@ -554,7 +554,7 @@ for( = 0; \< ; ++) { FixedSize_Fragmentation_sqf_small_block_encode(p, sAcc,sInternalItem, nBlockSize, sBlockId, sCurOffset, sCurBlockSize, sBLI, sRemainingItemsVar, bIsBitStringType, sErrCodeName) ::=<< //encode Block = ; -BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF); +BitStream_EncodeConstraintWholeNumber(pBitStrm, , 0, 0xFF); BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); @@ -599,29 +599,29 @@ Fragmentation_sqf_encode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0; = 0; = 0; -while ( >= 0x4000 && \< (asn1SccSint)strlen(

)

nCount) +while ( >= 0x4000 && \< (asn1SccSint)strlen(

)

nCount) { if ( >= 0x10000) { = 0x10000; - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF); + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC4, 0, 0xFF); } else if ( >= 0xC000) { = 0xC000; - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC3, 0, 0xFF); + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC3, 0, 0xFF); } else if ( >= 0x8000) { = 0x8000; - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC2, 0, 0xFF); + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC2, 0, 0xFF); } - else + else { = 0x4000; - BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF); + BitStream_EncodeConstraintWholeNumber(pBitStrm, 0xC1, 0, 0xFF); } - + BitStream_AppendBits(pBitStrm, &

arr[/8], (int)); @@ -658,7 +658,7 @@ FixedSize_Fragmentation_sqf_64K_decode(p, sAcc,sCurOffset, sCurBlockSize, sBlock //we expect to decode Blocks and each block must contain 64K elements. Each block must begin with the byte 0xC4 = 0x10000; = 0; -*pErrCode = ; +*pErrCode = ; for( = 0; ret && \< ; ++) { ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &, 0, 0xFF); ret = ret && ( == 0xC4); @@ -744,7 +744,7 @@ Fragmentation_sqf_decode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz ret = BitStream_DecodeConstraintWholeNumber(pBitStrm, &, 0, 0xFF); *pErrCode = ret ? 0 : ; if (ret) { - while(ret && ( & 0xC0)==0xC0) + while(ret && ( & 0xC0)==0xC0) { if ( == 0xC4) = 0x10000; @@ -773,7 +773,7 @@ if (ret) { } - + if (ret) { += (long); += ; @@ -782,7 +782,7 @@ if (ret) { } } if (ret) { - if ( ( & 0x80)>0) + if ( ( & 0x80)>0) { asn1SccSint len2; \<\<= 8; @@ -857,7 +857,7 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, nBit octet_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, nBits, nMinSize, nMaxSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; @@ -888,7 +888,7 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBi bit_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, nBits, nMinSize, nMaxSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; @@ -908,6 +908,8 @@ sparkAnnotations_encode(sTypeDefName) ::= << sparkAnnotations_decode(sTypeDefName) ::= << >> +Null_declare(p) ::= "" + decode_nullType(p) ::= << /*no encoding/decoding is required*/ >> diff --git a/StgC/variables_c.stg b/StgC/variables_c.stg index 583f35568..6b782a40f 100644 --- a/StgC/variables_c.stg +++ b/StgC/variables_c.stg @@ -57,16 +57,16 @@ PrintBitStringValue(td/*:FE_SizeableTypeDefinition*/,bIsFixedSize, arrsBits, nCo >> -PrintBitOrOctetStringValueAsCompoundLitteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << +PrintBitOrOctetStringValueAsCompoundLiteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << (){.nCount = , .arr = {}; separator=", ">}} >> -PrintOctetArrayAsCompoundLitteral(arruBytes) ::= << +PrintOctetArrayAsCompoundLiteral(arruBytes) ::= << (const byte[]){}; wrap, anchor, separator=", ">} >> -PrintBitArrayAsCompoundLitteral(arruBits) ::= << +PrintBitArrayAsCompoundLiteral(arruBits) ::= << SYNTAX ERROR >> @@ -192,9 +192,9 @@ PrintSequenceOfValue(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, nLength, ar { .nCount = , - .arr = + .arr = { - }; separator=",\n"> + }; separator=",\n"> } } >> diff --git a/StgC/xer_c.stg b/StgC/xer_c.stg index 55b9f54e6..b0b58fc25 100644 --- a/StgC/xer_c.stg +++ b/StgC/xer_c.stg @@ -9,14 +9,14 @@ const int = ; EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInXER, soSparkAnnotations) ::= << -#define _REQUIRED_BYTES_FOR_XER_ENCODING +#define _REQUIRED_BYTES_FOR_XER_ENCODING flag (const , ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints); flag _aux(const , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints); >> -EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp) ::= << +EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp) ::= << flag _aux(const , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints) { flag ret = TRUE; @@ -37,7 +37,7 @@ flag _aux(const , const char* xmlTag, - + return ret; } @@ -53,7 +53,7 @@ flag ( , ByteStream* pByteStrm, int* p flag _aux( , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode); >> -EmitTypeAssignment_decode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp) ::= << +EmitTypeAssignment_decode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp) ::= << flag _aux( , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode) { flag ret = TRUE; @@ -180,10 +180,10 @@ case : >> Enumerated_encode(p, sTag, nLevel, arrsItems, soCheckExp, sErrCode) ::= << -switch(

) +switch(

) { - default: + default: *pErrCode = ; /*COVERAGE_IGNORE*/ ret = FALSE; /*COVERAGE_IGNORE*/ } @@ -243,7 +243,7 @@ SequenceOf_encode(p, sAcc, sTag, nLevel, sI, nSizeMax, sChildBody, bFixedSize, s ret = Xer_EncodeComplexElementStart(pByteStrm, , NULL, pErrCode, ); *pErrCode = ret ? 0 : ; if (ret) { - for(=0;(( \<

nCount) && ret);++) + for(=0;(( \<

nCount) && ret);++) { } @@ -385,7 +385,7 @@ CHOICE_child_decode(p, sAcc, sChID, sChildBody, bFirst, sChildTag, sChildName, s CHOICE_no_tag_encode(p, sAcc, arrsChildren, sErrCode) ::= << -switch(

kind) +switch(

kind) { default: @@ -399,7 +399,7 @@ CHOICE_no_tag_decode(p, sAcc, arrsChildren, sErrCode) ::=<< char nextTag[256]; ret = Xer_LA_NextElementTag(pByteStrm, nextTag); if (ret) { - + else { ret = FALSE; *pErrCode = ; diff --git a/StgScala/LangGeneric_scala.fs b/StgScala/LangGeneric_scala.fs index de4d916f7..332b9fe48 100644 --- a/StgScala/LangGeneric_scala.fs +++ b/StgScala/LangGeneric_scala.fs @@ -6,19 +6,19 @@ open FsUtils open Language open System.IO -let getAccess_scala (fpt:FuncParamType) = - match fpt with - | VALUE x -> "." - | POINTER x -> "." - | FIXARRAY x -> "" +let getAccess2_scala (acc: Accessor) = + match acc with + | ValueAccess (sel, _, _) -> $".{sel}" + | PointerAccess (sel, _, _) -> $".{sel}" + | ArrayAccess (ix, _) -> $"({ix})" #if false -let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefintionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErroCode) (p:CallerScope) = - let ii = id.SeqeuenceOfLevel + 1; - let i = sprintf "i%d" (id.SeqeuenceOfLevel + 1) +let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Codec) (id : ReferenceToType) (typeDefinition:TypeDefinitionOrReference) isFixedSize uperMaxSizeInBits minSize maxSize (errCode:ErrorCode) (p:CallerScope) = + let ii = id.SequenceOfLevel + 1; + let i = sprintf "i%d" (id.SequenceOfLevel + 1) let nSizeInBits = GetNumberOfBitsForNonNegativeInteger ( (maxSize - minSize)) - let funcBodyContent, localVariables = + let funcBodyContent, localVariables = let nStringLength = match isFixedSize, codec with | true , _ -> [] @@ -28,13 +28,13 @@ let createBitStringFunction_funcBody_c handleFragmentation (codec:CommonTypes.Co match minSize with | _ when maxSize < 65536I && isFixedSize -> uper_c.bitString_FixSize p.arg.p (getAccess_c p.arg) (minSize) errCode.errCodeName codec , nStringLength | _ when maxSize < 65536I && (not isFixedSize) -> uper_c.bitString_VarSize p.arg.p (getAccess_c p.arg) (minSize) (maxSize) errCode.errCodeName nSizeInBits codec, nStringLength - | _ -> + | _ -> handleFragmentation p codec errCode ii (uperMaxSizeInBits) minSize maxSize "" 1I true false - {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} + {UPERFuncBodyResult.funcBody = funcBodyContent; errCodes = [errCode]; localVariables = localVariables; bValIsUnReferenced=false; bBsIsUnReferenced=false} #endif let srcDirName = Path.Combine("src", "main", "scala", "asn1src") -let asn1rtlDirName = Path.Combine("src", "main", "scala", "asn1scala") +let asn1rtlDirName = Path.Combine("src", "main", "scala", "asn1scala") type LangGeneric_scala() = inherit ILangGeneric() @@ -53,53 +53,32 @@ type LangGeneric_scala() = | Asn1AcnAst.ASN1SCC_UInt64 _ -> sprintf "%sL" (i.ToString()) | Asn1AcnAst.ASN1SCC_UInt _ -> sprintf "%sL" (i.ToString()) - override _.doubleValueToString (v:double) = + override _.doubleValueToString (v:double) = v.ToString(FsUtils.doubleParseString, System.Globalization.NumberFormatInfo.InvariantInfo) - override _.initializeString stringSize = sprintf "Array.fill(%d+1)(0x0)" stringSize - + override _.initializeString stringSize = sprintf "Array.fill(%d.toInt+1)(0x0.toByte)" stringSize + override _.supportsInitExpressions = false - override _.getPointer (fpt:FuncParamType) = - match fpt with - |VALUE x -> sprintf "%s" x - |POINTER x -> sprintf "%s" x - |FIXARRAY x -> sprintf "%s" x - - override this.getValue (fpt:FuncParamType) = - match fpt with - | VALUE x -> x - | POINTER x -> sprintf "%s" x - | FIXARRAY x -> sprintf "%s" x - - override this.getAccess (fpt:FuncParamType) = getAccess_scala fpt - - override this.ArrayAccess idx = "(" + idx + ")" - - override this.getPtrPrefix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "Ref[" - | POINTER x -> "Ref[" - | FIXARRAY x -> "Ref[" - - override this.getPtrSuffix (fpt: FuncParamType) = - match fpt with - | VALUE x -> "]" - | POINTER x -> "]" - | FIXARRAY x -> "]" - - override this.getStar (fpt:FuncParamType) = - match fpt with - | VALUE x -> "" - | POINTER x -> "Ref[]" - | FIXARRAY x -> "" - - override this.getArrayItem (fpt:FuncParamType) (idx:string) (childTypeIsString: bool) = - let newPath = sprintf "%s%sarr(%s)" fpt.p (this.getAccess fpt) idx - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - - override this.getNamedItemBackendName (defOrRef:TypeDefintionOrReference option) (nm:Asn1AcnAst.NamedItem) = - let itemname = + override this.getPointer (sel: Selection) = sel.joined this + + override this.getValue (sel: Selection) = sel.joined this + + override this.getAccess (sel: Selection) = "." + + override this.getAccess2 (acc: Accessor) = getAccess2_scala acc + + override this.getPtrPrefix _ = "" + + override this.getPtrSuffix _ = "" + + override this.getStar _ = "" + + override this.getArrayItem (sel: Selection) (idx:string) (childTypeIsString: bool) = + (sel.appendSelection "arr" FixArray false).append (ArrayAccess (idx, if childTypeIsString then FixArray else Value)) + + override this.getNamedItemBackendName (defOrRef:TypeDefinitionOrReference option) (nm:Asn1AcnAst.NamedItem) = + let itemname = match defOrRef with | Some (TypeDefinition td) -> td.typedefName + "." + ToC nm.scala_name | Some (ReferenceToExistingDefinition rted) -> rted.typedefName + "." + ToC nm.scala_name @@ -110,9 +89,9 @@ type LangGeneric_scala() = override this.setNamedItemBackendName0 (nm:Asn1Ast.NamedItem) (newValue:string) : Asn1Ast.NamedItem = {nm with scala_name = newValue} - override this.getNamedItemBackendName2 (_:string) (_:string) (nm:Asn1AcnAst.NamedItem) = + override this.getNamedItemBackendName2 (_:string) (_:string) (nm:Asn1AcnAst.NamedItem) = ToC nm.scala_name - + override this.decodeEmptySeq _ = None override this.decode_nullType _ = None @@ -121,13 +100,13 @@ type LangGeneric_scala() = override this.typeDef (ptd:Map) = ptd.[Scala] override this.getTypeDefinition (td:Map) = td.[Scala] - override this.getEnmTypeDefintion (td:Map) = td.[Scala] + override this.getEnumTypeDefinition (td:Map) = td.[Scala] override this.getStrTypeDefinition (td:Map) = td.[Scala] override this.getChoiceTypeDefinition (td:Map) = td.[Scala] override this.getSequenceTypeDefinition (td:Map) = td.[Scala] override this.getSizeableTypeDefinition (td:Map) = td.[Scala] override this.getAsn1ChildBackendName (ch:Asn1Child) = ch._scala_name - override this.getAsn1ChChildBackendName (ch:ChChildInfo) = ch._scala_name + override this.getAsn1ChChildBackendName (ch:ChChildInfo) = ch._scala_name override _.getChildInfoName (ch:Asn1Ast.ChildInfo) = ch.scala_name override _.setChildInfoName (ch:Asn1Ast.ChildInfo) (newValue:string) = {ch with scala_name = newValue} override this.getAsn1ChildBackendName0 (ch:Asn1AcnAst.Asn1Child) = ch._scala_name @@ -140,29 +119,30 @@ type LangGeneric_scala() = let xerRtl = match encodings |> Seq.exists(fun e -> e = XER) with true -> ["asn1crt_encoding_xer"] | false -> [] encRtl@uperRtl@acnRtl@xerRtl - override this.getEmptySequenceInitExpression () = "{}" + override this.getEmptySequenceInitExpression sTypeDefName = $"{sTypeDefName}()" override this.callFuncWithNoArgs () = "()" override this.rtlModuleName = "" override this.AssignOperator = "=" override this.TrueLiteral = "true" override this.FalseLiteral = "false" - override this.emtyStatement = "" + override this.emptyStatement = "" override this.bitStreamName = "BitStream" - override this.unaryNotOperator = "!" - override this.modOp = "%" - override this.eqOp = "==" - override this.neqOp = "!=" - override this.andOp = "&&" - override this.orOp = "||" - override this.initMetod = InitMethod.Procedure - + override this.unaryNotOperator = "!" + override this.modOp = "%" + override this.eqOp = "==" + override this.neqOp = "!=" + override this.andOp = "&&" + override this.orOp = "||" + override this.initMethod = InitMethod.Procedure + override _.decodingKind = Copy + override _.usesWrappedOptional = true override this.castExpression (sExp:string) (sCastType:string) = sprintf "(%s)(%s)" sCastType sExp override this.createSingleLineComment (sText:string) = sprintf "/*%s*/" sText - + override _.SpecNameSuffix = "Def" - override _.SpecExtention = "scala" - override _.BodyExtention = "scala" - override _.Keywords = CommonTypes.scala_keyworkds + override _.SpecExtension = "scala" + override _.BodyExtension = "scala" + override _.Keywords = CommonTypes.scala_keywords override _.getValueAssignmentName (vas: ValueAssignment) = vas.scala_name @@ -171,124 +151,63 @@ type LangGeneric_scala() = override this.allowsSrcFilesWithNoFunctions = true override this.requiresValueAssignmentsInSrcFile = true override this.supportsStaticVerification = false - - override this.getSeqChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) (removeDots: bool) = - let newPath = sprintf "%s%s%s" fpt.p (this.getAccess fpt) childName - let newPath = if removeDots then (ToC newPath) else newPath - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - - override this.getChChild (fpt:FuncParamType) (childName:string) (childTypeIsString: bool) : FuncParamType = - //let newPath = sprintf "e" // always use e for pattern matching - //let newPath = sprintf "%s%s%s" fpt.p (this.getAccess fpt) childName - //let newPath = sprintf "%s.%s" fpt.p childName - let newPath = sprintf "%s" childName - if childTypeIsString then (FIXARRAY newPath) else (VALUE newPath) - - override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = - let prefix = ToC (id.AcnAbsPath.Tail.StrJoin("_").Replace("#","elem")) - match typeIdsSet.TryFind prefix with - | None -> prefix + "_NONE" - | Some a when a = 1 -> prefix + "_NONE" - | Some a -> ToC (id.AcnAbsPath.StrJoin("_").Replace("#","elem")) + "_NONE" - - override this.presentWhenName (defOrRef:TypeDefintionOrReference option) (ch:ChChildInfo) : string = - let parentName = + + override this.getSeqChild (sel: Selection) (childName:string) (childTypeIsString: bool) (childIsOptional: bool) = + sel.appendSelection childName (if childTypeIsString then FixArray else Value) childIsOptional + + override this.getChChild (sel: Selection) (childName:string) (childTypeIsString: bool) : Selection = + Selection.emptyPath childName (if childTypeIsString then FixArray else Value) + + override this.choiceIDForNone (typeIdsSet:Map) (id:ReferenceToType) = "" + + override this.presentWhenName (defOrRef:TypeDefinitionOrReference option) (ch:ChChildInfo) : string = + let parentName = match defOrRef with | Some a -> match a with | ReferenceToExistingDefinition b -> b.typedefName + "." | TypeDefinition c -> c.typedefName + "." | None -> "" parentName + (ToC ch._present_when_name_private) + "_PRESENT" - + override this.getParamTypeSuffix (t:Asn1AcnAst.Asn1Type) (suf:string) (c:Codec) : CallerScope = - match c with - | Encode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Real _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.IA5String _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("pVal" + suf) } - | Asn1AcnAst.NumericString _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("pVal" + suf) } - | Asn1AcnAst.OctetString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.NullType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.BitString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Boolean _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Enumerated _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.SequenceOf _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Sequence _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Choice _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ObjectIdentifier _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.TimeType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ReferenceType r -> this.getParamTypeSuffix r.resolvedType suf c - | Decode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Real _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.IA5String _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("pVal" + suf) } - | Asn1AcnAst.NumericString _ -> {CallerScope.modName = t.id.ModName; arg= FIXARRAY ("pVal" + suf) } - | Asn1AcnAst.OctetString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.NullType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.BitString _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Boolean _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Enumerated _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.SequenceOf _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Sequence _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.Choice _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ObjectIdentifier _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.TimeType _ -> {CallerScope.modName = t.id.ModName; arg= POINTER ("pVal" + suf) } - | Asn1AcnAst.ReferenceType r -> this.getParamTypeSuffix r.resolvedType suf c - - override this.getParamValue (t:Asn1AcnAst.Asn1Type) (p:FuncParamType) (c:Codec) = - match c with - | Encode -> - match t.Kind with - | Asn1AcnAst.Integer _ -> this.getPointer p - | Asn1AcnAst.Real _ -> this.getPointer p - | Asn1AcnAst.IA5String _ -> this.getValue p //FIXARRAY "val" - | Asn1AcnAst.NumericString _-> this.getValue p// FIXARRAY "val" - | Asn1AcnAst.OctetString _ -> this.getPointer p - | Asn1AcnAst.NullType _ -> this.getPointer p - | Asn1AcnAst.BitString _ -> this.getPointer p - | Asn1AcnAst.Boolean _ -> this.getPointer p - | Asn1AcnAst.Enumerated _ -> this.getPointer p - | Asn1AcnAst.SequenceOf _ -> this.getPointer p - | Asn1AcnAst.Sequence _ -> this.getPointer p - | Asn1AcnAst.Choice _ -> this.getPointer p - | Asn1AcnAst.ObjectIdentifier _ -> this.getPointer p - | Asn1AcnAst.TimeType _ -> this.getPointer p - | Asn1AcnAst.ReferenceType r -> this.getParamValue r.resolvedType p c - | Decode -> - match t.Kind with - | Asn1AcnAst.IA5String _ -> this.getValue p //FIXARRAY "val" - | Asn1AcnAst.NumericString _ -> this.getValue p// FIXARRAY "val" - | Asn1AcnAst.ReferenceType r -> this.getParamValue r.resolvedType p c - | _ -> this.getPointer p + let rec getRecvType (kind: Asn1AcnAst.Asn1TypeKind) = + match kind with + | Asn1AcnAst.NumericString _ | Asn1AcnAst.IA5String _ -> FixArray // TODO: For Ada, this is Value no matter what? + | Asn1AcnAst.ReferenceType r -> getRecvType r.resolvedType.Kind + | _ -> Pointer + let recvId = "pVal" + suf + {CallerScope.modName = t.id.ModName; arg = Selection.emptyPath recvId (getRecvType t.Kind) } + + override this.getParamValue (t:Asn1AcnAst.Asn1Type) (p:Selection) (c:Codec) = + p.joined this + override this.getLocalVariableDeclaration (lv:LocalVariable) : string = match lv with | SequenceOfIndex (i,None) -> sprintf "var i%d: Int = 0" i - | SequenceOfIndex (i,Some iv) -> sprintf "var i%d: Int = %d" i iv + | SequenceOfIndex (i,Some iv) -> sprintf "var i%d: Int = %s" i iv | IntegerLocalVariable (name,None) -> sprintf "var %s: Int = 0" name - | IntegerLocalVariable (name,Some iv) -> sprintf "var %s: Int = %d" name iv + | IntegerLocalVariable (name,Some iv) -> sprintf "var %s: Int = %s" name iv | Asn1SIntLocalVariable (name,None) -> sprintf "var %s: Int = 0" name - | Asn1SIntLocalVariable (name,Some iv) -> sprintf "var %s: Int = %d" name iv + | Asn1SIntLocalVariable (name,Some iv) -> sprintf "var %s: Int = %s" name iv | Asn1UIntLocalVariable (name,None) -> sprintf "var %s: UInt = 0" name - | Asn1UIntLocalVariable (name,Some iv) -> sprintf "var %s: UInt = %d" name iv + | Asn1UIntLocalVariable (name,Some iv) -> sprintf "var %s: UInt = %s" name iv | FlagLocalVariable (name,None) -> sprintf "var %s: Boolean = false" name - | FlagLocalVariable (name,Some iv) -> sprintf "var %s: Boolean = %d" name iv + | FlagLocalVariable (name,Some iv) -> sprintf "var %s: Boolean = %s" name iv | BooleanLocalVariable (name,None) -> sprintf "var %s: Boolean = false" name - | BooleanLocalVariable (name,Some iv) -> sprintf "var %s: Boolean = %s" name (if iv then "true" else "false") - | AcnInsertedChild(name, vartype, initVal) -> sprintf "var %s: %s = %s" name vartype (if initVal = "" then "null" else initVal) - + | BooleanLocalVariable (name,Some iv) -> sprintf "var %s: Boolean = %s" name iv + | AcnInsertedChild(name, vartype, initVal) -> + sprintf "var %s: %s = %s" name vartype initVal + | GenericLocalVariable lv -> sprintf "var %s%s: %s%s = %s" (if lv.isStatic then "static " else "") lv.name lv.varType (if lv.arrSize.IsNone then "" else "["+lv.arrSize.Value+"]") (if lv.initExp.IsNone then "" else lv.initExp.Value) - - override this.getLongTypedefName (tdr:TypeDefintionOrReference) : string = + + override this.getLongTypedefName (tdr:TypeDefinitionOrReference) : string = match tdr with | TypeDefinition td -> td.typedefName | ReferenceToExistingDefinition ref -> ref.typedefName - - //override this.getEnmLongTypedefName (td:FE_EnumeratedTypeDefinition) _ = td; + override this.toHex n = sprintf "0x%x" n @@ -302,17 +221,17 @@ type LangGeneric_scala() = requires_charIndex = false requires_IA5String_i = true count_var = Asn1SIntLocalVariable ("nCount", None) - requires_presenceBit = true + requires_presenceBit = false catd = false //createBitStringFunction = createBitStringFunction_funcBody_c seqof_lv = - (fun id minSize maxSize -> [SequenceOfIndex (id.SeqeuenceOfLevel + 1, None)]) + (fun id minSize maxSize -> [SequenceOfIndex (id.SequenceOfLevel + 1, None)]) } - override this.acn = + override this.acn = { Acn_parts.null_valIsUnReferenced = true checkBitPatternPresentResult = true - getAcnDepSizeDeterminantLocVars = + getAcnDepSizeDeterminantLocVars = fun sReqBytesForUperEncoding -> [ GenericLocalVariable {GenericLocalVariable.name = "arr"; varType = "byte"; arrSize = Some sReqBytesForUperEncoding; isStatic = true; initExp = None} @@ -321,7 +240,7 @@ type LangGeneric_scala() = choice_handle_always_absent_child = false choice_requires_tmp_decoding = false } - override this.init = + override this.init = { Initialize_parts.zeroIA5String_localVars = fun _ -> [] choiceComponentTempInit = false @@ -339,11 +258,11 @@ type LangGeneric_scala() = override this.CreateAuxFiles (r:AstRoot) (di:DirInfo) (arrsSrcTstFiles : string list, arrsHdrTstFiles:string list) = let CreateScalaMainFile (r:AstRoot) outDir = - // Main file for test cass + // Main file for test case let printMain = test_cases_scala.PrintMain //match l with C -> test_cases_c.PrintMain | Ada -> test_cases_c.PrintMain let content = printMain "testsuite" let outFileName = Path.Combine(outDir, "mainprogram.scala") - File.WriteAllText(outFileName, content.Replace("\r","")) + File.WriteAllText(outFileName, content.Replace("\r","")) CreateScalaMainFile r di.srcDir @@ -355,7 +274,7 @@ type LangGeneric_scala() = srcDir=Path.Combine(rootDir, srcDirName); asn1rtlDir=Path.Combine(rootDir, asn1rtlDirName); boardsDir=rootDir - } + } - override this.getTopLevelDirs (target:Targets option) = + override this.getTopLevelDirs (target:Targets option) = [asn1rtlDirName; srcDirName; "lib"] diff --git a/StgScala/acn_scala.stg b/StgScala/acn_scala.stg index 2f25a444d..7d80008c0 100644 --- a/StgScala/acn_scala.stg +++ b/StgScala/acn_scala.stg @@ -5,7 +5,7 @@ getStringSize(p) ::= "

.indexOf(0x00)" getSizeableSize(p, sAcc) ::= "

nCount // TODO acn:5" EmitTypeAssignment_def_err_code(sErrCode, nErrValue, soErrorCodeComment) ::= << -@inline @cCode.inline val : Int = /* */ +@inline @cCode.inline val : Int = /* */ >> EmitAcnParameter(sName, sType) ::= " /*TODO acn:11 */" @@ -17,23 +17,20 @@ EmitTypeAssignment_primitive_def_encode(sVarName, sStar, sFuncName, sTypeDefName @inline @cCode.inline val _REQUIRED_BITS_FOR_ACN_ENCODING = >> -EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << def (@annotation.unused : , @annotation.unused codec: ACN, bCheckConstraints: Boolean): Either[ErrorCode, Int] = // acn:21 { - var ret: Either[ErrorCode, Int] = Right(0) - }; separator="\n"> - if bCheckConstraints then - ret = () - if (ret.isRight) { // classical design (scala 2), sContent could be empty - - } + if bCheckConstraints then + () match + case Left(l) => return Left(l) + case Right(_) => + - - ret + Right(0) } >> @@ -41,193 +38,182 @@ EmitTypeAssignment_primitive_def_decode(sVarName, sStar, sFuncName, sTypeDefName >> -EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_primitive_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, arrsAcnPrms, arrsAcnParamNames, bEmptyEncodingSpace, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << def (@annotation.unused codec: ACN): Either[ErrorCode, ] = -{ - var : = () - var ret: Either[ErrorCode, ] = Right() - +{ }; separator="\n"> - if ret.isRight then - ret = Right() - - ret match - case Left(x) => - assert(false) // no left should reach this point - case Right(x) => - (x) match - case Left(l) => - return Left(l) - case _ => + + () match + case Left(l) => Left(l) + case _ => Right() + + Right() - ret } >> A(sErrCode) /*nogen*/ ::= "" - +// TODO MF(soMF) ::= /*nogen*/ << -if (ret.isRight) { -

= _decode(

) -} +

= _decode(

) >> - + loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/ << = 0 -while ret.isRight && \< .asInstanceOf[Int] do +while \< .asInstanceOf[Int] do += 1 >> -alignToNext_encode(sMainBody, sAligmentValue, nAligmentValue) ::= << -codec.alignTo() +alignToNext_encode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +codec.alignTo() >> -alignToNext_decode(sMainBody, sAligmentValue, nAligmentValue) ::= << -codec.alignTo() +alignToNext_decode(sMainBody, sAlignmentValue, nAlignmentValue) ::= << +codec.alignTo() >> PositiveInteger_ConstSize_encode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize(_encode(

)

, )" PositiveInteger_ConstSize_decode(p, sSsuffix, sErrCode, nFixedSize, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize() +val

= codec.dec_Int_PositiveInteger_ConstSize() >> PositiveInteger_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_8(_encode(

)

)" PositiveInteger_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_8() +val

= codec.dec_Int_PositiveInteger_ConstSize_8() >> PositiveInteger_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_16(_encode(

)

)" PositiveInteger_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_16() +val

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_16() >> PositiveInteger_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_32(_encode(

)

)" PositiveInteger_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_32() +val

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_32() >> PositiveInteger_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_big_endian_64(_encode(

)

)" PositiveInteger_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_64() +val

= codec.dec_Int_PositiveInteger_ConstSize_big_endian_64() >> PositiveInteger_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_16(_encode(

)

)" PositiveInteger_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_16() +val

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_16() >> PositiveInteger_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_32(_encode(

)

)" PositiveInteger_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_32() +val

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_32() >> PositiveInteger_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_PositiveInteger_ConstSize_little_endian_64(_encode(

)

)" PositiveInteger_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_64() +val

= codec.dec_Int_PositiveInteger_ConstSize_little_endian_64() >> PositiveInteger_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= "codec.enc_Int_PositiveInteger_VarSize_LengthEmbedded(_encode(

)

)" PositiveInteger_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin) ::= << -

= codec.dec_Int_PositiveInteger_VarSize_LengthEmbedded() +val

= codec.dec_Int_PositiveInteger_VarSize_LengthEmbedded() >> TwosComplement_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize(_encode(

)

, )" TwosComplement_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nFixedSize, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize() +val

= codec.dec_Int_TwosComplement_ConstSize() >> TwosComplement_ConstSize_8_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_8(_encode(

)

)" TwosComplement_ConstSize_8_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_8() +val

= codec.dec_Int_TwosComplement_ConstSize_8() >> TwosComplement_ConstSize_big_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_16(_encode(

)

)" TwosComplement_ConstSize_big_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_big_endian_16() +val

= codec.dec_Int_TwosComplement_ConstSize_big_endian_16() >> TwosComplement_ConstSize_big_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_32(_encode(

)

)" TwosComplement_ConstSize_big_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_big_endian_32() +val

= codec.dec_Int_TwosComplement_ConstSize_big_endian_32() >> TwosComplement_ConstSize_big_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_big_endian_64(_encode(

)

)" TwosComplement_ConstSize_big_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_big_endian_64() +val

= codec.dec_Int_TwosComplement_ConstSize_big_endian_64() >> TwosComplement_ConstSize_little_endian_16_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_16(_encode(

)

)" TwosComplement_ConstSize_little_endian_16_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_little_endian_16() +val

= codec.dec_Int_TwosComplement_ConstSize_little_endian_16() >> TwosComplement_ConstSize_little_endian_32_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_32(_encode(

)

)" TwosComplement_ConstSize_little_endian_32_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_little_endian_32() +val

= codec.dec_Int_TwosComplement_ConstSize_little_endian_32() >> TwosComplement_ConstSize_little_endian_64_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_TwosComplement_ConstSize_little_endian_64(_encode(

)

)" TwosComplement_ConstSize_little_endian_64_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_TwosComplement_ConstSize_little_endian_64() +val

= codec.dec_Int_TwosComplement_ConstSize_little_endian_64() >> TwosComplement_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_TwosComplement_VarSize_LengthEmbedded(_encode(

)

)" TwosComplement_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -

= codec.dec_Int_TwosComplement_VarSize_LengthEmbedded() +val

= codec.dec_Int_TwosComplement_VarSize_LengthEmbedded() >> BCD_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= "codec.enc_Int_BCD_ConstSize(_encode(

)

, )" BCD_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nNibbles) ::= << -

= codec.dec_Int_BCD_ConstSize() +val

= codec.dec_Int_BCD_ConstSize() >> BCD_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_Int_BCD_VarSize_LengthEmbedded(_encode(

)

)" BCD_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -

= codec.dec_Int_BCD_VarSize_LengthEmbedded() +val

= codec.dec_Int_BCD_VarSize_LengthEmbedded() >> BCD_VarSize_NullTerminated_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= "codec.enc_Int_BCD_VarSize_NullTerminated(_encode(

)

)" BCD_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax) ::= << -

= codec.dec_Int_BCD_VarSize_NullTerminated() +val

= codec.dec_Int_BCD_VarSize_NullTerminated() >> ASCII_ConstSize_encode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= "codec.enc_SInt_ASCII_ConstSize(_encode(

)

, ) " ASCII_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -

= codec.dec_SInt_ASCII_ConstSize() +val

= codec.dec_SInt_ASCII_ConstSize() >> ASCII_VarSize_LengthEmbedded_encode(p, sSsuffix, sErrCode, soMF, soMFM) ::= "codec.enc_SInt_ASCII_VarSize_LengthEmbedded(_encode(

)

)" ASCII_VarSize_LengthEmbedded_decode(p, sSsuffix, sErrCode, soMF, soMFM) ::= << -

= codec.dec_SInt_ASCII_VarSize_LengthEmbedded() +val

= codec.dec_SInt_ASCII_VarSize_LengthEmbedded() >> @@ -236,7 +222,7 @@ codec.enc_SInt_ASCII_VarSize_NullTerminated(_encode(

)

> ASCII_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -

= codec.dec_SInt_ASCII_VarSize_NullTerminated((byte[]){}, ) +val

= codec.dec_SInt_ASCII_VarSize_NullTerminated((byte[]){}, ) >> @@ -245,7 +231,7 @@ codec.enc_UInt_ASCII_ConstSize(_encode(

)

, > ASCII_UINT_ConstSize_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, nSizeInBytes) ::= << -

= codec.dec_UInt_ASCII_ConstSize() +val

= codec.dec_UInt_ASCII_ConstSize() >> @@ -254,67 +240,81 @@ codec.enc_UInt_ASCII_VarSize_NullTerminated(_encode(

)

> ASCII_UINT_VarSize_NullTerminated_decode(p, sSsuffix, sErrCode, soMF, soMFM, nUperMin, nUperMax, arruNullBytes) ::= << -

= codec.dec_UInt_ASCII_VarSize_NullTerminated(

, (byte[]){}, ) +val

= codec.dec_UInt_ASCII_VarSize_NullTerminated(

, (byte[]){}, ) >> Real_32_big_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_big_endian(

.toFloat)" -Real_32_big_endian_decode(p, sSuffix, sErrCode) ::= "

= codec.dec_Real_IEEE754_32_big_endian()" +Real_32_big_endian_decode(p, sSuffix, sErrCode) ::= << +val

= codec.dec_Real_IEEE754_32_big_endian() +>> Real_64_big_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_big_endian(

)" -Real_64_big_endian_decode(p, sErrCode) ::= "

= codec.dec_Real_IEEE754_64_big_endian()" +Real_64_big_endian_decode(p, sErrCode) ::= << +val

= codec.dec_Real_IEEE754_64_big_endian() +>> Real_32_little_endian_encode(p, sSuffix, sErrCode) ::= "codec.enc_Real_IEEE754_32_little_endian(

)" -Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= "

= codec.dec_Real_IEEE754_32_little_endian()" +Real_32_little_endian_decode(p, sSuffix, sErrCode) ::= << +val

= codec.dec_Real_IEEE754_32_little_endian() +>> Real_64_little_endian_encode(p, sErrCode) ::= "codec.enc_Real_IEEE754_64_little_endian(

)" -Real_64_little_endian_decode(p, sErrCode) ::= "

= codec.dec_Real_IEEE754_64_little_endian()" +Real_64_little_endian_decode(p, sErrCode) ::= << +val

= codec.dec_Real_IEEE754_64_little_endian() +>> + Boolean_encode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalseValueAsByteArray, arrsBits, sErrCode) ::= << -{ - var true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) - var false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) +locally { + val true_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) + val false_data: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) codec.appendBitsMSBFirst(if

then true_data else false_data, ) } >> Boolean_decode(p, ptr, bEncValIsTrue, nSize, arruTrueValueAsByteArray, arruFalseValueAsByteArray, arrsBits, sErrCode) ::= << -{ +val

= { - var tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) + val tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) + + val tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) + + val x = codec.BitStream_ReadBitPattern(tmp, ) + + !x - var tmp: Array[UByte] = Array(.asInstanceOf[UByte]}; separator=", ">) + x -

= codec.BitStream_ReadBitPattern(tmp, ) -

= !

; } >> +Null_declare(p) ::= "val

: NullType = 0" + Null_pattern_encode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << -{ +locally { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) codec.appendBitsMSBFirst(tmp, ) } >> - Null_pattern_decode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSavePosition) ::= << -ret = Right(codec.BitStream_ReadBitPattern_ignore_value()) +codec.BitStream_ReadBitPattern_ignore_value() +val

: NullType = 0 -{ +locally { val tmp: Array[Byte] = Array(.asInstanceOf[Byte]}; separator=",">) if !codec.BitStream_ReadBitPattern(tmp, ) then - ret = Left() - + return Left() + } - +val

: NullType = 0 - >> @@ -325,15 +325,11 @@ Null_pattern2_decode(p, arruNullValueAsByteArray, nSize, arrsBits, sErrCode, bSa >> - Enumerated_item_encode(p, sName, sEnumHolder, nItemIdxOrVal, sIntVal) ::= << -case => - = +case => >> - Enumerated_item_decode(p, sName, sEnumHolder, nItemIdxOrVal, sIntVal) ::= << -case => -

= +case => >> EnumeratedEncIdx_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActualCodecFunc, sIntVal) ::= << @@ -345,49 +341,42 @@ EnumeratedEncIdx_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActual >> EnumeratedEncValues_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActualCodecFunc, sErrCode, sFirstItemName, sIntVal) ::= << -

match +val =

match - case _ => - return Left() -if ret.isRight then - + >> EnumeratedEncValues_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, sActualCodecFunc, sErrCode, sFirstItemName, sIntVal) ::= << -if ret.isRight then - match - - case _ => - return Left() +val

= match + + case _ => return Left() >> /* Strings */ Acn_String_Ascii_FixSize_encode(p, sErrCode, nAsn1Max) ::= "codec.enc_String_Ascii_FixSize(,

)" Acn_String_Ascii_FixSize_decode(p, sErrCode, nAsn1Max) ::= << -codec.dec_String_Ascii_FixSize() match - case None() => - return Left() - case Some(x) => -

= x +val

= codec.dec_String_Ascii_FixSize() match + case None() => return Left() + case Some(x) => x >> -Acn_String_Ascii_Null_Teminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -codec.enc_String_Ascii_Null_Teminated_mult(, Array({}), ,

) +Acn_String_Ascii_Null_Terminated_encode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << +codec.enc_String_Ascii_Null_Terminated_mult(, Array({}), ,

) >> -Acn_String_Ascii_Null_Teminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << -codec.dec_String_Ascii_Null_Teminated_mult(, Array({}), ) match +Acn_String_Ascii_Null_Terminated_decode(p, sErrCode, nAsn1Max, arruNullBytes) ::= << +val

= codec.dec_String_Ascii_Null_Terminated_mult(, Array({}), ) match case NoneMut() => return Left() - case SomeMut(x) =>

= x + case SomeMut(x) => x >> Acn_String_Ascii_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, sExtFld) ::= "codec.enc_String_Ascii_External_Field_Determinant(,

)" Acn_String_Ascii_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld) ::= << -codec.dec_String_Ascii_External_Field_Determinant(, ) match +val

= codec.dec_String_Ascii_External_Field_Determinant(, ) match case None() => return Left() - case Some(x) =>

= x + case Some(x) => x >> Acn_String_Ascii_Internal_Field_Determinant_encode(p, sErrCode, nAsn1Max, nAsn1Min, nInternalLengthDeterminantSizeInBits) ::= << @@ -395,9 +384,9 @@ codec.enc_String_Ascii_Internal_Field_Determinant(, ,

) >> Acn_String_Ascii_Internal_Field_Determinant_decode(p, sErrCode, nAsn1Max, nAsn1Min, nInternalLengthDeterminantSizeInBits) ::= << -codec.dec_String_Ascii_Internal_Field_Determinant(, ) match +val

= codec.dec_String_Ascii_Internal_Field_Determinant(, ) match case None() => return Left() - case Some(x) =>

= x + case Some(x) => x >> PrintAlphabet2(arrnCharSet) /*nogen*/ ::= << @@ -411,9 +400,9 @@ codec.enc_String_CharIndex_FixSize(, allowedCharSet, , < Acn_String_CharIndex_FixSize_decode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -codec.dec_String_CharIndex_FixSize(, allowedCharSet, ) match +val

= codec.dec_String_CharIndex_FixSize(, allowedCharSet, ) match case None() => return Left() - case Some(x) =>

= x + case Some(x) => x >> Acn_String_CharIndex_External_Field_Determinant_encode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << @@ -423,9 +412,9 @@ codec.enc_String_CharIndex_External_Field_Determinant(, allowedCharSet Acn_String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, arrnAlphabetAsciiCodes, nCharSetSize, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -codec.dec_String_CharIndex_External_Field_Determinant(, allowedCharSet, , ) match +val

= codec.dec_String_CharIndex_External_Field_Determinant(, allowedCharSet, , ) match case None() => return Left() - case Some(x) =>

= x + case Some(x) => x >> @@ -434,48 +423,57 @@ codec.enc_IA5String_CharIndex_External_Field_Determinant(,

) >> Acn_IA5String_CharIndex_External_Field_Determinant_decode(p, sErrCode, nAsn1Max, sExtFld, td/*:FE_StringTypeDefinition*/, nCharSize) ::= << -

= codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) +val

= codec.dec_IA5String_CharIndex_External_Field_Determinant(, ) >> -oct_external_field_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << codec.encodeOctetString_no_length(

arr,

nCount.toInt) >> -oct_external_field_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -if ((\<=) && (\<=)) then -

nCount = .asInstanceOf[Int] - /* TODO copyToArray? */ - codec.decodeOctetString_no_length(

nCount.toInt).copyToArray(

arr) +oct_external_field_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +val

= + if ((\<=) && (\<=)) then + (.toLong, codec.decodeOctetString_no_length(.toInt)) + else return Left() >> -oct_external_field_fix_size_encode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +oct_external_field_fix_size_encode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << codec.encodeOctetString_no_length(

arr, ) >> -oct_external_field_fix_size_decode(p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << -if ((\<=) && (\<=)) then - codec.decodeOctetString_no_length().copyToArray(

arr) +oct_external_field_fix_size_decode(sTypedefName, p, sAcc, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode) ::= << +val

= + if ((\<=) && (\<=)) then + (codec.decodeOctetString_no_length()) + else return Left() >> -sqf_external_field_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -if ((\<=) && (\<=)) then -

nCount = .toInt - +sqf_external_field_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << +val

= + if ((\<=) && (\<=)) then + val

= (.toInt, Array.fill(.toInt)()) + +

+ else return Left() >> -sqf_external_field_fix_size_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << +sqf_external_field_fix_size_encode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << >> -sqf_external_field_fix_size_decode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << -if ((\<=) && (\<=)) then - +sqf_external_field_fix_size_decode(sTypeDefName, p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, sExtFld, nAlignSize, sErrCode, nIntItemMinSize, nIntItemMaxSize, sChildInitExpr) ::= << +val

= + if ((\<=) && (\<=)) then + val

= (Array.fill(.toInt)()) + +

+ else return Left() >> oct_sqf_null_terminated_encode(p, sAcc, i, sInternalItem, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength, sErrCode, nIntItemMinSize, nIntItemMaxSize) ::= << @@ -486,113 +484,105 @@ codec.appendBitsMSBFirst(Array({}), = 0 -ret = Right(0) - + var checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) -while ret.isRight && \< && !checkBitPatternPresentResult.getOrElse(true) do +while \< && !checkBitPatternPresentResult.getOrElse(true) do += 1 checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) -if ret.isRight && ( == ) && !checkBitPatternPresentResult.getOrElse(true) then +if ( == ) && !checkBitPatternPresentResult.getOrElse(true) then checkBitPatternPresentResult = codec.checkBitPatternPresent(Array({}), ) -if (ret && checkBitPatternPresentResult.isEmpty) { - ret = Left() /*COVERAGE_IGNORE*/ -} else if (ret && checkBitPatternPresentResult.get) { +if checkBitPatternPresentResult.isEmpty then + return Left() +else if checkBitPatternPresentResult.get then

nCount = - ret = Right(0) -} >> -bit_string_external_field_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << codec.appendBitsMSBFirst(

arr,

nCount) >> -bit_string_external_field_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if (\<=) && (\<=) then -

nCount = .toInt - codec.readBits(

nCount).copyToArray(

arr) match +bit_string_external_field_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +val

= + if (\<=) && (\<=) then + (, codec.readBits()) + else return Left() >> -bit_string_external_field_fixed_size_encode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +bit_string_external_field_fixed_size_encode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << codec.appendBitsMSBFirst(

arr, ) >> -bit_string_external_field_fixed_size_decode(p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << -if (\<=) && (\<=) then - codec.readBits().copyToArray(

arr) +bit_string_external_field_fixed_size_decode(sTypeDefName, p, sErrCode, sAcc, noSizeMin, nSizeMax, sExtFld) ::= << +val

= + if (\<=) && (\<=) then + (codec.readBits()) + else return Left() >> -bit_string_null_terminated_encode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +bit_string_null_terminated_encode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << codec.appendBitsMSBFirst(

arr,

arr.length*8) // TODO: re-introduce nCount? -> codec.appendBitsMSBFirst(

arr,

nCount) codec.appendBitsMSBFirst(Array({}), ) >> -bit_string_null_terminated_decode(p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << - codec.readBits_nullterminated(Array({}), , ) match - case NoneMut() => - return Left() - case SomeMut(arr, i) => -

arr = arr +bit_string_null_terminated_decode(sTypeDefName, p, sErrCode, sAcc, i, noSizeMin, nSizeMax, arruNullBytes, nBitPatternLength) ::= << +val

= codec.readBits_nullterminated(Array({}), , ) match + case NoneMut() => return Left() + case SomeMut(arr, i) => (arr) >> RefTypeParam_tmpVar(sName, sTypeDecl) ::= " " ReferenceType1_encode(p, sName, bAcnEncodeFuncRequiresResult, arrsArgs, arrsLocalPrms) ::= << = ;// 3031}; separator="\n"> -ret = _ACN_Encode(

, codec, pErrCode, FALSE, ) +_ACN_Encode(

, codec, pErrCode, FALSE, ) match + case Left(err) => return Left(err) + case Right(_) => >> ReferenceType1_decode(p, sName, bAcnEncodeFuncRequiresResult, arrsArgs, arrsLocalPrms) ::= << = ; // 3030}; separator="\n"> -ret = _ACN_Decode(

, codec, pErrCode, ) +_ACN_Decode(

, codec, pErrCode, ) match + case Left(err) => return Left(err) + case Right(_) => >> /* SEQUENCE*/ -sequence_presense_optChild_encode(p, sAcc, sChName, sErrCode) ::= << -codec.appendBit(

exist.) +sequence_presence_optChild_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= << +codec.appendBit(

.isDefined) >> -sequence_presense_optChild_decode(p, sAcc, sChName, sErrCode) ::= << -

exist. = codec.readBit() +sequence_presence_optChild_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << + = codec.readBit() >> -sequence_presense_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << -

exist. == match - case false => - return Left() - case true => - ret = Right(0) +sequence_presence_optChild_pres_acn_expression_encode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << +if

.isDefined != then + return Left() >> -sequence_presense_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, sErrCode) ::= << -

exist. = +sequence_presence_optChild_pres_acn_expression_decode(p, sAcc, sChName, sAcnExpression, soExistVar, sErrCode) ::= << + = >> -sequence_presense_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" -sequence_presense_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= << -

exist. = ->> +sequence_presence_optChild_pres_bool_encode(p, sAcc, sChName, sExtFldName) ::= "" +sequence_presence_optChild_pres_bool_decode(p, sAcc, sChName, sExtFldName) ::= "" -sequence_presense_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" -sequence_presense_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= << -

exist. = == ->> +sequence_presence_optChild_pres_int_encode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" +sequence_presence_optChild_pres_int_decode(p, sAcc, sChName, sExtFldName, nIntVal) ::= "" -sequence_presense_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" -sequence_presense_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= << -

exist. = == "" ->> +sequence_presence_optChild_pres_str_encode(p, sAcc, sChName, sExtFldName, sVal) ::= "" +sequence_presence_optChild_pres_str_decode(p, sAcc, sChName, sExtFldName, sVal) ::= "" sequence_save_bitStream_start_encode(sBitStreamPositionsLocalVar) ::=<< - = pBitStrm // save the initial position of the bit stream at + = pBitStrm // save the initial position of the bit stream at >> sequence_save_bitStream_start_decode(sBitStreamPositionsLocalVar) ::=<< -ret = Right(0) = pBitStrm // save the initial position of the bit stream >> @@ -606,16 +596,12 @@ sequence_save_bitstream_decode(sBitStreamPositionsLocalVar, sChName) ::=<< sequence_acn_child_encode(sChName, sChildContent, sErrCode, soSaveBitStrmPosStatement) ::= << /* Encode */ -if _is_initialized then - ret = Right(0) - - -else - return Left() + + >> sequence_acn_child_decode(sChName, sChildContent, sErrCode, soSaveBitStrmPosStatement) ::= << -/* Decode */ +/* Decode */ >> @@ -632,73 +618,70 @@ sequence_mandatory_child_decode(sChName, sChildContent, soSaveBitStrmPosStatemen >> -sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_encode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << /* Encode */ -/* marked as ALWAYS PRESENT, so do not look in exist */ - - +/* marked as ALWAYS PRESENT, so it must be Some */ +

match + case Some() => + + + case None() => return Left(628) >> -sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_present_child_decode(p, sAcc, sChName, soChildContent, soChildExpr, soSaveBitStrmPosStatement) ::= << /* Decode */ /* marked as ALWAYS PRESENT */ -

exist. = true - +val

_ = + + Some() >> -sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_encode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << /* Encode */ /* marked as ALWAYS ABSENT, so do not encode anything */ >> - -sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_always_absent_child_decode(p, sAcc, sChName, sChildContent, sChildTypedef, soSaveBitStrmPosStatement) ::= << /* Decode */ /* marked as ALWAYS ABSENT, so do not decode anything */ -

exist. = false +val

_ = None[]() >> -sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /* Encode */ -if

exist. then - +

match + case Some() => + + case None() => >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /* Decode */ -if

exist. then - ->> - -sequence_optional_always_present_child_encode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << -/* Encode */ - - ->> - -sequence_optional_always_present_child_decode(p, sAcc, sChName, sChildContent, soSaveBitStrmPosStatement) ::= << -/* Decode (always present) */ - -

exist. = true - +val

_ = + if then + + Some() + else None[]() >> -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << +sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << - + >> -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soSaveBitStrmPosStatement) ::= << +sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue, soExistVar, soChildExpr, sChildTypedef, soSaveBitStrmPosStatement) ::= << /* Decode */ -if

exist. then - -else - +val

_ = + if then + + Some() + else + >> sequence_call_post_encoding_function(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << @@ -706,7 +689,9 @@ sequence_call_post_encoding_function(p, sFncName, sBitStreamStartPos, sBitStream >> sequence_call_post_decoding_validator(p, sFncName, sBitStreamStartPos, sBitStreamPositionsNullPos) ::= << -ret = (

, , , codec) +(

, , , codec) match + case Left(err) => return Left(err) + case Right(_) => >> /* SEQUENCE END */ @@ -714,7 +699,7 @@ ret = (

, , , codec) /* Choice like uper */ ChoiceChildAlwaysAbsent_encode(p, sAcc, sChildID, nChildIndex, sErrorCodeName) ::= << -case => +case => return Left() >> @@ -731,32 +716,27 @@ case () => ChoiceChild_decode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case => - var : = -

= () + () >> Choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= <<

match }; separator="\n"> - case _ => - return Left() >> Choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits, sErrCode) ::= << codec.decodeConstrainedWholeNumber(0, ) match - case None() => + case None() => return Left() case Some(x) => - = x.asInstanceOf[Int] - - match + = x.toInt +val

= match }; separator="\n"> - case _ => - return Left() + case _ => return Left() >> -/* Choice with presense determinants */ +/* Choice with presence determinants */ ChoiceChild_preWhen_encode(p, sAcc, sChildID, sChildBody, arrsConditions, bFirst, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case () => @@ -766,26 +746,26 @@ case () => ChoiceChild_preWhen_bool_condition(sExtFld) ::= "" ChoiceChild_preWhen_int_condition(sExtFld, nVal) ::= "( == )" ChoiceChild_preWhen_str_condition(sExtFld, sVal, arrsNullChars) ::= "(.sameElements(\"\".getBytes ++ Array(0x00.toByte)))" - +// TODO: Et le "else" ??? ChoiceChild_preWhen_decode(p, sAcc, sChildID, sChildBody, arrsConditions, bFirst, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << -else if () { - var : = +val

= if () { + +else if () { + + -

= () + () } >> Choice_preWhen_encode(p, sAcc, arrsChildren, sErrCode) ::= <<

match - case _ => - return Left() >> Choice_preWhen_decode(p, sAcc, arrsChildren, sErrCode) ::= << -else - return Left() +else return Left() >> /* Choice with Enum determinant */ @@ -796,114 +776,122 @@ case () => ChoiceChild_Enum_decode(p, sAcc, sEnmName, sChildID, sChildBody, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr) ::= << case => - var : = -

= () + () >> Choice_Enum_encode(p, sAcc, arrsChildren, sEnmExtFld, sErrCode) ::= <<

match - case _ => - ret = Left(ERR_INVALID_ENUM_VALUE) >> Choice_Enum_decode(p, sAcc, arrsChildren, sEnmExtFld, sErrCode) ::= << - match +val

= match - case _ => - ret = Left(ERR_INVALID_ENUM_VALUE) >> /* Updates */ SizeDependency(v, sCount, nMin, nMax, bCheckRange, sTypedefName) ::= << -_is_initialized = true - = +val = >> SizeDependencyFixedSize(v, nFixedSize) ::= << -_is_initialized = true - = +val = >> -ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName) ::= << -case .(x) => - _is_initialized = true - = +ChoiceDependencyEnum_Item(v, sChildCID, sChildCIDHolder, sEnumCName, bIsOptional) ::= << + +case Some(.(_)) => + +case .(_) => + + >> -ChoiceDependencyEnum(sChPath, sAcc, arrsChoiceEnumItems) ::= << - match +ChoiceDependencyEnum(sV, sChPath, sAcc, arrsChoiceEnumItems, bIsOptional, sDefaultExpr) ::= << +val = match - case _ => - return Left(ERR_INVALID_ENUM_VALUE) + + case None() => + >> PresenceDependency(v, sSeqPath, sAcc, sChildName) ::= << -_is_initialized = true - = (exist.) +val = .isDefined >> ChoiceDependencyIntPres_child(v, sChildNamePrese, nChildRetVal) ::= << case _: => - _is_initialized = true - = + >> ChoiceDependencyStrPres_child(v, sChildNamePrese, sChildRetVal, arrsNullChars) ::= << case _: => - _is_initialized = true - = "".getBytes ++ Array(0x00.toByte) + "".getBytes ++ Array(0x00.toByte) >> -ChoiceDependencyPres(sChPath, sAcc, arrsChoiceItems) ::= << - match +ChoiceDependencyPres(v, sChPath, sAcc, arrsChoiceItems) ::= << +val = match - case _ => - return Left(951) >> MultiAcnUpdate_checkEqual_pri0(p1,p2) ::= "( == )" MultiAcnUpdate_checkEqual_str0(p1,p2) ::= "( == )" -MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, bIsFirst) ::= << -else if _is_initialized then - = +MultiAcnUpdate_get_first_init_value_pri(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << + +val = + + +val = if .isDefined then + + +else if .isDefined then + + + >> -MultiAcnUpdate_get_first_init_value_str(sV0, sVi, bIsFirst) ::= << -else if _is_initialized then - = +MultiAcnUpdate_get_first_init_value_str(sV0, sVi, sChPath, bIsFirst, bIsSingleElement) ::= << + >> -MultiAcnUpdate_checkEqual_pri(sV0, sVi) ::= "((_is_initialized && == ) || !_is_initialized)" -MultiAcnUpdate_checkEqual_str(sV0, sVi) ::= "((_is_initialized && == ) || !_is_initialized)" - +MultiAcnUpdate_checkEqual_pri(sV0, sVi, sChPath, bIsAlwaysInit) ::= << + +( == ) + +((.isDefined && == ) || !.isDefined) + +>> +MultiAcnUpdate_checkEqual_str(sV0, sVi, sChPath, bIsAlwaysInit) ::= << + +>> -MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, arrsLocalCheckEquality) ::= << -{ +MultiAcnUpdate(v, sV0, sErrCode, arrsLocalDeclarations, arrsLocalUpdateStatements, arrsGetFirstIntValue, bIsFirstIntValueSingle, arrsLocalCheckEquality, sDefaultExpr) ::= << +val = { - + - - if ret.isRight then - - - else - return Left() - - if ret.isRight then - _is_initialized = true - - if !() then - return Left(998) + + + + else + + + + if !() then + return Left(998) + } >> -checkAccessPath(arrsCheckPaths, sUpdateStatement) ::= << -if then - +checkAccessPath(arrsCheckPaths, sUpdateStatement, v, sInitExpr) ::= << +val = + if then + + + else >> @@ -915,18 +903,12 @@ SizeDependency_oct_str_containing(p, sFuncName, sReqBytesForUperEncoding, v, bIs pBitStrm = pBitStrm_save } -if ret.isRight then - = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1)bitStrm.currentByte*8+bitStrm.currentBit; - _is_initialized = true + = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1)bitStrm.currentByte*8+bitStrm.currentBit; >> octet_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sExtField, sErrCode, soInner) ::= << -codec.encodeOctetString_no_length(arr, .asInstanceOf[Int]) match - case false => - return Left() - case true => - ret = Right(0) +codec.encodeOctetString_no_length(arr, .asInstanceOf[Int]) >> octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sExtField, sErrCode, soInner) ::= << @@ -935,10 +917,10 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco /* decode to a temporary bitstream */ val pBitStrm_save: BitStream = pBitStrm val bitStrm: BitStream = BitStream_Init() - + if .asInstanceOf[Int] \<= then codec.decodeOctetString_no_length(.asInstanceOf[Int]) match - case NoneMut() => + case NoneMut() => return Left() case SomeMut(arr) => bitStrm.buf = arr @@ -950,7 +932,7 @@ octet_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEnco >> bit_string_containing_ext_field_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << -codec.appendBitsMSBFirst(arr, .asInstanceOf[Int]) +codec.appendBitsMSBFirst(arr, .toInt) >> bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, sExtField, sErrCode) ::= << @@ -960,12 +942,14 @@ bit_string_containing_ext_field_func_decode(p, sFuncName, sReqBytesForUperEncodi val bitStrm: BitStream = BitStream_Init() if .asInstanceOf[Int] \<= then codec.readBits((int)) match - case NoneMut() => + case NoneMut() => return Left() case SomeMut(arr) => bitStrm.buf = arr - ret = (

, bitStrm) + (

, bitStrm) match + case Left(err) => return Left(err) + case Right(_) => } >> @@ -976,35 +960,28 @@ sparkAnnotations_decode(sTypeDefName) ::= "" octet_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, nBits, nMinSize, nMaxSize, bFixedSize) ::= << /*open new scope to declare some variables*/ { - /* encode to a temporary bitstream */ + /* encode to a temporary bitstream */ val bitStrm: BitStream = BitStream_Init() - ret = (

, bitStrm, false) - - if ret.isRight then - int nCount = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1) - - codec.encodeOctetString_no_length(bitStrm.buf, nCount) match - case false => - return Left(pErrCode) - case true => - ret = Right(0) - - - codec.encodeConstrainedWholeNumber(nCount, , ) - codec.encodeOctetString_no_length(bitStrm.buf, nCount) match - case false => - return Left(pErrCode) - case true => - ret = Right(0) - - + (

, bitStrm, false) match + case Left(err) => return Left(err) + case Right(_) => + + int nCount = bitStrm.currentBit == 0 ? bitStrm.currentByte : (bitStrm.currentByte + 1) + + codec.encodeOctetString_no_length(bitStrm.buf, nCount) + + + codec.encodeConstrainedWholeNumber(nCount, , ) + codec.encodeOctetString_no_length(bitStrm.buf, nCount) + + } >> octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits, nMinSize, nMaxSize, bFixedSize) ::= << /*open new scope to declare some variables*/ -{ - /* decode to a temporary bitstream */ +{ + /* decode to a temporary bitstream */ val bitStrm: BitStream = BitStream_Init() @@ -1013,7 +990,6 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits return Left(pErrCode) case SomeMut(arr) => bitStrm.buf = arr - var nCount: Int = 0 codec.decodeConstrainedWholeNumber(, ) match @@ -1022,16 +998,16 @@ octet_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, nBits case Some(x) => nCount = x - if ret.isRight then - codec.decodeOctetString_no_length(nCount.asInstanceOf[Int]) - case NoneMut() => - return Left(pErrCode) - case SomeMut(arr) => - bitStrm.buf = arr + codec.decodeOctetString_no_length(nCount.asInstanceOf[Int]) + case NoneMut() => + return Left(pErrCode) + case SomeMut(arr) => + bitStrm.buf = arr - if ret.isRight then - ret = (

, &bitStrm) + (

, &bitStrm) match + case Left(err) => return Left(err) + case Right(_) => } >> @@ -1041,24 +1017,28 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit /* encode to a temporary bitstream */ val bitStrm: BitStream = BitStream_Init() - ret = (

, bitStrm, false) // TODO check if call is correct asn:1131 - if ret.isRight then - val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; - - codec.appendBitsMSBFirst(bitStrm.buf, nCount) - - codec.encodeConstrainedWholeNumber(nCount, , ) - codec.appendBitsMSBFirst(bitStrm.buf, nCount) - + (

, bitStrm, false) match // TODO check if call is correct asn:1131 + case Left(err) => return Left(err) + case Right(_) => + + val nCount: Int = bitStrm.currentByte*8 + bitStrm.currentBit; + + codec.appendBitsMSBFirst(bitStrm.buf, nCount) + + + codec.BitStream_EncodeConstraintWholeNumber(nCount, , ) + codec.appendBits(bitStrm.buf, nCount) + + } >> bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBitsForUperEncoding, nBits, nMinSize, nMaxSize, bFixedSize) ::= << /*open new scope to declare some variables*/ -{ +{ /* decode to a temporary bitstream */ val codec: Codec = ACN(BitStream_Init()) - + codec.readBits() match case NoneMut() => @@ -1066,8 +1046,9 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit case SomeMut(arr) => bitStrm.buf = arr - if ret.isRight then - ret = (

, bitStrm) // TODO check if call is right + (

, bitStrm) match // TODO check if call is right + case Left(err) => return Left(err) + case Right(_) => var nCount: Int = 0 @@ -1076,16 +1057,16 @@ bit_string_containing_func_decode(p, sFuncName, sReqBytesForAcnEncoding, sReqBit return Left(pErrCode) case Some(x) => nCount = x - ret = Right(0) codec.readBits(nCount) match case NoneMut() => return Left(pErrCode) case SomeMut(arr) => bitStrm.buf = arr - ret = Right(0) - ret = (

, bitStrm) + (

, bitStrm) match + case Left(err) => return Left(err) + case Right(_) => } diff --git a/StgScala/equal_scala.stg b/StgScala/equal_scala.stg index f5e3ced16..123cb99bf 100644 --- a/StgScala/equal_scala.stg +++ b/StgScala/equal_scala.stg @@ -30,10 +30,10 @@ if (ret) { E Q U A L F U N C T I O N S ***************************************************************************************** */ -PrintEqualDefintionPrimitive(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionPrimitive(sFuncName, sTypeDefName) ::= << >> -PrintEqualDefintionComposite(sFuncName, sTypeDefName) ::= << +PrintEqualDefinitionComposite(sFuncName, sTypeDefName) ::= << >> PrintEqualPrimitive(sFuncName, sTypeDefName, sContent) ::= << @@ -65,7 +65,7 @@ def (: , : ): Boole - + return @@ -102,12 +102,12 @@ isEqual_NullType()/*nogen*/ ::= "ret = true" isEqual_BitString(p1,p2,bIsFixedSize, nFixedSize) ::= << - (nCount == nCount) && - (arr.slice(0,(nCount/8).toInt).sameElements(arr.slice(0,(nCount/8).toInt))) && + (nCount == nCount) && + (arr.slice(0,(nCount/8).toInt).sameElements(arr.slice(0,(nCount/8).toInt))) && (if nCount % 8 > 0 then (arr(nCount.toInt/8) \>> (8-nCount % 8) == arr(nCount.toInt/8)\>>(8-nCount % 8) ) else true) - (arr.slice(0,/8).sameElements(arr.slice(0,/8))) && + (arr.slice(0,/8).sameElements(arr.slice(0,/8))) && (if ( % 8) > 0 then (arr(/8)\>>(8- % 8) == arr(/8)\>>(8- % 8) ) else true) @@ -120,7 +120,7 @@ isEqual_OctetString(p1,p2, bIsFixedSize, nFixedSize) ::= << (nCount == nCount) && (arr.sameElements(arr)) arr.sameElements(arr) - + >> isObjectIdentifier_equal(p1, p2) ::= << @@ -129,8 +129,8 @@ ObjectIdentifier_equal(, ) -isEqual_Choice_Child(choiceTypeDefName, sCid, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << -case (.(), .()) => +isEqual_Choice_Child(sChoiceTypeDefName, sCid, sInnerStatement, sTmpVarName1, sTmpVarName2) ::= << +case (.(), .()) => >> @@ -144,9 +144,9 @@ isEqual_Choice(p1,p2, sAccess, arrsChildren) ::= << isEqual_Sequence_child(p1, p2, sAcc, bIsOptional, sChName, soInnerStatement) ::= << -ret = (exist. == exist.) +ret = (.isDefined == .isDefined) -if (ret && exist.) then +if (ret && .isDefined) then diff --git a/StgScala/header_scala.stg b/StgScala/header_scala.stg index 349a364d3..0d3b1c6bc 100644 --- a/StgScala/header_scala.stg +++ b/StgScala/header_scala.stg @@ -18,9 +18,9 @@ import stainless.annotation._ }; separator="\n"> -}; separator="\n"> +}; separator="\n"> -}; separator="\n"> +}; separator="\n"> >> Define_TAS(sTypeDefinition, arrsProcs) ::= << @@ -34,7 +34,7 @@ PrintValueAssignment(sName, sTypeDecl, sValue) ::= << >> /* -Scala TYPES +Scala TYPES */ Declare_Integer() ::="Long" @@ -107,7 +107,7 @@ Define_new_enumerated_item_macro(td/*:FE_EnumeratedTypeDefinition*/, sAsn1Name, >> Define_new_enumerated(td/*:FE_EnumeratedTypeDefinition*/, arrsEnumNames, arrsEnumNamesAndValues, nIndexMax, arrsResolvingMacros) ::= << -enum (val i: Int): +enum (val i: Int): }; separator="\n"> // please use the following macros to avoid breaking code. @@ -137,7 +137,7 @@ Define_new_octet_string(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize /*nCount equals to Number of bytes in the array. Max value is : (unsure - TODO read asn1 standard)*/ -case class (var nCount: Long, var arr: Array[Byte]) +case class (nCount: Long, arr: Array[Byte]) { require(arr.length == ) } @@ -160,7 +160,7 @@ Define_new_bit_string(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, /*nCount equals to Number of bits in the array. Max value is : */ -case class (var nCount: Long, var arr: Array[Byte]) +case class (nCount: Long, arr: Array[Byte]) { require(arr.length == ) } @@ -173,19 +173,19 @@ typedef /*********************************** SEQUENCE OF ************************************************************/ -Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefintion) ::= << +Define_new_sequence_of(td/*:FE_SizeableTypeDefinition*/, nMin, nMax, bFixedSize, sChildType, soChildDefinition) ::= << - + -case class (var nCount: Int, arr: Array[]) +case class (nCount: Int, arr: Array[]) { require(arr.length == ) } >> -Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefintion) ::= << +Define_subType_sequence_of(td/*:FE_SizeableTypeDefinition*/, prTd/*:FE_SizeableTypeDefinition*/, soParentTypePackage, bFixedSize, soChildDefinition) ::= << - + typedef >> @@ -195,31 +195,30 @@ typedef Define_new_sequence_child_bit(sName) ::= ": Boolean" -Define_new_sequence_child(sName, sType) ::= ": " +Define_new_sequence_child(sName, sType, bIsOptional) ::= << + +: Option[] + +: + +>> Define_new_sequence_save_pos_child(td/*:FE_SequenceTypeDefinition*/, sName, nMaxBytesInACN) ::= "BitStream ;" -Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildldrenDefintions, arrsNullFieldsSavePos) ::= << +Define_new_sequence(td/*:FE_SequenceTypeDefinition*/, arrsChildren, arrsOptionalChildren, arrsChildrenDefinitions, arrsNullFieldsSavePos) ::= << /*-- --------------------------------------------*/ - + -case class ( +case class ( ) - -case class ( - }; separator=", \n"> -) - + case class ( - - var exist: , - - }; separator=", \n"> + }; separator=", \n"> ) >> @@ -227,7 +226,7 @@ case class ( Define_subType_sequence(td/*:FE_SequenceTypeDefinition*/, prTd/*:FE_SequenceTypeDefinition*/, soParentTypePackage, arrsOptionalChildren) ::= << type = -type = +type = >> @@ -238,12 +237,11 @@ Define_new_choice_child(sName, sType, sPresent) ::=<< : >> -Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildldrenDefintions) ::= << +Define_new_choice(td/*:FE_ChoiceTypeDefinition*/, sChoiceIDForNone, sFirstChildNamePresent, arrsChildren, arrsPresent, arrsCombined, nIndexMax, arrsChildrenDefinitions) ::= << /*-- --------------------------------------------*/ - + enum : - case () }; separator="\n"> >> diff --git a/StgScala/init_scala.stg b/StgScala/init_scala.stg index 11643e811..038ef42af 100644 --- a/StgScala/init_scala.stg +++ b/StgScala/init_scala.stg @@ -7,21 +7,14 @@ methodNameSuffix() ::= "_Initialize" initTypeAssignment_def(sVarName, sStar, sFuncName, sTypeDefName) ::= << >> initTypeAssignment(sVarName, sPtrPrefix, sPtrSuffix, sFuncName, sTypeDefName, sContent, arrsLocalVariables, sDefaultInitValue) ::= << -def (): = -{ - var : = - - - - -} +def (): = >> initInteger(sVal, nValue) ::= " = " initReal(sVal, dValue) ::= " = " initBoolean(sVal, bValue) ::= " = truefalse" -initObjectIdentifier_vali(p, sAcc, sI, nIntVal) ::= "

values() = " +initObjectIdentifier_valid(p, sAcc, sI, nIntVal) ::= "

values() = " initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= <<

nCount = @@ -30,14 +23,14 @@ initObjectIdentifier(p, sAcc, nSize, arrsValues) ::= << init_Asn1LocalTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours =

mins = -

sec = +

sec =

fraction = >> init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= <<

hours =

mins = -

sec = +

sec =

fraction = >> @@ -45,7 +38,7 @@ init_Asn1UtcTime(p, sAcc, tv/*:Asn1TimeValue*/) ::= << init_Asn1LocalTimeWithTimeZone(p, sAcc, tv/*:Asn1TimeValue*/, tz/*:Asn1TimeZoneValue*/) ::= <<

hours =

mins = -

sec = +

sec =

fraction =

tz.sign =

tz.hours = @@ -91,7 +84,7 @@ initTestCaseIA5String(p, sAcc, nSize, nMaxSizePlusOne, i, td/*:FE_StringTypeDefi

= Array.fill(){0} while ( \< ) { - val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">) + val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">)

() = allowedCharSet( % ) @@ -158,13 +151,13 @@ initSequence_pragma(p) ::= "" initFixedSequenceOf(arrsInnerValues) ::= << - + >> initVarSizeSequenceOf(p, sAcc, nSize, arrsInnerValues) ::= <<

nCount = ; - + >> @@ -186,12 +179,12 @@ while ( \< ) { /*SEQUENCE*/ initSequence_optionalChild(p, sAcc, sChName, sPresentFlag, sChildContent) ::=<< -

exist. = +

exist. = if == 0 then false else true >> initSequence(arrsInnerValues) ::= << - + >> initSequence_emptySeq(p) ::= "" @@ -207,14 +200,14 @@ initTestCase_sequence_child_opt(p, sAcc, sChName) ::= << initChoice(p, sAcc, sChildContent, sChildID, sChildName, sChildTypeName, sChoiceTypeName, sChildTempVarName, sChildTempDefaultInit, bComponentTempInit) ::= << var : = - -

= () + +

= () >> initTestCase_choice_child(p, sAcc, sChildContent, sChildID, sChildName, sChildTypeName, sChoiceTypeName, sChildTempVarName, sChildTempDefaultInit) ::= << var : = - -

= () + +

= () >> initChildWithInitFunc(p, sChildInitFuncName) ::= << @@ -238,17 +231,17 @@ val : = >> initTypeConstant_body(sTypeDecl, sConstantName, sValue) ::= << -val : sTypeDecl> = +val : = >> -initFixSizeOctetString(nMax, bZeroSizedArray) ::= "Array.fill()(0)" -initVarSizeOctetString(nMin, nMax) ::= "null" +initFixSizeOctetString(sTypeDefName, nMax, bZeroSizedArray) ::= "(Array.fill()(0))" +initVarSizeOctetString(sTypeDefName, nMin, nMax) ::= "(, Array.fill()(0))" -initFixSizeBitString(nMax, nMaxOctets) ::= "Array.fill()(0)" -initVarSizeBitString(nMin, nMax, nMaxOctets) ::= "null" +initFixSizeBitString(sTypeDefName, nMax, nMaxOctets) ::= "(Array.fill()(0))" +initVarSizeBitString(sTypeDefName, nMin, nMax, nMaxOctets) ::= "(, Array.fill()(0))" -initFixSizeSequenceOfExpr(nMax, sChildExp) ::= "null" -initVarSizeSequenceOfExpr(nMin, nMax, sChildExp) ::= "null" +initFixSizeSequenceOfExpr(sTypeDefName, nMax, sChildExp) ::= "(Array.fill()())" +initVarSizeSequenceOfExpr(sTypeDefName, nMin, nMax, sChildExp) ::= "(, Array.fill()())" initObjectIdentifierAsExpr() ::= << @@ -284,10 +277,16 @@ init_Asn1Date_LocalTimeWithTimeZoneExpr() ::= << {.years = 0, .months = 0, .days = 0, .hours = 0, .mins = 0, .sec = 0, .fraction = 0, .tz.sign = 0, .tz.hours = 0, .tz.mins = 0 } >> -initSequenceChildExpr(sChildName, sChildExpr) ::= " = " -initSequenceOptionalChildExpr(sChildName, nPresenceBit) ::= " = " -initSequenceExpr(arrsChildren, arrsOptionalChildren) ::= << -, exist = null +initSequenceChildExpr(sChildName, sChildExpr, bIsOptional) ::= << + + = Some() + + = + +>> +initSequenceOptionalChildExpr(sChildName, nPresenceBit) ::= " = if == 0 then false else true" +initSequenceExpr(sTypeDefName, sTypeDefNameExist, arrsChildren, arrsOptionalChildren) ::= << +() >> -initChoiceExpr(sChildName, sChildKind, sChildExpr) ::= "{.kind = , .u. = }" +initChoiceExpr(sChildName, sChildKind, sChildExpr) ::= "()" diff --git a/StgScala/isvalid_scala.stg b/StgScala/isvalid_scala.stg index 341aad5e5..5e03c26b0 100644 --- a/StgScala/isvalid_scala.stg +++ b/StgScala/isvalid_scala.stg @@ -2,11 +2,6 @@ rtlModuleName() ::= "" - -getStringSize(p) ::= "strlen(

)" - - - JoinItems(sPart, soNestedPart) ::= << @@ -91,24 +86,24 @@ ExpLt(sExp1, sExp2) ::= "( \< )" ExpLte(sExp1, sExp2) ::= "( \<= )" ExpOr(sExp1, sExp2) ::= "(() || ())" ExpAnd(sExp1, sExp2) ::= "( && )" -ExpAndMulit(arrsExp) ::= << +ExpAndMulti(arrsExp) ::= << >> ExpNot(sExp) ::= "(!)" StrLen(sExp) ::= ".indexOf(0)" ArrayLen(sExp, sAcc) ::= "nCount" -ExpressionToStament(sExp1) ::=<< +ExpressionToStatement(sExp1) ::=<< ret = >> -StatementOrStament(sStat1, sStat2) ::= << +StatementOrStatement(sStat1, sStat2) ::= << if ret.isLeft then >> -ExpressionOrStament(sExp1, sStat2) ::= << +ExpressionOrStatement(sExp1, sStat2) ::= << ret = if ret.isLeft then @@ -120,13 +115,13 @@ if ret.isLeft then ret = >> -StatementAndStament(sStat1, sStat2) ::= << +StatementAndStatement(sStat1, sStat2) ::= << if ret.isRight then >> -ExpressionAndStament(sExp1, sStat2) ::= << +ExpressionAndStatement(sExp1, sStat2) ::= << ret = if ret.isRight then @@ -146,7 +141,7 @@ else ret = Right(0) >> -StatementExceptStament(sStat1, sStat2) ::= << +StatementExceptStatement(sStat1, sStat2) ::= << if ret.isRight then @@ -156,7 +151,7 @@ if ret.isRight then ret = Right(0) >> -ExpressionExceptStament(sExp1, sStat2) ::= << +ExpressionExceptStatement(sExp1, sStat2) ::= << ret = if ret.isRight then @@ -170,9 +165,9 @@ StatementExceptExpression(sStat1, sExp2) ::= << if ret.isRight then ret = () match - case Right(x) => + case Right(x) => Left(171) - case Left(x) => + case Left(x) => Right(0) >> @@ -188,7 +183,7 @@ while(ret.isRight && \<

nCount Print_AlphabetCheckFunc(sFuncName, arrsAlphaConBody) ::= << -def (str: Array[Byte]): Boolean = +def (str: Array[Byte]): Boolean = { var valid: Boolean = true var i: Int = 0 @@ -202,7 +197,7 @@ def (str: Array[Byte]): Boolean = -SingleValContraint(p, v) ::= "(

== )" +SingleValConstraint(p, v) ::= "(

== )" @@ -210,11 +205,11 @@ SingleValContraint(p, v) ::= "(

== )" stringContainsChar(sStrVal, p) ::= ".contains(

)" -RangeContraint(p, v1, v2, bMin, bMax) ::= "( \<=

&&

\<= )" +RangeConstraint(p, v1, v2, bMin, bMax) ::= "( \<=

&&

\<= )" -RangeContraint_val_MAX(p, v, bMin) ::= "(

>= )" +RangeConstraint_val_MAX(p, v, bMin) ::= "(

>= )" -RangeContraint_MIN_val(p, v, bMax) ::= "(

\<= )" +RangeConstraint_MIN_val(p, v, bMax) ::= "(

\<= )" AND_Constraint(sCon1, sCon2) ::= "( && )" @@ -242,18 +237,20 @@ call_base_type_func_exp(p, sFuncName) ::= "(

)" Sequence_OptionalChild(p, sAcc, sChName, sInnerStatement) ::= << -if

exist. then - +

match + case Some() => + + case None() => >> Sequence_optional_child_always_present_or_absent(p, sAcc, sChName, sErrCode, sPresOrAbs) ::= << -ret =

exist. == +ret =

.isDefined == ret = ; >> Sequence_optional_child_always_present_or_absent_expr(p, sAcc, sChName, sPresOrAbs) ::= << -(

exist. == ) +(

.isDefined == ) >> /* SEQUENCE end*/ @@ -261,10 +258,10 @@ Sequence_optional_child_always_present_or_absent_expr(p, sAcc, sChName, sPresOr /* CHOICE start*/ -Choice_OptionalChild(p, pLocal, sAcc, sChPresent, sInnerStatement) ::= << +Choice_OptionalChild(p, sPLocal, sAcc, sChPresent, sInnerStatement) ::= <<

match - case () => - + case () => + case _ => () >> @@ -278,7 +275,7 @@ Choice_child_always_absent_Exp(p, sAcc, sChPresent) ::= << choice_child(sChPresent, sChildBody, bAlwaysAbsent) ::= << case => - + >> choice(p, sAccess, arrsChildren, sErrCodeForInvalidCase) ::= << diff --git a/StgScala/uper_scala.stg b/StgScala/uper_scala.stg index d5592f2a2..f736acff5 100644 --- a/StgScala/uper_scala.stg +++ b/StgScala/uper_scala.stg @@ -4,17 +4,14 @@ rtlModuleName() ::= "" call_base_type_func_encode(p, sFuncName) ::= << (

, codec, false) match // uper:6 - case Right(retVal) => - ret = Right(retVal) - case Left(err) => - return Left(err) + case Right(_) => + case Left(err) => return Left(err) >> call_base_type_func_decode(p, sFuncName) ::= << -(codec) match // uper:13 - case Right(decData) => -

= decData - case Left(err) => - return Left(err) +// uper call_base_type_func_decode +val

= (codec) match // uper:13 + case Right(decData) => decData + case Left(err) => return Left(err) >> /*******************************************************/ @@ -31,23 +28,20 @@ EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrc @inline @cCode.inline val _REQUIRED_BITS_FOR_ENCODING = >> -EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_encode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << def (@annotation.unused : , @annotation.unused codec: UPER, bCheckConstraints: Boolean): Either[ErrorCode, Int] = //uper:35 { - var ret: Either[ErrorCode, Int] = Right(0) - }; separator="\n"> if bCheckConstraints then - ret = () - if(ret.isRight) { // classical design (scala 2), sContent could be empty - - } + () match + case Left(l) => return Left(l) + case Right(_) => + - - ret + Right(0) } >> @@ -55,15 +49,13 @@ EmitTypeAssignment_def_decode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrc }; separator="\n"> >> -EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << +EmitTypeAssignment_decode(sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp, bReqBytesForEncodingIsZero, bBsIsUnreferenced, bVarNameIsUnreferenced, soInitFuncName) ::= << def (@annotation.unused codec: UPER): Either[ErrorCode, ] = // uper:58 -{ - var pVal: = () - +{ }; separator="\n"> - + (pVal) match // uper:68 case Left(l) => Left(l) @@ -82,11 +74,11 @@ if !codec.appendByte(

arr()) then InternalItem_oct_str_decode(p, sAcc, i, sErrCode) ::=<< if !codec.readByte(

arr()) then - ret = Left() + return Left() >> PrintAlphabet2(arrnCharSet) /*nogen*/::= << -val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">) +val allowedCharSet: Array[Byte] = Array(}; wrap, anchor, separator=",">) >> InternalItem_string_with_alpha_encode(p, sErrCode, td/*:FE_StringTypeDefinition*/, i, nLastItemIndex, arrnAlphabetAsciiCodes, nAlphabetLength, nCharIndexSize) ::=<< @@ -116,7 +108,7 @@ codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraint_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -

= codec.decodeConstrainedWholeNumber(, ) // uper:122 +val

= codec.decodeConstrainedWholeNumber(, ) // uper:122 >> /*case: Positive fully constraint A:: = INTEGER (5..20) */ @@ -125,34 +117,38 @@ codec.encodeConstrainedWholeNumber(

, , ) >> IntFullyConstraintPos_decode(p, nMin, nMax, nBits, sSsuffix, sErrCode) ::= << -

= codec.decodeConstraintPosWholeNumber(, ) // uper:135 +val

= codec.decodeConstrainedPosWholeNumber(, ) // uper:135 >> /*case: A :: = INTEGER */ -IntUnconstraint_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnconstrainedWholeNumber(

)" -IntUnconstraint_decode(p, sErrCode, bCoverageIgnore) ::= << -

= codec.decodeUnconstrainedWholeNumber() // uper:145 +IntUnconstrained_encode(p, sErrCode, bCoverageIgnore) ::= "codec.encodeUnconstrainedWholeNumber(

)" +IntUnconstrained_decode(p, sErrCode, bCoverageIgnore) ::= << +val

= codec.decodeUnconstrainedWholeNumber() // uper:145 >> /*case: A :: = INTEGER(MIN..5) */ -IntUnconstraintMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnconstrainedWholeNumber(

)" -IntUnconstraintMax_decode(p, nMax, soCheckExp, sErrCode) ::= << +IntUnconstrainedMax_encode(p, nMax, soCheckExp, sErrCode) ::= "codec.encodeUnconstrainedWholeNumber(

)" +IntUnconstrainedMax_decode(p, nMax, soCheckExp, sErrCode) ::= << if !codec.decodeUnconstrainedWholeNumber() then // TODO meth does not return a boolean value...? - ret = if then 0 else + + if ! then return Left() + + return Left() + >> /*case: A:: = INTEGER (-5..MAX) */ -IntSemiConstraint_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstraintWholeNumber(

, )" +IntSemiConstraint_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstrainedWholeNumber(

, )" IntSemiConstraint_decode(p, nMin, sErrCode) ::= << -if !codec.decodeSemiConstraintWholeNumber() then - ret = +if !codec.decodeSemiConstrainedWholeNumber() then + return Left() >> /*case: A:: = INTEGER (5..MAX) */ -IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstraintPosWholeNumber(

, )" +IntSemiConstraintPos_encode(p, nMin, sErrCode) ::= "codec.encodeSemiConstrainedPosWholeNumber(

, )" IntSemiConstraintPos_decode(p, nMin, sErrCode) ::= << -if !codec.decodeSemiConstraintPosWholeNumber() then - ret = +if !codec.decodeSemiConstrainedPosWholeNumber() then + return Left() >> /*case: A:: = INTEGER (5..5) */ @@ -161,7 +157,7 @@ IntNoneRequired_encode(p, nConst, sErrCode) ::=<< ; // NOP >> IntNoneRequired_decode(p, nConst, sErrCode) ::= << -

= +val

= >> /*case: A:: = INTEGER (5..40,...) */ @@ -177,11 +173,11 @@ IntRootExt_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< /* read extension bit*/ val success = codec.readBit(extBit) if success then - if extBit == false then /* ext bit is zero ==> value is expecteted with root range*/ + if extBit == false then /* ext bit is zero ==> value is expected with root range*/ - else - - else + else + + else ret = } >> @@ -191,10 +187,10 @@ IntRootExt2_encode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::=<< if then codec.appendBitZero() /* write extension bit, value within root range, so ext bit is zero */ -else - /* value is not within root range, so ext bit is one and value is encoded as uncostraint */ - codec.appendBitOne() - +else + /* value is not within root range, so ext bit is one and value is encoded as unconstrained */ + codec.appendBitOne() + >> IntRootExt2_decode(p, nMin, sRootBaseConstraint, sIntBody, sErrCode) ::="" @@ -207,18 +203,18 @@ codec.appendBit(

) >> Boolean_decode(p, sErrCode) ::= << -

= codec.readBit() // uper:225 +val

= codec.readBit() // uper:225 >> Real_encode(p, sSuffix, sErrCode) ::= "codec.encodeReal(

)" Real_decode(p, sSuffix, sErrCode) ::= << -

= codec.decodeReal().toDouble // uper:234 +val

= codec.decodeReal().toDouble // uper:234 >> ObjectIdentifier_encode(p, sErrCode) ::= "codec.ObjectIdentifier_encode(

);" ObjectIdentifier_decode(p, sErrCode) ::= << if !codec.ObjectIdentifier_decode() then // uper:234 TODO - ret = + return Left() >> RelativeOID_encode(p, sErrCode) ::= "codec.RelativeOID_encode(

);" @@ -237,21 +233,17 @@ Enumerated_item_encode(p, sName, nIndex, nLastItemIndex) ::= << case => codec.encodeConstrainedWholeNumber(, 0, ) >> - Enumerated_item_decode(p, sName, nIndex, nLastItemIndex) ::= << -case => -

= +case => >> Enumerated_encode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= <<

match // uper:270 - case _ => - ret = Left() >> Enumerated_decode(p, td/*:FE_EnumeratedTypeDefinition*/, arrsItem, nMin, nMax, nBits, sErrCode, nLastItemIndex, sFirstItemName) ::= << -codec.decodeConstrainedWholeNumber(0, ) match // uper:277 +val

= codec.decodeConstrainedWholeNumber(0, ) match // uper:277 case _ => return Left() @@ -264,30 +256,20 @@ case () => codec.encodeConstrainedWholeNumber(, 0, ) >> + choice_child_decode(p, sAcc, sChildID, nChildIndex, nIndexSizeInBits, nLastItemIndex, sChildContent, sChildName, sChildTypeDef, sChoiceTypeName, sChildInitExpr, bIsSequence, bIsEnum) ::= << case => - - var : = () - - - var : = - - var : = - - -

= () + () >> choice_encode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= <<

match // uper:310 }; separator="\n"> - case _ => - ret = Left() >> choice_decode(p, sAcc, arrsChildren, nLastItemIndex, sChoiceIndexName, sErrCode, td/*:FE_ChoiceTypeDefinition*/, nIndexSizeInBits) ::= << -codec.decodeConstrainedWholeNumber(0, ) match // uper:317 +val

= codec.decodeConstrainedWholeNumber(0, ) match // uper:317 }; separator="\n"> case _ => return Left() @@ -296,64 +278,73 @@ codec.decodeConstrainedWholeNumber(0, ) match // uper:317 /* CHOICE END*/ /* SEQUENCE START */ -sequence_presence_bit_encode(p, sAcc, sChName, sErrCode) ::= << -codec.appendBit(

exist.) +sequence_presence_bit_encode(p, sAcc, sChName, soExistVar, sErrCode) ::= << +codec.appendBit(

.isDefined) >> - -sequence_presence_bit_decode(p, sAcc, sChName, sErrCode) ::= << -

exist. = codec.readBit() // uper:332 +sequence_presence_bit_decode(p, sAcc, sChName, soExistVar, sErrCode) ::= << +val = codec.readBit() >> -sequence_presence_bit_fix_encode(p, sAcc, sChName, sErrCode, sVal) ::= << +sequence_presence_bit_fix_encode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= << codec.appendBit() >> -sequence_presence_bit_fix_decode(p, sAcc, sChName, sErrCode, sVal) ::= << - +sequence_presence_bit_fix_decode(p, sAcc, sChName, soExistVar, sErrCode, sVal) ::= << + >> sequence_mandatory_child_encode(sChName, sChildContent) ::= << -/*Encode */ +/*Encode sequence_mandatory_child_encode */ >> sequence_mandatory_child_decode(sChName, sChildContent) ::= << -/* Decode */ +/* Decode sequence_mandatory_child_decode */ >> - -sequence_optional_child_encode(p, sAcc, sChName, sChildContent) ::= << +sequence_optional_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << /*Encode */ -if

exist. then - +

match + case Some() => + + case None() => >> -sequence_optional_child_decode(p, sAcc, sChName, sChildContent) ::= << +sequence_optional_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef) ::= << /*Decode */ -if

exist. then - +val

_ = + if then + + Some() + else None[]() >> -sequence_default_child_encode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << - +sequence_default_child_encode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << + >> -sequence_default_child_decode(p, sAcc, sChName, sChildContent, sInitWithDefaultValue) ::= << +sequence_default_child_decode(p, sAcc, sChName, sChildContent, soExistVar, soChildExpr, sChildTypedef, sInitWithDefaultValue) ::= << /*Decode */ -if

exist. then - -else - +val

_ = + if then + + Some() + else + +>> + +sequence_build(p, sTypeDefName, arrsChildren) ::= << +val

= () >> /* SEQUENCE END */ -loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< +loopFixedItem (i, fixedSize, sInternalItem)::= /*nogen*/<< = 0 while( \< .asInstanceOf[Int]) { @@ -365,16 +356,17 @@ while( \< .asInstanceOf[Int]) /* IA5String & Numeric String */ -str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << >> -str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << +val

=

() = 0x0 >> -str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +str_VarSize_encode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << nStringLength =

.indexOf(0x00) /*ret = nStringLength >= && nStringLength \<= ;*/ codec.encodeConstrainedWholeNumber(nStringLength, , ) @@ -382,8 +374,9 @@ codec.encodeConstrainedWholeNumber(nStringLength, , ) >> -str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << -nStringLength = codec.decodeConstrainedWholeNumberInt(, ) // uper:418 +str_VarSize_decode(p, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, soInitExpr) ::= << +val

= +nStringLength = codec.decodeConstrainedWholeNumberInt(, )

(nStringLength) = 0 = 0 @@ -391,66 +384,67 @@ nStringLength = codec.decodeConstrainedWholeNumberInt(, ) // >> /* SEQUENCE OF & OCTET STRING*/ -seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +seqOf_FixedSize_encode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << >> -seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize) ::= << +seqOf_FixedSize_decode(p, sTasName, i, sInternalItem, nFixedSize, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr) ::= << +val

= (, Array.fill()()) >> -seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << +seqOf_VarSize_encode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << codec.encodeConstrainedWholeNumber(

nCount, , ) >> -seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sErrCode) ::= << -

nCount = codec.decodeConstrainedWholeNumber(, ).toInt // uper:444 +seqOf_VarSize_decode(p, sAcc, sTasName, i, sInternalItem, nSizeMin, nSizeMax, nSizeInBits, nIntItemMinSize, nIntItemMaxSize, nAlignSize, sChildInitExpr, sErrCode) ::= << +val

_nCount = codec.decodeConstrainedWholeNumber(, ).toInt +val

= (

_nCount.toInt, Array.fill(

_nCount.toInt)()) = 0 - + >> -octect_FixedSize_encode(p, sAcc, nFixedSize) ::= << -codec.encodeOctetString_no_length(

arr, .asInstanceOf[Int]) +octet_FixedSize_encode(sTypeDefName, p, sAcc, nFixedSize) ::= << +codec.encodeOctetString_no_length(

arr, .toInt) >> -octect_FixedSize_decode(p, sAcc, nFixedSize) ::= << -/* TODO copyToArray? */ -codec.decodeOctetString_no_length().copyToArray(

arr) // uper:460 +octet_FixedSize_decode(sTypeDefName, p, sAcc, nFixedSize) ::= << +val

= (codec.decodeOctetString_no_length()) >> -octect_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << codec.encodeConstrainedWholeNumber(

nCount, , ) -codec.encodeOctetString_no_length(

arr,

nCount.asInstanceOf[Int]) +codec.encodeOctetString_no_length(

arr,

nCount.toInt) >> -octect_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << +octet_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, nSizeInBits, sErrCode) ::= << // decode length -

nCount = codec.decodeConstrainedWholeNumber(, ) // uper:475 +val

_nCount = codec.decodeConstrainedWholeNumber(, ) // decode payload -/* TODO copyToArray? */ -codec.decodeOctetString_no_length(

nCount.toInt).copyToArray(

arr) // uper:483 +val

_arr = codec.decodeOctetString_no_length(

_nCount.toInt) +val

= (

_nCount,

_arr) >> /* BIT STRING*/ -bitString_FixSize_encode(p, sAcc, nFixedSize, sErrCode) ::= << -assert(.asInstanceOf[Int] >= 0) // overflow may happen during cast +bitString_FixSize_encode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= << +assert(.toInt >= 0) // overflow may happen during cast codec.appendBitsMSBFirst(

arr, .toInt) ->> -bitString_FixSize_decode(p, sAcc, nFixedSize, sErrCode) ::= << -/* TODO copyToArray instead of assigning*/ -codec.readBits(.toInt).copyToArray(

arr) // uper:496 +>> +bitString_FixSize_decode(sTypeDefName, p, sAcc, nFixedSize, sErrCode) ::= << +val

= (codec.readBits(.asInstanceOf[Int])) >> -bitString_VarSize_encode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +bitString_VarSize_encode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << codec.encodeConstrainedWholeNumber(

nCount, , ) - + >> -bitString_VarSize_decode(p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << -

nCount = codec.decodeConstrainedWholeNumber(, ) // uper:509 - +bitString_VarSize_decode(sTypeDefName, p, sAcc, nSizeMin, nSizeMax, sErrCode, nSizeInBits) ::= << +val

_nCount = codec.decodeConstrainedWholeNumber(, ) +val

_arr = codec.readBits(

_nCount.asInstanceOf[Int]) +val

= (

_nCount,

_arr) >> @@ -522,7 +516,7 @@ Fragmentation_sqf_encode(p, sAcc, sInternalItem, nIntItemMaxSize, nSizeMin, nSiz = 0 = 0 = 0 -while ( >= 0x4000 && \< (asn1SccSint)strlen(

)

nCount) +while ( >= 0x4000 && \< (asn1SccSint)strlen(

)

nCount) { if >= 0x10000 then = 0x10000 @@ -533,10 +527,10 @@ while ( >= 0x4000 && \< (a else if >= 0x8000 then = 0x8000 codec.encodeConstrainedWholeNumber(0xC2, 0, 0xFF) - else + else = 0x4000 codec.encodeConstrainedWholeNumber(0xC1, 0, 0xFF) - + codec.appendBitsMSBFirst(

arr[/8], .asInstanceOf[Int]) @@ -565,7 +559,7 @@ codec.appendBitsMSBFirst(

arr[/8], .toIn while( \< ( + ).asInstanceOf[Int]) { - += 1 + += 1 } >> @@ -575,7 +569,7 @@ FixedSize_Fragmentation_sqf_64K_decode(p, sAcc,sCurOffset, sCurBlockSize, sBlock //we expect to decode Blocks and each block must contain 64K elements. Each block must begin with the byte 0xC4 = 0x10000; = 0; -*pErrCode = ; +*pErrCode = ; for( = 0; ret && \< ; ++) { ret = codec.decodeConstrainedWholeNumber(, 0, 0xFF) val check = (ret == 0) && ( == 0xC4); @@ -676,10 +670,10 @@ while(( & 0xC0) == 0xC0) { = 0x8000 else if == 0xC1 then = 0x4000 - else + else return Left() - if + > then + if + > then return Left() @@ -705,15 +699,15 @@ if (( & 0x80) > 0) then var len2 = 0; \<\<= 8 len2 = codec.decodeConstrainedWholeNumber(0, 0xFF).toInt // uper:780 - + |= len2; - &= 0x7FFF; + &= 0x7FFF; if ( + \<= ) then return Left() -if(!codec.readBits(&

arr[/8], .asInstanceOf[Int])) // TODO remove adress of operator +if(!codec.readBits(&

arr[/8], .asInstanceOf[Int])) // TODO remove address of operator return @@ -735,7 +729,7 @@ if (( >= ) && ( \<= )) then

[] = 0x0 -else +else return Left() @@ -765,7 +759,7 @@ octet_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, nBit octet_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, nBits, nMinSize, nMaxSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; @@ -796,7 +790,7 @@ bit_string_containing_func_encode(p, sFuncName, sReqBytesForUperEncoding, sReqBi bit_string_containing_func_decode(p, sFuncName, sReqBytesForUperEncoding, sReqBitsForUperEncoding, nBits, nMinSize, nMaxSize) ::= << /*open new scope to declare some variables*/ -{ +{ /*decode to a temporary bitstream*/ static byte arr[]; BitStream bitStrm; @@ -816,6 +810,8 @@ sparkAnnotations_encode(sTypeDefName) ::= << sparkAnnotations_decode(sTypeDefName) ::= << >> +Null_declare(p) ::= "val

: NullType = 0" + decode_nullType(p) ::= << /*no encoding/decoding is required*/ >> diff --git a/StgScala/variables_scala.stg b/StgScala/variables_scala.stg index 633baead3..5bfa24d6d 100644 --- a/StgScala/variables_scala.stg +++ b/StgScala/variables_scala.stg @@ -57,16 +57,16 @@ PrintBitStringValue(td/*:FE_SizeableTypeDefinition*/,bIsFixedSize, arrsBits, nCo >> -PrintBitOrOctetStringValueAsCompoundLitteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << +PrintBitOrOctetStringValueAsCompoundLiteral(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, arruBytes, nCount) ::= << (){.nCount = , .arr = {}; separator=", ">}} // variables:61 >> -PrintOctetArrayAsCompoundLitteral(arruBytes) ::= << +PrintOctetArrayAsCompoundLiteral(arruBytes) ::= << (const byte[]){}; wrap, anchor, separator=", ">} >> -PrintBitArrayAsCompoundLitteral(arruBits) ::= << +PrintBitArrayAsCompoundLiteral(arruBits) ::= << SYNTAX ERROR >> @@ -192,9 +192,9 @@ PrintSequenceOfValue(td/*:FE_SizeableTypeDefinition*/, bIsFixedSize, nLength, ar { .nCount = , - .arr = + .arr = { - }; separator=",\n"> + }; separator=",\n"> } } >> diff --git a/StgScala/xer_scala.stg b/StgScala/xer_scala.stg index b12f6cc4e..c632d9ec1 100644 --- a/StgScala/xer_scala.stg +++ b/StgScala/xer_scala.stg @@ -9,14 +9,14 @@ const int = ; EmitTypeAssignment_def_encode(sVarName, sStar, sFuncName, sTypeDefName, arrsErrcodes, bEmptyEncodingSpace, nMaxBytesInXER, soSparkAnnotations) ::= << -#define _REQUIRED_BYTES_FOR_XER_ENCODING +#define _REQUIRED_BYTES_FOR_XER_ENCODING flag (const , ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints); flag _aux(const , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints); >> -EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp) ::= << +EmitTypeAssignment_encode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp) ::= << flag _aux(const , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode, flag bCheckConstraints) { flag ret = TRUE; @@ -37,7 +37,7 @@ flag _aux(const , const char* xmlTag, - + return ret; } @@ -53,7 +53,7 @@ flag ( , ByteStream* pByteStrm, int* p flag _aux( , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode); >> -EmitTypeAssignment_decode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitilialExp) ::= << +EmitTypeAssignment_decode(sTasName, sVarName, sStar, sFuncName, soIValidFuncName, sTypeDefName, arrsLocalVariables, sContent, soSparkAnnotations, sInitialExp) ::= << flag _aux( , const char* xmlTag, ByteStream* pByteStrm, int* pErrCode) { flag ret = TRUE; @@ -240,7 +240,7 @@ SequenceOf_encode(p, sAcc, sTag, nLevel, sI, nSizeMax, sChildBody, bFixedSize, s ret = Xer_EncodeComplexElementStart(pByteStrm, , NULL, pErrCode, ); *pErrCode = ret ? 0 : ; if (ret) { - for(=0;(( \<

nCount) && ret);++) + for(=0;(( \<

nCount) && ret);++) { } @@ -393,7 +393,7 @@ CHOICE_no_tag_decode(p, sAcc, arrsChildren, sErrCode) ::=<< char nextTag[256]; ret = Xer_LA_NextElementTag(pByteStrm, nextTag); if (ret) { - + else { ret = FALSE; *pErrCode = ; diff --git a/StgVarious/generic.stg b/StgVarious/generic.stg index 50327914e..184d8c1c5 100644 --- a/StgVarious/generic.stg +++ b/StgVarious/generic.stg @@ -50,7 +50,7 @@ ImportedMod(sName, sCName, arrsTypes, arrsVars) ::= << {"$sName$":{"ImportedTypes": [$arrsTypes:{t|"$t$"};separator=","$], "ImportedVariables": [$arrsVars:{t|"$t$"};separator=","$]}} >> -TasXml(sName, nLine, nPos, sType, sCName, sAssigOp, sContract, bAddedType) ::= << +TasXml(sName, nLine, nPos, sType, sCName, sAssignOp, sContract, bAddedType) ::= << types["$sName$"] = { "Line": $nLine$, "CharPositionInLine": $nPos$, "AddedType":$bAddedType$, "type": { $sType$ @@ -99,8 +99,8 @@ IA5StringType () ::= "IA5StringType" NumericStringType () ::= "NumericStringType" -AssigOpNormalType () ::= "=" -AssigOpSpecialType () ::= "=" +AssignOpNormalType () ::= "=" +AssignOpSpecialType () ::= "=" EnumItem (sName, sCName, nVal, nLine, nPos, sCID) ::= << "$sName$": { diff --git a/StgVarious/icdtemplate_acn.stg b/StgVarious/icdtemplate_acn.stg index 21ef13170..ef1559a97 100644 --- a/StgVarious/icdtemplate_acn.stg +++ b/StgVarious/icdtemplate_acn.stg @@ -46,7 +46,7 @@ EmitRowWith3Dots() ::= << >> -EmmitFilePart2(sFileName, sAsn1Content) ::= << +EmitFilePart2(sFileName, sAsn1Content) ::= <<

File : $sFileName$

@@ -72,7 +72,7 @@ $arrsTases;separator="\n"$ >> -EmmitTass(sTypeContent) ::= << +EmitTass(sTypeContent) ::= << $sTypeContent$  
>> @@ -134,7 +134,7 @@ $arrsItems;separator="\n"$ EmitSequenceOrChoice(bIsAnonymousType, sTasName, sTasNameC, bHasAcnDef, sAsn1Kinf, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, arrsChildren, arrsParams, arrsComments) ::= << -
+ @@ -189,7 +189,7 @@ $arrsChildren;separator="\n"$ >> -EmmitSeqOrChoiceRow(sCssClass, nIndex, sName, sComment, sPresentWhen, sType, sConstraint, sMin, sMax, noAlignToNextSize, soUnit) ::= << +EmitSeqOrChoiceRow(sCssClass, nIndex, sName, sComment, sPresentWhen, sType, sConstraint, sMin, sMax, noAlignToNextSize, soUnit) ::= << $if(noAlignToNextSize)$ @@ -217,12 +217,12 @@ $endif$ >> -EmmitSequencePreambleSingleComment(nIndex, sOptChildName) ::= << +EmitSequencePreambleSingleComment(nIndex, sOptChildName) ::= <<
  • bit$nIndex$ == 1 ⇒ $sOptChildName$ is present
  • >> -EmmitSequencePreambleComment(arrsOptWihtNoPresentWhenChildren) ::= << +EmitSequencePreambleComment(arrsOptWihtNoPresentWhenChildren) ::= << Special field used by ACN to indicate the presence/absence of optional fields that do not have the present when property. $if(arrsOptWihtNoPresentWhenChildren)$
    @@ -232,11 +232,11 @@ $arrsOptWihtNoPresentWhenChildren;separator="\n"$ $endif$ >> -EmmitChoiceIndexComment() ::= << +EmitChoiceIndexComment() ::= << Special field used by ACN to indicate which choice alternative is present. >> -EmmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, sMax) ::= << +EmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, sMax) ::= << @@ -249,14 +249,14 @@ EmmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, >> -EmmitSeqChild_RefType(sRefName, sRefNameC) ::= << +EmitSeqChild_RefType(sRefName, sRefNameC) ::= << $sRefName$ >> EmitPrimitiveType(bIsAnonymousType, sTasName, sTasNameC, bHasAcnDef, sAsnKindName, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, sAsn1Constraints, sMinBits, sMaxBits, arrsParams, arrsComments, soUnit) ::= << - +
    $nIndex$ $sName$
    @@ -624,12 +624,12 @@ font.enumeration_name RootHtml(arrsFiles1, arrsFiles2, bAcnParamsMustBeExplained, arrsFiles3, sCssFileName) ::= << - +ICD - + The following tables describe the binary encodings of the data model using the ACN Encoding Rules. diff --git a/StgVarious/icdtemplate_uper.stg b/StgVarious/icdtemplate_uper.stg index 1e8e6e437..2af7ddc2b 100644 --- a/StgVarious/icdtemplate_uper.stg +++ b/StgVarious/icdtemplate_uper.stg @@ -107,7 +107,7 @@ $arrsItems;separator="\n"$ // applicable to Integers, booleans, reals EmitPrimitiveType(sColor, sTasName, sTasNameC, sAsnKindName, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, sAsn1Constraints, sMinBits, sMaxBits, arrsCommentsm, soUnit) ::= << - +
    @@ -158,7 +158,7 @@ $endif$ EmitSequence(sColor, sTasName, sTasNameC, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, arrsChildren, arrsComments) ::= << - +
    @@ -208,7 +208,7 @@ $arrsChildren;separator="\n"$ -EmmitSeqChild_RefType(sRefName, sRefNameC) ::= << +EmitSeqChild_RefType(sRefName, sRefNameC) ::= << $sRefName$ >> @@ -216,7 +216,7 @@ EmmitSeqChild_RefType(sRefName, sRefNameC) ::= << OddRow() ::= "OddRow" EvenRow() ::= "EvenRow" -EmmitSequenceChild(sCssClass, nIndex, sName, sComment, sOptionality, sType, sConstraint, sMin, sMax, soUnit) ::= << +EmitSequenceChild(sCssClass, nIndex, sName, sComment, sOptionality, sType, sConstraint, sMin, sMax, soUnit) ::= << @@ -231,11 +231,11 @@ EmmitSequenceChild(sCssClass, nIndex, sName, sComment, sOptionality, sType, sCon >> -EmmitSequencePreambleSingleComment(nIndex, sOptChildName) ::= << +EmitSequencePreambleSingleComment(nIndex, sOptChildName) ::= <<
  • bit$nIndex$ == 1 ⇒ $sOptChildName$ is present
  • >> -EmmitSequencePreambleComment(arrsOptChildren) ::= << +EmitSequencePreambleComment(arrsOptChildren) ::= << Special field used by PER to indicate the presence/absence of optional and default fields.
      @@ -247,7 +247,7 @@ $arrsOptChildren;separator="\n"$ /* *** CHOICE ****/ EmitChoice(sColor, sTasName, sTasNameC, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, arrsChildren, arrsComments) ::= << - +
    $nIndex$ $sName$
    @@ -293,7 +293,7 @@ $arrsChildren;separator="\n"$ >> -EmmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, sMax, soUnit) ::= << +EmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, sMax, soUnit) ::= << @@ -306,11 +306,11 @@ EmmitChoiceChild(sCssClass, nIndex, sName, sComment, sType, sConstraint, sMin, >> -EmmitChoiceIndexSingleComment(nIndex, sChildName) ::= << +EmitChoiceIndexSingleComment(nIndex, sChildName) ::= <<
  • $nIndex$ ⇒ $sChildName$
  • >> -EmmitChoiceIndexComment(arrsOptChildren) ::= << +EmitChoiceIndexComment(arrsOptChildren) ::= << Special field used by PER to indicate which choice alternative is present.
      @@ -322,7 +322,7 @@ $arrsOptChildren;separator="\n"$ /* *********** CHOICE END ********** */ /* *********** SEQUENCE OF, OCTET STRING etc ********** */ EmitSizeable(sColor, sTasName, sTasNameC, sKind, sMinBytes, sMaxBytes, sMaxBitsExplained, sCommentLine, arrsRows, arrsComments) ::= << - +
    $nIndex$ $sName$
    @@ -377,13 +377,13 @@ EmitRowWith3Dots() ::= << -EmmitTass(sTypeContent) ::= << +EmitTass(sTypeContent) ::= << $sTypeContent$  
    >> -EmmitModule(sModName, arrsComments, arrsTases) ::= << +EmitModule(sModName, arrsComments, arrsTases) ::= <<

    Module : $sModName$

    @@ -394,14 +394,14 @@ $arrsTases;separator="\n"$
     >>
     
     
    -EmmitFile(sAsnFileName, arrsModules) ::= <<
    +EmitFile(sAsnFileName, arrsModules) ::= <<
     

    Asn1 file : $sAsnFileName$

    $arrsModules;separator="\n"$
    >> -EmmitFilePart2(sFileName, sAsn1Content) ::= << +EmitFilePart2(sFileName, sAsn1Content) ::= <<

    File : $sFileName$

    @@ -415,7 +415,7 @@ RootHtml(arrsFiles1, arrsFiles2, bIntegerSizeMustBeExplained, bRealSizeMustBeExp ICD -