diff --git a/cangjie_libs/compress/zlib.cjd b/cangjie_libs/compress/zlib.cjd new file mode 100644 index 0000000000000000000000000000000000000000..5dfe07c7912e90404b8d4ec92f0d5a297eef5749 --- /dev/null +++ b/cangjie_libs/compress/zlib.cjd @@ -0,0 +1,55 @@ +package compress.zlib + +// --------------------------- +// -----classes +// --------------------------- +public class CompressInputStream <: InputStream { + public init(inputStream: InputStream, wrap!: WrapType = DeflateFormat, compressLevel!: CompressLevel = DefaultCompression, bufLen!: Int64 = 512) + public func close(): Unit + public func read(outBuf: Array): Int64 +} + +public class CompressOutputStream <: OutputStream { + public init(outputStream: OutputStream, wrap!: WrapType = DeflateFormat, compressLevel!: CompressLevel = DefaultCompression, bufLen!: Int64 = 512) + public func close(): Unit + public func flush(): Unit + public func write(inBuf: Array): Unit +} + +public class DecompressInputStream <: InputStream { + public init(inputStream: InputStream, wrap!: WrapType = DeflateFormat, bufLen!: Int64 = 512) + public func close(): Unit + public func read(outBuf: Array): Int64 +} + +public class DecompressOutputStream <: OutputStream { + public init(outputStream: OutputStream, wrap!: WrapType = DeflateFormat, bufLen!: Int64 = 512) + public func close(): Unit + public func flush(): Unit + public func write(inBuf: Array): Unit +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum CompressLevel { + BestCompression + BestSpeed + DefaultCompression +} + +public enum WrapType { + DeflateFormat + GzipFormat +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ZlibException <: Exception { + public init(message: String) +} + + diff --git a/cangjie_libs/crypto/crypto.cjd b/cangjie_libs/crypto/crypto.cjd new file mode 100644 index 0000000000000000000000000000000000000000..f40e7f521b0b9c3a9d5dd44dfcd0a7db0571ea40 --- /dev/null +++ b/cangjie_libs/crypto/crypto.cjd @@ -0,0 +1,85 @@ +package crypto.crypto + +// --------------------------- +// -----classes +// --------------------------- +public class SecureRandom { + public init(priv!: Bool = false) + public func nextBool(): Bool + public func nextBytes(length: Int32): Array + public func nextFloat16(): Float16 + public func nextFloat32(): Float32 + public func nextFloat64(): Float64 + public func nextGaussianFloat16(mean!: Float16 = 0.0, sigma!: Float16 = 1.0): Float16 + public func nextGaussianFloat32(mean!: Float32 = 0.0, sigma!: Float32 = 1.0): Float32 + public func nextGaussianFloat64(mean!: Float64 = 0.0, sigma!: Float64 = 1.0): Float64 + public func nextInt16(): Int16 + public func nextInt32(): Int32 + public func nextInt16(max: Int16): Int16 + public func nextInt32(max: Int32): Int32 + public func nextInt64(): Int64 + public func nextInt64(max: Int64): Int64 + public func nextInt8(): Int8 + public func nextInt8(max: Int8): Int8 + public func nextUInt16(): UInt16 + public func nextUInt16(max: UInt16): UInt16 + public func nextUInt32(): UInt32 + public func nextUInt32(max: UInt32): UInt32 + public func nextUInt64(): UInt64 + public func nextUInt64(max: UInt64): UInt64 + public func nextUInt8(): UInt8 + public func nextUInt8(max: UInt8): UInt8 +} + +public class SM4 <: BlockCipher { + public init( optMode: OperationMode, key: Array, iv!: Array = Array(), paddingMode!: PaddingMode = PaddingMode.PKCS7Padding, aad!: Array = Array(), tagSize!: Int64 = SM4_GCM_TAG_SIZE ) + public prop aad: Array + public prop blockSize: Int64 + public prop keySize: Int64 + public prop key: Array + public prop optMode: OperationMode + public prop paddingMode: PaddingMode + public prop iv: Array + public prop ivSize: Int64 + public prop tagSize: Int64 + public func encrypt(input: Array): Array + public func encrypt(input: InputStream, output: OutputStream) + public func decrypt(input: Array): Array + public func decrypt(input: InputStream, output: OutputStream) +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class SecureRandomException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct OperationMode <: ToString & Equatable { + public static let ECB + public static let CBC + public static let OFB + public static let CFB + public static let CTR + public static let GCM + public let mode: String + public override func toString(): String + public operator override func ==(other: OperationMode): Bool + public operator override func !=(other: OperationMode): Bool +} + +public struct PaddingMode <: Equatable { + public static let NoPadding + public static let PKCS7Padding + public let paddingType: Int64 + public operator override func ==(other: PaddingMode): Bool + public operator override func !=(other: PaddingMode): Bool +} + + diff --git a/cangjie_libs/crypto/digest.cjd b/cangjie_libs/crypto/digest.cjd new file mode 100644 index 0000000000000000000000000000000000000000..438cce4bf895289876daccdf9ace903b60b5cf9c --- /dev/null +++ b/cangjie_libs/crypto/digest.cjd @@ -0,0 +1,106 @@ +package crypto.digest + +// --------------------------- +// -----classes +// --------------------------- +public class HMAC <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init(key: Array, digest: () -> Digest) + public init(key: Array, algorithm: HashType) + public static func equal(mac1: Array, mac2: Array): Bool + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class MD5 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SHA1 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SHA224 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SHA256 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SHA384 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SHA512 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + +public class SM3 <: Digest { + public prop blockSize: Int64 + public prop size: Int64 + public init() + public func finish(): Array + public func reset(): Unit + public func write(buffer: Array): Unit +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class CryptoException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct HashType <: ToString & Equatable { + public static prop MD5: HashType + public static prop SHA1: HashType + public static prop SHA224: HashType + public static prop SHA256: HashType + public static prop SHA384: HashType + public static prop SHA512: HashType + public static prop SM3: HashType + public func toString(): String + public operator override func ==(other: HashType): Bool + public operator override func !=(other: HashType): Bool +} + + diff --git a/cangjie_libs/crypto/keys.cjd b/cangjie_libs/crypto/keys.cjd new file mode 100644 index 0000000000000000000000000000000000000000..86f69c80125a3b4578ac4e768b230160cc469d72 --- /dev/null +++ b/cangjie_libs/crypto/keys.cjd @@ -0,0 +1,113 @@ +package crypto.keys + +// --------------------------- +// -----classes +// --------------------------- +public class ECDSAPrivateKey <: PrivateKey { + public init(curve: Curve) + public static func decodeDer(blob: DerBlob): ECDSAPrivateKey + public static func decodeDer(blob: DerBlob, password!: ?String): ECDSAPrivateKey + public static func decodeFromPem(text: String): ECDSAPrivateKey + public static func decodeFromPem(text: String, password!: ?String): ECDSAPrivateKey + public override func encodeToDer(): DerBlob + public func encodeToDer(password!: ?String): DerBlob + public override func encodeToPem(): PemEntry + public func sign(digest: Array): Array + public override func toString(): String +} + +public class ECDSAPublicKey <: PublicKey { + public init(pri: ECDSAPrivateKey) + public static func decodeDer(blob: DerBlob): ECDSAPublicKey + public static func decodeFromPem(text: String): ECDSAPublicKey + public override func encodeToDer(): DerBlob + public override func encodeToPem(): PemEntry + public override func toString(): String + public func verify(digest: Array, sig: Array): Bool +} + +public class RSAPrivateKey <: PrivateKey { + public init(bits: Int32) + public init(bits: Int32, e: BigInt) + public static func decodeDer(blob: DerBlob): RSAPrivateKey + public static func decodeDer(blob: DerBlob, password!: ?String): RSAPrivateKey + public static func decodeFromPem(text: String): RSAPrivateKey + public static func decodeFromPem(text: String, password!: ?String): RSAPrivateKey + public func decrypt(input: InputStream, output: OutputStream, padType!: PadOption): Unit + public override func encodeToDer(): DerBlob + public func encodeToDer(password!: ?String): DerBlob + public override func encodeToPem(): PemEntry + public func sign(hash: Digest, digest: Array, padType!: PadOption): Array + public override func toString(): String +} + +public class RSAPublicKey <: PublicKey { + public init(pri: RSAPrivateKey) + public static func decodeDer(blob: DerBlob): RSAPublicKey + public static func decodeFromPem(text: String): RSAPublicKey + public override func encodeToDer(): DerBlob + public override func encodeToPem(): PemEntry + public func encrypt(input: InputStream, output: OutputStream, padType!: PadOption): Unit + public override func toString(): String + public func verify(hash: Digest, digest: Array, sig: Array, padType!: PadOption): Bool +} + +public class SM2PrivateKey <: PrivateKey { + public init() + public static func decodeDer(blob: DerBlob): SM2PrivateKey + public static func decodeDer(blob: DerBlob, password!: ?String): SM2PrivateKey + public static func decodeFromPem(text: String): SM2PrivateKey + public static func decodeFromPem(text: String, password!: ?String): SM2PrivateKey + public func decrypt(input: Array): Array + public func encodeToDer(): DerBlob + public func encodeToDer(password!: ?String): DerBlob + public func encodeToPem(password!: ?String): PemEntry + public func encodeToPem(): PemEntry + public func sign(data: Array): Array + public override func toString(): String +} + +public class SM2PublicKey <: PublicKey { + public init(pri: SM2PrivateKey) + public static func decodeDer(blob: DerBlob): SM2PublicKey + public static func decodeFromPem(text: String): SM2PublicKey + public func encodeToDer(): DerBlob + public func encodeToPem(): PemEntry + public func encrypt(input: Array): Array + public override func toString(): String + public func verify(data: Array, sig: Array): Bool +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum Curve { + BP256 + BP320 + BP384 + BP512 + P224 + P256 + P384 + P521 +} + +public enum PadOption { + OAEP(OAEPOption) + PKCS1 + PSS(PSSOption) +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct OAEPOption { + public init(hash: Digest, mgfHash: Digest, label!: String = "") + public init(hash: Digest, mgfHash: Digest, label!: String = "") +} + +public struct PSSOption {} + + diff --git a/cangjie_libs/crypto/x509.cjd b/cangjie_libs/crypto/x509.cjd new file mode 100644 index 0000000000000000000000000000000000000000..256723f7706af70f0afc342719a3e8efe54fcd91 --- /dev/null +++ b/cangjie_libs/crypto/x509.cjd @@ -0,0 +1,259 @@ +package crypto.x509 + +// --------------------------- +// -----classes +// --------------------------- +public class X509Certificate <: Equatable & Hashable & ToString { + public prop dnsNames: Array + public prop emailAddresses: Array + public prop extKeyUsage: ExtKeyUsage + public prop issuer: X509Name + public prop IPAddresses: Array + public prop keyUsage: KeyUsage + public prop notAfter: DateTime + public prop notBefore: DateTime + public prop publicKey: PublicKey + public prop publicKeyAlgorithm: PublicKeyAlgorithm + public prop serialNumber: SerialNumber + public prop signature: Signature + public prop signatureAlgorithm: SignatureAlgorithm + public prop subject: X509Name + public init( certificateInfo: X509CertificateInfo, parent!: X509Certificate, publicKey!: PublicKey, privateKey!: PrivateKey, signatureAlgorithm!: ?SignatureAlgorithm = None) + public static func decodeFromDer(der: DerBlob): X509Certificate + public static func decodeFromPem(pem: String): Array + public func encodeToDer(): DerBlob + public func encodeToPem(): PemEntry + public override func hashCode(): Int64 + public static func systemRootCerts(): Array + public override func toString(): String + public func verify(verifyOption: VerifyOption): Bool + public override operator func !=(other: X509Certificate): Bool + public override operator func ==(other: X509Certificate): Bool +} + +public class X509CertificateRequest <: Hashable & ToString { + public prop IPAddresses: Array + public prop dnsNames: Array + public prop emailAddresses: Array + public prop publicKey: PublicKey + public prop publicKeyAlgorithm: PublicKeyAlgorithm + public prop signature: Signature + public prop signatureAlgorithm: SignatureAlgorithm + public prop subject: X509Name + public init( privateKey: PrivateKey, certificateRequestInfo!: ?X509CertificateRequestInfo = None, signatureAlgorithm!: ?SignatureAlgorithm = None) + public static func decodeFromDer(der: DerBlob): X509CertificateRequest + public static func decodeFromPem(pem: String): Array + public func encodeToDer(): DerBlob + public func encodeToPem(): PemEntry + public override func hashCode(): Int64 + public override func toString(): String +} + +public class X509Name <: ToString { + public prop commonName: ?String + public prop countryName: ?String + public prop email: ?String + public prop localityName: ?String + public prop organizationName: ?String + public prop organizationalUnitName: ?String + public prop provinceName: ?String + public init( countryName!: ?String = None, provinceName!: ?String = None, localityName!: ?String = None, organizationName!: ?String = None, organizationalUnitName!: ?String = None, commonName!: ?String = None, email!: ?String = None ) + public override func toString(): String +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum PublicKeyAlgorithm <: Equatable & ToString { + DSA + ECDSA + RSA + UnknownPublicKeyAlgorithm + public override func toString(): String + public override operator func !=(other: PublicKeyAlgorithm): Bool + public override operator func ==(other: PublicKeyAlgorithm): Bool +} + +public enum SignatureAlgorithm <: Equatable & ToString { + DSAWithSHA1 + DSAWithSHA256 + ECDSAWithSHA1 + ECDSAWithSHA256 + ECDSAWithSHA384 + ECDSAWithSHA512 + MD2WithRSA + MD5WithRSA + SHA1WithRSA + SHA256WithRSA + SHA384WithRSA + SHA512WithRSA + UnknownSignatureAlgorithm + public override func toString(): String + public override operator func !=(other: SignatureAlgorithm): Bool + public override operator func ==(other: SignatureAlgorithm): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class X509Exception <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface DHParamters <: Key { + static func decodeDer(blob: DerBlob): DHParamters + static func decodeFromPem(text: String): DHParamters + override func encodeToPem(): PemEntry +} + +public interface Key <: ToString { + static func decodeDer(encoded: DerBlob): Key + static func decodeFromPem(text: String): Key + func encodeToDer(): DerBlob + func encodeToPem(): PemEntry +} + +public interface PrivateKey <: Key { + static func decodeDer(blob: DerBlob): PrivateKey + static func decodeDer(blob: DerBlob, password!: ?String): PrivateKey + static func decodeFromPem(text: String): PrivateKey + static func decodeFromPem(text: String, password!: ?String): PrivateKey + func encodeToDer(password!: ?String): DerBlob + override func encodeToPem(): PemEntry + func encodeToPem(password!: ?String): PemEntry +} + +public interface PublicKey <: Key { + static func decodeDer(blob: DerBlob): PublicKey + static func decodeFromPem(text: String): PublicKey + override func encodeToPem(): PemEntry +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct DerBlob <: Equatable & Hashable { + public prop body: Array + public prop size: Int64 + public init(content: Array) + public override func hashCode(): Int64 + public override operator func !=(other: DerBlob): Bool + public override operator func ==(other: DerBlob): Bool +} + +public struct ExtKeyUsage <: ToString { + public static let AnyKey = 0u16 + public static let ClientAuth = 2u16 + public static let CodeSigning = 4u16 + public static let EmailProtection = 3u16 + public static let OCSPSigning = 5u16 + public static let ServerAuth = 1u16 + public static let TimeStamping = 6u16 + public init(keys: Array) + public override func toString(): String +} + +public struct KeyUsage <: ToString { + public static let CRLSign = 0x0002u16 + public static let CertSign = 0x0004u16 + public static let DataEncipherment = 0x0010u16 + public static let DecipherOnly = 0x0100u16 + public static let DigitalSignature = 0x0080u16 + public static let EncipherOnly = 0x0001u16 + public static let KeyAgreement = 0x0008u16 + public static let KeyEncipherment = 0x0020u16 + public static let NonRepudiation = 0x0040u16 + public init(keys: UInt16) + public override func toString(): String +} + +public struct Pem <: Collection & ToString { + public override prop size: Int64 + public Pem(private let items: Array) + public static func decode(text: String): Pem + public func encode(): String + public override func isEmpty(): Bool + public override func iterator(): Iterator + public override func toString(): String +} + +public struct PemEntry <: ToString { + public static let LABEL_CERTIFICATE = "CERTIFICATE" + public static let LABEL_CERTIFICATE_REQUEST = "CERTIFICATE REQUEST" + public static let LABEL_DH_PARAMETERS = "DH PARAMETERS" + public static let LABEL_EC_PARAMETERS = "EC PARAMETERS" + public static let LABEL_EC_PRIVATE_KEY = "EC PRIVATE KEY" + public static let LABEL_ENCRYPTED_PRIVATE_KEY = "ENCRYPTED PRIVATE KEY" + public static let LABEL_PRIVATE_KEY = "PRIVATE KEY" + public static let LABEL_PUBLIC_KEY = "PUBLIC KEY" + public static let LABEL_RSA_PRIVATE_KEY = "RSA PRIVATE KEY" + public static let LABEL_SM2_PRIVATE_KEY = "SM2 PRIVATE KEY" + public static let LABEL_X509_CRL = "X509 CRL" + public PemEntry( public let label: String, public let headers: Array<(String, String)>, public let body: ?DerBlob) + public let body: ?DerBlob + public let headers: Array<(String, String)> + public let label: String + public init(label: String, body: DerBlob) + public func encode(): String + public func header(name: String): Iterator + public override func toString(): String +} + +public struct SerialNumber <: Equatable & Hashable & ToString { + public init(length!: UInt8 = 16) + public override func hashCode(): Int64 + public override func toString(): String + public override operator func !=(other: SerialNumber): Bool + public override operator func ==(other: SerialNumber): Bool +} + +public struct Signature <: Equatable & Hashable { + public prop signatureValue: DerBlob + public override func hashCode(): Int64 + public override operator func !=(other: Signature): Bool + public override operator func ==(other: Signature): Bool +} + +public struct VerifyOption { + public var dnsName: String = "" + public var intermediates: Array = Array() + public var roots: Array = X509Certificate.systemRootCerts() + public var time: DateTime = DateTime.now() +} + +public struct X509CertificateInfo { + public var IPAddresses: Array + public var dnsNames: Array + public var emailAddresses: Array + public var extKeyUsage: ?ExtKeyUsage + public var keyUsage: ?KeyUsage + public var notAfter: DateTime + public var notBefore: DateTime + public var serialNumber: SerialNumber + public var subject: ?X509Name + public init( serialNumber!: ?SerialNumber = None, notBefore!: ?DateTime = None, notAfter!: ?DateTime = None, subject!: ?X509Name = None, dnsNames!: Array = Array(), emailAddresses!: Array = Array(), IPAddresses!: Array = Array(), keyUsage!: ?KeyUsage = None, extKeyUsage!: ?ExtKeyUsage = None) +} + +public struct X509CertificateRequestInfo { + public var IPAddresses: Array + public var dnsNames: Array + public var emailAddresses: Array + public var subject: ?X509Name + public init( subject!: ?X509Name = None, dnsNames!: Array = Array(), emailAddresses!: Array = Array(), IPAddresses!: Array = Array()) +} + + +// --------------------------- +// -----type +// --------------------------- +public type IP = Array {} + + diff --git a/cangjie_libs/encoding/base64.cjd b/cangjie_libs/encoding/base64.cjd new file mode 100644 index 0000000000000000000000000000000000000000..1bcb709044bf715132a8a8069f7a314bfe2c59c6 --- /dev/null +++ b/cangjie_libs/encoding/base64.cjd @@ -0,0 +1,8 @@ +package encoding.base64 + +// --------------------------- +// -----funcs +// --------------------------- +public func fromBase64String(data: String): Option> +public func toBase64String(data: Array): String + diff --git a/cangjie_libs/encoding/hex.cjd b/cangjie_libs/encoding/hex.cjd new file mode 100644 index 0000000000000000000000000000000000000000..ce205a8cfe325b630e7f69612503adc2bc6b1e19 --- /dev/null +++ b/cangjie_libs/encoding/hex.cjd @@ -0,0 +1,8 @@ +package encoding.hex + +// --------------------------- +// -----funcs +// --------------------------- +public func fromHexString(data: String): Option> +public func toHexString(data: Array): String + diff --git a/cangjie_libs/encoding/json.cjd b/cangjie_libs/encoding/json.cjd new file mode 100644 index 0000000000000000000000000000000000000000..340e54a8fcbaa6995efaeb504e34970d5e7b2bbb --- /dev/null +++ b/cangjie_libs/encoding/json.cjd @@ -0,0 +1,126 @@ +package encoding.json + +// --------------------------- +// -----classes +// --------------------------- +public class JsonArray <: JsonValue { + public init() + public init(list: ArrayList) + public init(list: Array) + public func add(jv: JsonValue): JsonArray + public func get(index: Int64): Option + public func getItems(): ArrayList + public func kind(): JsonKind + public func size(): Int64 + public func toJsonString(): String + public func toJsonString(depth: Int64, bracketInNewLine!: Bool = false, indent!: String = " "): String + public func toString(): String + public operator func [](index: Int64): JsonValue +} + +public class JsonBool <: JsonValue { + public init(bv: Bool) + public func getValue(): Bool + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + +public class JsonFloat <: JsonValue { + public init(fv: Float64) + public init(v: Int64) + public func getValue(): Float64 + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + +public class JsonInt <: JsonValue { + public init(iv: Int64) + public func getValue(): Int64 + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + +public class JsonNull <: JsonValue { + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + +public class JsonObject <: JsonValue { + public init() + public init(map: HashMap) + public func containsKey(key: String): Bool + public func get(key: String): Option + public func getFields(): HashMap + public func kind(): JsonKind + public func put(key: String, v: JsonValue): Unit + public func size(): Int64 + public func toJsonString(): String + public func toJsonString(depth: Int64, bracketInNewLine!: Bool = false, indent!: String = " "): String + public func toString(): String + public operator func [](key: String): JsonValue +} + +public class JsonString <: JsonValue { + public init(sv: String) + public func getValue(): String + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + +sealed abstract class JsonValue <: ToString { + public static func fromStr(s: String): JsonValue + public func asArray(): JsonArray + public func asBool(): JsonBool + public func asFloat(): JsonFloat + public func asInt(): JsonInt + public func asNull(): JsonNull + public func asObject(): JsonObject + public func asString(): JsonString + public func kind(): JsonKind + public func toJsonString(): String + public func toString(): String +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum JsonKind { + JsArray + JsBool + JsFloat + JsInt + JsNull + JsObject + JsString +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class JsonException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface ToJson { + static func fromJson(jv: JsonValue): DataModel + func toJson(): JsonValue +} + +extend DataModel <: ToJson { + public static func fromJson(jv: JsonValue): DataModel + public func toJson(): JsonValue +} + + diff --git a/cangjie_libs/encoding/json.stream.cjd b/cangjie_libs/encoding/json.stream.cjd new file mode 100644 index 0000000000000000000000000000000000000000..f0443cd2c8f62c7d5dedd91e7ecd13d45bfb24db --- /dev/null +++ b/cangjie_libs/encoding/json.stream.cjd @@ -0,0 +1,253 @@ +package encoding.json.stream + +// --------------------------- +// -----classes +// --------------------------- +public class JsonReader { + public init(inputStream: InputStream) + public func endArray(): Unit + public func endObject(): Unit + public func peek(): Option + public func readName(): String + public func readValue(): T where T <: JsonDeserializable + public func skip(): Unit + public func startArray(): Unit + public func startObject(): Unit +} + +public class JsonWriter { + public init(out: OutputStream) + public var writeConfig = WriteConfig.compact + public func endArray(): Unit + public func endObject(): Unit + public func flush(): Unit + public func jsonValue(value: String): JsonWriter + public func startArray(): Unit + public func startObject(): Unit + public func writeName(name: String): JsonWriter + public func writeNullValue(): JsonWriter + public func writeValue(v: T): JsonWriter where T <: JsonSerializable +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum JsonToken <: Equatable & Hashable { + BeginArray + BeginObject + EndArray + EndObject + JsonBool + JsonNull + JsonNumber + JsonString + Name + public func hashCode(): Int64 + public operator func !=(that: JsonToken): Bool + public operator func ==(that: JsonToken): Bool +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface JsonDeserializable { + static func fromJson(r: JsonReader): T +} + +extend BigInt <: JsonDeserializable { + public static func fromJson(r: JsonReader): BigInt +} + +extend Bool <: JsonDeserializable { + public static func fromJson(r: JsonReader): Bool +} + +extend DateTime <: JsonDeserializable { + public static func fromJson(r: JsonReader): DateTime +} + +extend Decimal <: JsonDeserializable { + public static func fromJson(r: JsonReader): Decimal +} + +extend Float16 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Float16 +} + +extend Float32 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Float32 +} + +extend Float64 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Float64 +} + +extend String <: JsonDeserializable { + public static func fromJson(r: JsonReader): String +} + +extend Int16 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Int16 +} + +extend Int32 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Int32 +} + +extend Int64 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Int64 +} + +extend Int8 <: JsonDeserializable { + public static func fromJson(r: JsonReader): Int8 +} + +extend IntNative <: JsonDeserializable { + public static func fromJson(r: JsonReader): IntNative +} + +extend UInt16 <: JsonDeserializable { + public static func fromJson(r: JsonReader): UInt16 +} + +extend UInt32 <: JsonDeserializable { + public static func fromJson(r: JsonReader): UInt32 +} + +extend UInt64 <: JsonDeserializable { + public static func fromJson(r: JsonReader): UInt64 +} + +extend UInt8 <: JsonDeserializable { + public static func fromJson(r: JsonReader): UInt8 +} + +extend UIntNative <: JsonDeserializable { + public static func fromJson(r: JsonReader): UIntNative +} + +extend Array <: JsonDeserializable> where T <: JsonDeserializable { + public static func fromJson(r: JsonReader): Array +} + +extend ArrayList <: JsonDeserializable> where T <: JsonDeserializable { + public static func fromJson(r: JsonReader): ArrayList +} + +extend Option <: JsonDeserializable> where T <: JsonDeserializable { + public static func fromJson(r: JsonReader): Option +} + +extend HashMap <: JsonDeserializable> where V <: JsonDeserializable, K <: String { + public static func fromJson(r: JsonReader): HashMap +} + +public interface JsonSerializable { + func toJson(w: JsonWriter): Unit +} + +extend BigInt <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Bool <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend DateTime <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Decimal <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Float16 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Float32 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Float64 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend String <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Int16 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Int32 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Int64 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Int8 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend IntNative <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend UInt16 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend UInt32 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend UInt64 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend UInt8 <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend UIntNative <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Array <: JsonSerializable where T <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend ArrayList <: JsonSerializable where T <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend Option <: JsonSerializable where T <: JsonSerializable { + public func toJson(w: JsonWriter): Unit +} + +extend HashMap <: JsonSerializable where V <: JsonSerializable, K <: String { + public func toJson(w: JsonWriter): Unit +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct WriteConfig { + public static let compact: WriteConfig + public static let pretty: WriteConfig + public mut prop dateTimeFormat: DateTimeFormat + public mut prop htmlSafe: Bool + public mut prop indent: String + public mut prop newline: String + public mut prop useSpaceAfterSeparators: Bool +} + + diff --git a/cangjie_libs/encoding/url.cjd b/cangjie_libs/encoding/url.cjd new file mode 100644 index 0000000000000000000000000000000000000000..fe67ab2f7cc2b7e258554d8da2ddd4a066441ea2 --- /dev/null +++ b/cangjie_libs/encoding/url.cjd @@ -0,0 +1,63 @@ +package encoding.url + +// --------------------------- +// -----classes +// --------------------------- +public class Form { + public init() + public init(queryComponent: String) + public func add(key: String, value: String): Unit + public func clone(): Form + public func get(key: String): Option + public func getAll(key: String): ArrayList + public func isEmpty(): Bool + public func remove(key: String): Unit + public func set(key: String, value: String): Unit + public func toEncodeString(): String +} + +public class URL <: ToString { + public prop fragment: ?String + public prop host: String + public prop hostName: String + public prop opaque: String + public prop path: String + public prop port: String + public prop query: ?String + public prop queryForm: Form + public prop rawFragment: ?String + public prop rawPath: String + public prop rawQuery: ?String + public prop rawUserInfo: UserInfo + public prop scheme: String + public prop userInfo: UserInfo + public init(scheme!: String, hostName!: String, path!: String) + public static func mergePaths(basePath: String, refPath: String): String + public static func parse(rawUrl: String): URL + public func isAbsoluteURL(): Bool + public func replace(scheme!: Option = None, userInfo!: Option = None, hostName!: Option = None, port!: Option = None, path!: Option = None, query!: Option = None, fragment!: Option = None): URL + public func resolveURL(ref: URL): URL + public func toString(): String +} + +public class UserInfo <: ToString { + public init() + public init(userName: String) + public init(userName: String, passWord: Option) + public init(userName: String, passWord: String) + public func password(): Option + public func toString(): String + public func username(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class UrlSyntaxException <: Exception { + public init(reason: String) + public init(input: String, reason: String) + public init(input: String, reason: String, pos: String) +} + + diff --git a/cangjie_libs/encoding/xml.cjd b/cangjie_libs/encoding/xml.cjd new file mode 100644 index 0000000000000000000000000000000000000000..1fcc2fa7552f1446865896352d85b03e99b6c534 --- /dev/null +++ b/cangjie_libs/encoding/xml.cjd @@ -0,0 +1,53 @@ +package encoding.xml + +// --------------------------- +// -----classes +// --------------------------- +public class XmlAttr <: ToString { + public mut prop content: String + public mut prop name: String + public init(name: String, content: String) + public func toString(): String +} + +public class XmlElement <: ToString { + public mut prop attributes: ArrayList + public prop attributesNum: Int64 + public mut prop childrenElements: ArrayList + public prop childrenNum: Int64 + public mut prop content: String + public prop isClosed: Bool + public mut prop name: String + public init(name: String, content: String) + public func toString(): String + public func toXmlString(): String +} + +public class XmlParser { + public init() + public init(handler: SaxHandler) + public func parse(str: String): Option +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class XmlException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface SaxHandler { + func characters(content: String): Unit + func endDocument(): Unit + func endElement(name: String): Unit + func startDocument(): Unit + func startElement(name: String, attrs: ArrayList): Unit +} + + diff --git a/cangjie_libs/fuzz/fuzz.cjd b/cangjie_libs/fuzz/fuzz.cjd new file mode 100644 index 0000000000000000000000000000000000000000..7b167c5006b073c668654521aaff17749ba2dfde --- /dev/null +++ b/cangjie_libs/fuzz/fuzz.cjd @@ -0,0 +1,114 @@ +package fuzz.fuzz + +// --------------------------- +// -----classes +// --------------------------- +public class DebugDataProvider <: FuzzDataProvider { + public override func consumeAll(): Array + public override func consumeAllAsAscii(): String + public override func consumeAllAsString(): String + public override func consumeAsciiString(maxLength: Int64): String + public override func consumeBool(): Bool + public override func consumeBools(count: Int64): Array + public override func consumeByte(): Byte + public override func consumeBytes(count: Int64): Array + public override func consumeFloat32(): Float32 + public override func consumeFloat64(): Float64 + public override func consumeInt16(): Int16 + public override func consumeInt16s(count: Int64): Array + public override func consumeInt32(): Int32 + public override func consumeInt32s(count: Int64): Array + public override func consumeInt64(): Int64 + public override func consumeInt64s(count: Int64): Array + public override func consumeInt8(): Int8 + public override func consumeInt8s(count: Int64): Array + public override func consumeRune(): Rune + public override func consumeString(maxLength: Int64): String + public override func consumeUInt16(): UInt16 + public override func consumeUInt16s(count: Int64): Array + public override func consumeUInt32(): UInt32 + public override func consumeUInt32s(count: Int64): Array + public override func consumeUInt64(): UInt64 + public override func consumeUInt64s(count: Int64): Array + public override func consumeUInt8(): UInt8 + public override func consumeUInt8s(count: Int64): Array + public static func wrap(dp: FuzzDataProvider): DebugDataProvider +} + +public class Fuzzer { + public init(targetFunction: (Array) -> Int32) + public init(targetFunction: (Array) -> Int32, args: Array) + public init(targetFunction: (FuzzDataProvider) -> Int32) + public init(targetFunction: (FuzzDataProvider) -> Int32, args: Array) + public func disableDebugDataProvider(): Unit + public func disableFakeCoverage(): Unit + public func enableDebugDataProvider(): Unit + public func enableFakeCoverage(): Unit + public func getArgs(): Array + public func setArgs(args: Array): Unit + public func setTargetFunction(targetFunction: (Array) -> Int32): Unit + public func setTargetFunction(targetFunction: (FuzzDataProvider) -> Int32): Unit + public func startFuzz(): Unit +} + +public class FuzzerBuilder { + public init(targetFunction: (Array) -> Int32) + public init(targetFunction: (FuzzDataProvider) -> Int32) + public func build(): Fuzzer + public func setArgs(args: Array): FuzzerBuilder + public func setTargetFunction(targetFunction: (Array) -> Int32): FuzzerBuilder + public func setTargetFunction(targetFunction: (FuzzDataProvider) -> Int32): FuzzerBuilder +} + +public open class FuzzDataProvider { + public let data: Array + public var offset: Int64 + public var remainingBytes: Int64 + public open func consumeAll(): Array + public open func consumeAllAsAscii(): String + public open func consumeAllAsString(): String + public open func consumeAsciiString(maxLength: Int64): String + public open func consumeBool(): Bool + public open func consumeBools(count: Int64): Array + public open func consumeByte(): Byte + public open func consumeBytes(count: Int64): Array + public open func consumeFloat32(): Float32 + public open func consumeFloat64(): Float64 + public open func consumeInt16(): Int16 + public open func consumeInt16s(count: Int64): Array + public open func consumeInt32(): Int32 + public open func consumeInt32s(count: Int64): Array + public open func consumeInt64(): Int64 + public open func consumeInt64s(count: Int64): Array + public open func consumeInt8(): Int8 + public open func consumeInt8s(count: Int64): Array + public open func consumeRune(): Rune + public open func consumeString(maxLength: Int64): String + public open func consumeUInt16(): UInt16 + public open func consumeUInt16s(count: Int64): Array + public open func consumeUInt32(): UInt32 + public open func consumeUInt32s(count: Int64): Array + public open func consumeUInt64(): UInt64 + public open func consumeUInt64s(count: Int64): Array + public open func consumeUInt8(): UInt8 + public open func consumeUInt8s(count: Int64): Array + public static func withCangjieData(data: Array): FuzzDataProvider + public static unsafe func withNativeData(data: CPointer, length: Int64): FuzzDataProvider +} + + +// --------------------------- +// -----vars +// --------------------------- +public let FUZZ_VERSION = "1.0.0" {} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ExhaustedException <: Exception { + public init() + public init(message: String) +} + + diff --git a/cangjie_libs/log/log.cjd b/cangjie_libs/log/log.cjd new file mode 100644 index 0000000000000000000000000000000000000000..6fb8d766adcf20c2259d2abd801447ccd40538d5 --- /dev/null +++ b/cangjie_libs/log/log.cjd @@ -0,0 +1,158 @@ +package log.log + +// --------------------------- +// -----classes +// --------------------------- +public abstract class Logger <: Resource { + public open mut prop level: LogLevel + public func debug(message: String, attrs: Array): Unit + public func debug(message: () -> String, attrs: Array): Unit + public func enabled(level: LogLevel): Bool + public func error(message: String, attrs: Array): Unit + public func error(message: () -> String, attrs: Array): Unit + public func fatal(message: String, attrs: Array): Unit + public func fatal(message: () -> String, attrs: Array): Unit + public func info(message: String, attrs: Array): Unit + public func info(message: () -> String, attrs: Array): Unit + public open func log(level: LogLevel, message: String, attrs: Array): Unit + public open func log(level: LogLevel, message: () -> String, attrs: Array): Unit + public open func log(record: LogRecord): Unit + public func trace(message: String, attrs: Array): Unit + public func trace(message: () -> String, attrs: Array): Unit + public func warn(message: String, attrs: Array): Unit + public func warn(message: () -> String, attrs: Array): Unit + public open func withAttrs(attrs: Array): Logger +} + +public class LogRecord { + public init(time: DateTime, level: LogLevel, msg: String, attrs: Array) + public mut prop attrs: Array + public prop level: LogLevel + public mut prop message: String + public prop time: DateTime + public func clone(): LogRecord +} + +public abstract class LogWriter { + public func endArray(): Unit + public func endObject(): Unit + public func startArray(): Unit + public func startObject(): Unit + public func writeBool(v: Bool): Unit + public func writeFloat(v: Float64): Unit + public func writeDateTime(v: DateTime): Unit + public func writeDuration(v: Duration): Unit + public func writeInt(v: Int64): Unit + public func writeKey(v: String): Unit + public func writeNone(): Unit + public func writeString(v: String): Unit + public func writeValue(v: LogValue): Unit +} + +public class NoopLogger <: Logger { + public init() + public mut prop level: LogLevel + public func close(): Unit + public func isClosed(): Bool + public func log(level: LogLevel, message: String, attrs: Array): Unit + public func log(level: LogLevel, message: () -> String, attrs: Array): Unit + public func log(record: LogRecord): Unit + public func withAttrs(attrs: Array): Logger +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public open class LogException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func getGlobalLogger(attrs: Array): Logger +public func setGlobalLogger(logger: Logger): Unit + +// --------------------------- +// -----interfaces +// --------------------------- +public interface LogValue { + func writeTo(w: LogWriter): Unit +} + +extend Bool <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend Int64 <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend Float64 <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend String <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend DateTime <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend Duration <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend Array <: LogValue where T <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend HashMap <: LogValue where K <: String, V <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend TreeMap <: LogValue where K <: String, V <: LogValue { + public func writeTo(w: LogWriter): Unit +} + +extend Option <: LogValue where T <: LogValue { + public func writeTo(w: LogWriter): Unit +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct LogLevel <: ToString & Comparable { + public let name: String + public let value: Int32 + public const init(name: String, value: Int32) + public static const ALL = LogLevel("ALL", -0x8000_0000) + public static const DEBUG = LogLevel("DEBUG", 2000) + public static const ERROR = LogLevel("ERROR", 5000) + public static const FATAL = LogLevel("FATAL", 6000) + public static const INFO = LogLevel("INFO", 3000) + public static const OFF = LogLevel("OFF", 0x7FFF_FFFF) + public static const TRACE = LogLevel("TRACE", 1000) + public static const WARN = LogLevel("WARN", 4000) + public func compare(rhs: LogLevel): Ordering + public func toString(): String + public operator func ==(rhs: LogLevel): Bool + public operator func !=(rhs: LogLevel): Bool + public operator func >=(rhs: LogLevel): Bool + public operator func <=(rhs: LogLevel): Bool + public operator func >(rhs: LogLevel): Bool + public operator func <(rhs: LogLevel): Bool +} + + +// --------------------------- +// -----types +// --------------------------- +public type Attr = (String, LogValue) {} + + diff --git a/cangjie_libs/logger/logger.cjd b/cangjie_libs/logger/logger.cjd new file mode 100644 index 0000000000000000000000000000000000000000..bd2baad4c5a2bfacd97e223c4dbda71e391dfc27 --- /dev/null +++ b/cangjie_libs/logger/logger.cjd @@ -0,0 +1,72 @@ +package logger.logger + +// --------------------------- +// -----classes +// --------------------------- +public class JsonLogger <: Logger { + public init(output: OutputStream) + public open mut prop level: LogLevel + public func debug(message: String, attrs: Array): Unit + public func debug(message: () -> String, attrs: Array): Unit + public func enabled(level: LogLevel): Bool + public func error(message: String, attrs: Array): Unit + public func error(message: () -> String, attrs: Array): Unit + public func fatal(message: String, attrs: Array): Unit + public func fatal(message: () -> String, attrs: Array): Unit + public func info(message: String, attrs: Array): Unit + public func info(message: () -> String, attrs: Array): Unit + public open func log(level: LogLevel, message: String, attrs: Array): Unit + public open func log(level: LogLevel, message: () -> String, attrs: Array): Unit + public open func log(record: LogRecord): Unit + public func trace(message: String, attrs: Array): Unit + public func trace(message: () -> String, attrs: Array): Unit + public func warn(message: String, attrs: Array): Unit + public func warn(message: () -> String, attrs: Array): Unit + public open func withAttrs(attrs: Array): Logger +} + +public class SimpleLogger <: Logger { + public init(output: OutputStream) + public open mut prop level: LogLevel + public func debug(message: String, attrs: Array): Unit + public func debug(message: () -> String, attrs: Array): Unit + public func enabled(level: LogLevel): Bool + public func error(message: String, attrs: Array): Unit + public func error(message: () -> String, attrs: Array): Unit + public func fatal(message: String, attrs: Array): Unit + public func fatal(message: () -> String, attrs: Array): Unit + public func info(message: String, attrs: Array): Unit + public func info(message: () -> String, attrs: Array): Unit + public open func log(level: LogLevel, message: String, attrs: Array): Unit + public open func log(level: LogLevel, message: () -> String, attrs: Array): Unit + public open func log(record: LogRecord): Unit + public func trace(message: String, attrs: Array): Unit + public func trace(message: () -> String, attrs: Array): Unit + public func warn(message: String, attrs: Array): Unit + public func warn(message: () -> String, attrs: Array): Unit + public open func withAttrs(attrs: Array): Logger +} + +public class TextLogger <: Logger { + public init(output: OutputStream) + public open mut prop level: LogLevel + public func debug(message: String, attrs: Array): Unit + public func debug(message: () -> String, attrs: Array): Unit + public func enabled(level: LogLevel): Bool + public func error(message: String, attrs: Array): Unit + public func error(message: () -> String, attrs: Array): Unit + public func fatal(message: String, attrs: Array): Unit + public func fatal(message: () -> String, attrs: Array): Unit + public func info(message: String, attrs: Array): Unit + public func info(message: () -> String, attrs: Array): Unit + public open func log(level: LogLevel, message: String, attrs: Array): Unit + public open func log(level: LogLevel, message: () -> String, attrs: Array): Unit + public open func log(record: LogRecord): Unit + public func trace(message: String, attrs: Array): Unit + public func trace(message: () -> String, attrs: Array): Unit + public func warn(message: String, attrs: Array): Unit + public func warn(message: () -> String, attrs: Array): Unit + public open func withAttrs(attrs: Array): Logger +} + + diff --git a/cangjie_libs/net/http.cjd b/cangjie_libs/net/http.cjd new file mode 100644 index 0000000000000000000000000000000000000000..d4963cd437060a3b976502177106708523586e01 --- /dev/null +++ b/cangjie_libs/net/http.cjd @@ -0,0 +1,471 @@ +package net.http + +// --------------------------- +// -----classes +// --------------------------- +public class Client { + public prop autoRedirect: Bool + public prop connector: (SocketAddress) -> StreamingSocket + public prop cookieJar: ?CookieJar + public prop enablePush: Bool + public prop headerTableSize: UInt32 + public prop httpProxy: String + public prop httpsProxy: String + public prop initialWindowSize: UInt32 + public prop logger: Logger + public prop maxConcurrentStreams: UInt32 + public prop maxFrameSize: UInt32 + public prop maxHeaderListSize: UInt32 + public prop poolSize: Int64 + public prop readTimeout: Duration + public prop writeTimeout: Duration + public func close(): Unit + public func connect(url: String, header!: HttpHeaders = HttpHeaders(), version!: Protocol = HTTP1_1): (HttpResponse, ?StreamingSocket) + public func delete(url: String): HttpResponse + public func get(url: String): HttpResponse + public func getTlsConfig(): ?TlsClientConfig + public func head(url: String): HttpResponse + public func options(url: String): HttpResponse + public func post(url: String, body: Array): HttpResponse + public func post(url: String, body: InputStream): HttpResponse + public func post(url: String, body: String): HttpResponse + public func put(url: String, body: Array): HttpResponse + public func put(url: String, body: InputStream): HttpResponse + public func put(url: String, body: String): HttpResponse + public func send(req: HttpRequest): HttpResponse + public func upgrade(req: HttpRequest): (HttpResponse, ?StreamingSocket) +} + +public class ClientBuilder { + public init() + public func autoRedirect(auto: Bool): ClientBuilder + public func build(): Client + public func connector(connector: (SocketAddress)->StreamingSocket): ClientBuilder + public func cookieJar(cookieJar: ?CookieJar): ClientBuilder + public func enablePush(enable: Bool): ClientBuilder + public func headerTableSize(size: UInt32): ClientBuilder + public func httpProxy(addr: String): ClientBuilder + public func httpsProxy(addr: String): ClientBuilder + public func initialWindowSize(size: UInt32): ClientBuilder + public func logger(logger: Logger): ClientBuilder + public func maxConcurrentStreams(size: UInt32): ClientBuilder + public func maxFrameSize(size: UInt32): ClientBuilder + public func maxHeaderListSize(size: UInt32): ClientBuilder + public func noProxy(): ClientBuilder + public func poolSize(size: Int64): ClientBuilder + public func readTimeout(timeout: Duration): ClientBuilder + public func tlsConfig(config: TlsClientConfig): ClientBuilder + public func writeTimeout(timeout: Duration): ClientBuilder +} + +public class Cookie { + public prop cookieName: String + public prop cookieValue: String + public prop domain: String + public prop expires: ?DateTime + public prop httpOnly: Bool + public prop maxAge: ?Int64 + public prop others: ArrayList + public prop path: String + public prop secure: Bool + public init(name: String, value: String, expires!: ?DateTime = None, maxAge!: ?Int64 = None, domain!: String = "", path!: String = "", secure!: Bool = false, httpOnly!: Bool = false) + public func toSetCookieString(): String +} + +public class FileHandler <: HttpRequestHandler { + public init(path: String, handlerType!: FileHandlerType = DownLoad, bufferSize!: Int64 = 64 * 1024) + public func handle(ctx: HttpContext): Unit +} + +public class FuncHandler <: HttpRequestHandler { + public FuncHandler(let handler: (HttpContext) -> Unit) + public func handle(ctx: HttpContext): Unit +} + +public class HttpContext { + public prop clientCertificate: ?Array + public prop request: HttpRequest + public prop responseBuilder: HttpResponseBuilder +} + +public class HttpHeaders <: Iterable<(String, Collection)> { + public init() + public func add(name: String, value: String): Unit + public func del(name: String): Unit + public func get(name: String): Collection + public func getFirst(name: String): ?String + public func isEmpty(): Bool + public func iterator(): Iterator<(String, Collection)> + public func set(name: String, value: String): Unit +} + +public class HttpRequest <: ToString { + public prop body: InputStream + public prop bodySize: Option + public prop close: Bool + public prop form: Form + public prop headers: HttpHeaders + public prop method: String + public prop readTimeout: ?Duration + public prop remoteAddr: String + public prop trailers: HttpHeaders + public prop url: URL + public prop version: Protocol + public prop writeTimeout: ?Duration + public override func toString(): String +} + +public class HttpRequestBuilder { + public init() + public init(request: HttpRequest) + public func addHeaders(headers: HttpHeaders): HttpRequestBuilder + public func addTrailers(trailers: HttpHeaders): HttpRequestBuilder + public func body(body: Array): HttpRequestBuilder + public func body(body: InputStream): HttpRequestBuilder + public func body(body: String): HttpRequestBuilder + public func build(): HttpRequest + public func connect(): HttpRequestBuilder + public func delete(): HttpRequestBuilder + public func get(): HttpRequestBuilder + public func head(): HttpRequestBuilder + public func header(name: String, value: String): HttpRequestBuilder + public func method(method: String): HttpRequestBuilder + public func options(): HttpRequestBuilder + public func post(): HttpRequestBuilder + public func priority(urg: Int64, inc: Bool): HttpRequestBuilder + public func put(): HttpRequestBuilder + public func readTimeout(timeout: Duration): HttpRequestBuilder + public func setHeaders(headers: HttpHeaders): HttpRequestBuilder + public func setTrailers(trailers: HttpHeaders): HttpRequestBuilder + public func trace(): HttpRequestBuilder + public func trailer(name: String, value: String): HttpRequestBuilder + public func url(rawUrl: String): HttpRequestBuilder + public func url(url: URL): HttpRequestBuilder + public func version(version: Protocol): HttpRequestBuilder + public func writeTimeout(timeout: Duration): HttpRequestBuilder +} + +public class HttpResponse <: ToString { + public prop body: InputStream + public prop bodySize: Option + public prop close: Bool + public prop headers: HttpHeaders + public prop request: Option + public prop status: UInt16 + public prop trailers: HttpHeaders + public prop version: Protocol + public func getPush(): ?ArrayList + public override func toString(): String +} + +public class HttpResponseBuilder { + public init() + public func addHeaders(headers: HttpHeaders): HttpResponseBuilder + public func addTrailers(trailers: HttpHeaders): HttpResponseBuilder + public func body(body: Array): HttpResponseBuilder + public func body(body: InputStream): HttpResponseBuilder + public func body(body: String): HttpResponseBuilder + public func build(): HttpResponse + public func header(name: String, value: String): HttpResponseBuilder + public func request(request: HttpRequest): HttpResponseBuilder + public func setHeaders(headers: HttpHeaders): HttpResponseBuilder + public func setTrailers(trailers: HttpHeaders): HttpResponseBuilder + public func status(status: UInt16): HttpResponseBuilder + public func trailer(name: String, value: String): HttpResponseBuilder + public func version(version: Protocol): HttpResponseBuilder +} + +public class HttpResponsePusher { + public static func getPusher(ctx: HttpContext): ?HttpResponsePusher + public func push(path: String, method: String, header: HttpHeaders): Unit +} + +public class HttpResponseWriter { + public HttpResponseWriter(let ctx: HttpContext) + public func write(buf: Array): Unit +} + +public class NotFoundHandler <: HttpRequestHandler { + public init() + public func handle(ctx: HttpContext): Unit +} + +public class OptionsHandler <: HttpRequestHandler { + public init() + public func handle(ctx: HttpContext): Unit +} + +public abstract class ProtocolService { + open protected mut prop server: Server + protected func serve(): Unit + open protected func closeGracefully(): Unit + open protected func close(): Unit +} + +public class RedirectHandler <: HttpRequestHandler { + public init(url: String, code: UInt16) + public func handle(ctx: HttpContext): Unit +} + +public class Server { + public prop addr: String + public prop distributor: HttpRequestDistributor + public prop enableConnectProtocol: Bool + public prop headerTableSize: UInt32 + public prop httpKeepAliveTimeout: Duration + public prop initialWindowSize: UInt32 + public prop listener: ServerSocket + public prop logger: Logger + public prop maxConcurrentStreams: UInt32 + public prop maxFrameSize: UInt32 + public prop maxHeaderListSize: UInt32 + public prop maxRequestBodySize: Int64 + public prop maxRequestHeaderSize: Int64 + public prop port: UInt16 + public prop protocolServiceFactory: ProtocolServiceFactory + public prop readHeaderTimeout: Duration + public prop readTimeout: Duration + public prop servicePoolConfig: ServicePoolConfig + public prop transportConfig: TransportConfig + public prop writeTimeout: Duration + public func afterBind(f: ()->Unit): Unit + public func close(): Unit + public func closeGracefully(): Unit + public func getTlsConfig(): ?TlsServerConfig + public func onShutdown(f: ()->Unit): Unit + public func serve(): Unit + public func updateCA(newCa: Array): Unit + public func updateCA(newCaFile: String): Unit + public func updateCert(certChain: Array, certKey: PrivateKey): Unit + public func updateCert(certificateChainFile: String, privateKeyFile: String): Unit +} + +public class ServerBuilder { + public init() + public func addr(addr: String): ServerBuilder + public func afterBind(f: ()->Unit): ServerBuilder + public func build(): Server + public func distributor(distributor: HttpRequestDistributor): ServerBuilder + public func enableConnectProtocol(flag: Bool): ServerBuilder + public func headerTableSize(size: UInt32): ServerBuilder + public func httpKeepAliveTimeout(timeout: Duration): ServerBuilder + public func initialWindowSize(size: UInt32): ServerBuilder + public func listener(listener: ServerSocket): ServerBuilder + public func logger(logger: Logger): ServerBuilder + public func maxConcurrentStreams(size: UInt32): ServerBuilder + public func maxFrameSize(size: UInt32): ServerBuilder + public func maxHeaderListSize(size: UInt32): ServerBuilder + public func maxRequestBodySize(size: Int64): ServerBuilder + public func maxRequestHeaderSize(size: Int64): ServerBuilder + public func onShutdown(f: ()->Unit): ServerBuilder + public func port(port: UInt16): ServerBuilder + public func protocolServiceFactory(factory: ProtocolServiceFactory): ServerBuilder + public func readHeaderTimeout(timeout: Duration): ServerBuilder + public func readTimeout(timeout: Duration): ServerBuilder + public func servicePoolConfig(cfg: ServicePoolConfig): ServerBuilder + public func tlsConfig(config: TlsServerConfig): ServerBuilder + public func transportConfig(config: TransportConfig): ServerBuilder + public func writeTimeout(timeout: Duration): ServerBuilder +} + +public class WebSocket { + public prop logger: Logger + public prop subProtocol: String + public static func upgradeFromClient(client: Client, url: URL, version!: Protocol = HTTP1_1, subProtocols!: ArrayList = ArrayList(), headers!: HttpHeaders = HttpHeaders()): (WebSocket, HttpHeaders) + public static func upgradeFromServer(ctx: HttpContext, subProtocols!: ArrayList = ArrayList(), origins!: ArrayList = ArrayList(), userFunc!:(HttpRequest) -> HttpHeaders = {_: HttpRequest => HttpHeaders()}): WebSocket + public func closeConn(): Unit + public func read(): WebSocketFrame + public func write(frameType: WebSocketFrameType, byteArray: Array, frameSize!: Int64 = FRAMESIZE): Unit + public func writeCloseFrame(status!: ?UInt16 = None, reason!: String = ""): Unit + public func writePingFrame(byteArray: Array): Unit + public func writePongFrame(byteArray: Array): Unit +} + +public class WebSocketFrame { + public prop fin: Bool + public prop frameType: WebSocketFrameType + public prop payload: Array +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum FileHandlerType { + DownLoad + UpLoad +} + +public enum Protocol <: Equatable & ToString { + HTTP1_0 + HTTP1_1 + HTTP2_0 + UnknownProtocol(String) + public override func toString(): String + public override operator func != (that: Protocol): Bool + public override operator func == (that: Protocol): Bool +} + +public enum WebSocketFrameType <: Equatable & ToString { + ContinuationWebFrame + TextWebFrame + BinaryWebFrame + CloseWebFrame + PingWebFrame + PongWebFrame + UnknownWebFrame + public override func toString(): String + public override operator func != (that: WebSocketFrameType): Bool + public override operator func == (that: WebSocketFrameType): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ConnectionException <: Exception { + public init(message: String) +} + +public class CoroutinePoolRejectException <: Exception { + public init(message: String) +} + +public class HttpException <: Exception { + public init(message: String) +} + +public class HttpStatusException <: Exception { + public init(message: String) +} + +public class HttpTimeoutException <: Exception { + public init(message: String) +} + +public class WebSocketException <: Exception { + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func handleError(ctx: HttpContext, code: UInt16): Unit +public func notFound(ctx: HttpContext): Unit +public func upgrade(ctx: HttpContext): StreamingSocket + +// --------------------------- +// -----interfaces +// --------------------------- +public interface CookieJar { + prop isHttp: Bool + prop rejectPublicSuffixes: ArrayList + static func createDefaultCookieJar(rejectPublicSuffixes: ArrayList, isHttp: Bool): CookieJar + static func parseSetCookieHeader(response: HttpResponse): ArrayList + static func toCookieString(cookies: ArrayList): String + func clear(): Unit + func getCookies(url: URL): ArrayList + func removeCookies(domain: String): Unit + func storeCookies(url: URL, cookies: ArrayList): Unit +} + +public interface HttpRequestDistributor { + func distribute(path: String): HttpRequestHandler + func register(path: String, handler: (HttpContext) -> Unit): Unit + func register(path: String, handler: HttpRequestHandler): Unit +} + +public interface HttpRequestHandler { + func handle(ctx: HttpContext): Unit +} + +public interface ProtocolServiceFactory { + func create(protocol: Protocol, socket: StreamingSocket): ProtocolService +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct HttpStatusCode { + public static const STATUS_ACCEPTED: UInt16 = 202 + public static const STATUS_ALREADY_REPORTED: UInt16 = 208 + public static const STATUS_BAD_GATEWAY: UInt16 = 502 + public static const STATUS_BAD_REQUEST: UInt16 = 400 + public static const STATUS_CONFLICT: UInt16 = 409 + public static const STATUS_CONTINUE: UInt16 = 100 + public static const STATUS_CREATED: UInt16 = 201 + public static const STATUS_EARLY_HINTS: UInt16 = 103 + public static const STATUS_EXPECTATION_FAILED: UInt16 = 417 + public static const STATUS_FAILED_DEPENDENCY: UInt16 = 424 + public static const STATUS_FORBIDDEN: UInt16 = 403 + public static const STATUS_FOUND: UInt16 = 302 + public static const STATUS_GATEWAY_TIMEOUT: UInt16 = 504 + public static const STATUS_GONE: UInt16 = 410 + public static const STATUS_HTTP_VERSION_NOT_SUPPORTED: UInt16 = 505 + public static const STATUS_IM_USED: UInt16 = 226 + public static const STATUS_INSUFFICIENT_STORAGE: UInt16 = 507 + public static const STATUS_INTERNAL_SERVER_ERROR: UInt16 = 500 + public static const STATUS_LENGTH_REQUIRED: UInt16 = 411 + public static const STATUS_LOCKED: UInt16 = 423 + public static const STATUS_LOOP_DETECTED: UInt16 = 508 + public static const STATUS_METHOD_NOT_ALLOWED: UInt16 = 405 + public static const STATUS_MISDIRECTED_REQUEST: UInt16 = 421 + public static const STATUS_MOVED_PERMANENTLY: UInt16 = 301 + public static const STATUS_MULTIPLE_CHOICES: UInt16 = 300 + public static const STATUS_MULTI_STATUS: UInt16 = 207 + public static const STATUS_NETWORK_AUTHENTICATION_REQUIRED: UInt16 = 511 + public static const STATUS_NON_AUTHORITATIVE_INFO: UInt16 = 203 + public static const STATUS_NOT_ACCEPTABLE: UInt16 = 406 + public static const STATUS_NOT_EXTENDED: UInt16 = 510 + public static const STATUS_NOT_FOUND: UInt16 = 404 + public static const STATUS_NOT_IMPLEMENTED: UInt16 = 501 + public static const STATUS_NOT_MODIFIED: UInt16 = 304 + public static const STATUS_NO_CONTENT: UInt16 = 204 + public static const STATUS_OK: UInt16 = 200 + public static const STATUS_PARTIAL_CONTENT: UInt16 = 206 + public static const STATUS_PAYMENT_REQUIRED: UInt16 = 402 + public static const STATUS_PERMANENT_REDIRECT: UInt16 = 308 + public static const STATUS_PRECONDITION_FAILED: UInt16 = 412 + public static const STATUS_PRECONDITION_REQUIRED: UInt16 = 428 + public static const STATUS_PROCESSING: UInt16 = 102 + public static const STATUS_PROXY_AUTH_REQUIRED: UInt16 = 407 + public static const STATUS_REQUESTED_RANGE_NOT_SATISFIABLE: UInt16 = 416 + public static const STATUS_REQUEST_CONTENT_TOO_LARGE: UInt16 = 413 + public static const STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: UInt16 = 431 + public static const STATUS_REQUEST_TIMEOUT: UInt16 = 408 + public static const STATUS_REQUEST_URI_TOO_LONG: UInt16 = 414 + public static const STATUS_RESET_CONTENT: UInt16 = 205 + public static const STATUS_SEE_OTHER: UInt16 = 303 + public static const STATUS_SERVICE_UNAVAILABLE: UInt16 = 503 + public static const STATUS_SWITCHING_PROTOCOLS: UInt16 = 101 + public static const STATUS_TEAPOT: UInt16 = 418 + public static const STATUS_TEMPORARY_REDIRECT: UInt16 = 307 + public static const STATUS_TOO_EARLY: UInt16 = 425 + public static const STATUS_TOO_MANY_REQUESTS: UInt16 = 429 + public static const STATUS_UNAUTHORIZED: UInt16 = 401 + public static const STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: UInt16 = 451 + public static const STATUS_UNPROCESSABLE_ENTITY: UInt16 = 422 + public static const STATUS_UNSUPPORTED_MEDIA_TYPE: UInt16 = 415 + public static const STATUS_UPGRADE_REQUIRED: UInt16 = 426 + public static const STATUS_USE_PROXY: UInt16 = 305 + public static const STATUS_VARIANT_ALSO_NEGOTIATES: UInt16 = 506 +} + +public struct ServicePoolConfig { + public let capacity: Int64 + public let preheat: Int64 + public let queueCapacity: Int64 + public init( capacity!: Int64 = 10 ** 4, queueCapacity!: Int64 = 10 ** 4, preheat!: Int64 = 0) +} + +public struct TransportConfig { + public mut prop keepAliveConfig: SocketKeepAliveConfig + public mut prop readBufferSize: ?Int64 + public mut prop readTimeout: Duration + public mut prop writeBufferSize: ?Int64 + public mut prop writeTimeout: Duration +} + + diff --git a/cangjie_libs/net/tls.cjd b/cangjie_libs/net/tls.cjd new file mode 100644 index 0000000000000000000000000000000000000000..fa82dd541b49dd69dc4ffb01c4f13fd708f5da08 --- /dev/null +++ b/cangjie_libs/net/tls.cjd @@ -0,0 +1,157 @@ +package net.tls + +// --------------------------- +// -----classes +// --------------------------- +public class TlsSessionContext <: Equatable & ToString { + public static func fromName(name: String): TlsSessionContext + public override func toString(): String + public override operator func !=(other: TlsSessionContext) + public override operator func ==(other: TlsSessionContext) +} + +public class TlsSocket <: StreamingSocket & ToString & Equatable & Hashable { + public prop alpnProtocolName: ?String + public prop cipherSuite: CipherSuite + public prop clientCertificate: ?Array + public prop domain: ?String + public override prop localAddress: SocketAddress + public prop peerCertificate: ?Array + public override mut prop readTimeout: ?Duration + public override prop remoteAddress: SocketAddress + public prop serverCertificate: Array + public prop session: ?TlsSession + public prop socket: StreamingSocket + public prop tlsVersion: TlsVersion + public override mut prop writeTimeout: ?Duration + public static func client( socket: StreamingSocket, session!: ?TlsSession = None, clientConfig!: TlsClientConfig = TlsClientConfig()): TlsSocket + public static func server( socket: StreamingSocket, sessionContext!: ?TlsSessionContext = None, serverConfig!: TlsServerConfig): TlsSocket + public func close(): Unit + public func handshake(timeout!: ?Duration = None): Unit + public override func hashCode(): Int64 + public func isClosed(): Bool + public override func read(buffer: Array): Int64 + public func toString(): String + public func write(buffer: Array): Unit + public override operator func !=(other: TlsSocket) + public override operator func ==(other: TlsSocket) +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum CertificateVerifyMode { + CustomCA(Array) + Default + TrustAll +} + +public enum SignatureAlgorithm <: ToString & Equatable { + SignatureAndHashAlgorithm(SignatureType, HashType) + SignatureScheme(SignatureSchemeType) + public func toString():String + public operator func !=(other: SignatureAlgorithm) : Bool + public operator func ==(other: SignatureAlgorithm) : Bool +} + +public enum SignatureSchemeType <: ToString & Equatable { + ECDSA_SECP256R1_SHA256 + ECDSA_SECP384R1_SHA384 + ECDSA_SECP521R1_SHA512 + ED25519 + ED448 + RSA_PKCS1_SHA256 + RSA_PKCS1_SHA384 + RSA_PKCS1_SHA512 + RSA_PSS_PSS_SHA256 + RSA_PSS_PSS_SHA384 + RSA_PSS_PSS_SHA512 + RSA_PSS_RSAE_SHA256 + RSA_PSS_RSAE_SHA384 + RSA_PSS_RSAE_SHA512 + public func toString(): String + public operator func !=(other: SignatureSchemeType): Bool + public operator func ==(other: SignatureSchemeType): Bool +} + +public enum SignatureType <: ToString & Equatable { + DSA + ECDSA + RSA + public func toString(): String + public operator func !=(other: SignatureType) : Bool + public operator func ==(other: SignatureType) : Bool +} + +public enum TlsClientIdentificationMode { + Disabled + Optional + Required +} + +public enum TlsVersion <: ToString { + Unknown + V1_2 + V1_3 + public override func toString(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class TlsException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct CipherSuite <: ToString & Equatable { + public static prop allSupported: Array + public func toString(): String + public operator func !=(that: CipherSuite): Bool + public operator func ==(that: CipherSuite): Bool +} + +public struct TlsClientConfig { + public var keylogCallback: ?(TlsSocket, String) -> Unit = None + public var verifyMode: CertificateVerifyMode = CertificateVerifyMode.Default + public mut prop alpnProtocolsList: Array + public mut prop cipherSuitesV1_2: ?Array + public mut prop cipherSuitesV1_3: ?Array + public mut prop clientCertificate: ?(Array, PrivateKey) + public mut prop domain: ?String + public mut prop maxVersion: TlsVersion + public mut prop minVersion: TlsVersion + public mut prop securityLevel: Int32 + public mut prop signatureAlgorithms: ?Array + public init() +} + +public struct TlsServerConfig { + public var clientIdentityRequired: TlsClientIdentificationMode = Disabled + public var keylogCallback: ?(TlsSocket, String) -> Unit = None + public var verifyMode: CertificateVerifyMode = CertificateVerifyMode.Default + public mut prop cipherSuitesV1_2: Array + public mut prop cipherSuitesV1_3: Array + public mut prop dhParameters: ?DHParamters + public mut prop maxVersion: TlsVersion + public mut prop minVersion: TlsVersion + public mut prop securityLevel: Int32 + public mut prop serverCertificate: (Array, PrivateKey) + public mut prop supportedAlpnProtocols: Array + public init(certChain: Array, certKey: PrivateKey) +} + +public struct TlsSession <: Equatable & ToString & Hashable { + public override func hashCode(): Int64 + public override func toString(): String + public override operator func !=(other: TlsSession) + public override operator func ==(other: TlsSession) +} + + diff --git a/cangjie_libs/serialization/serialization.cjd b/cangjie_libs/serialization/serialization.cjd new file mode 100644 index 0000000000000000000000000000000000000000..cf029cd29cf773705c97f69f3a2e24b59c2f40e0 --- /dev/null +++ b/cangjie_libs/serialization/serialization.cjd @@ -0,0 +1,170 @@ +package serialization.serialization + +// --------------------------- +// -----classes +// --------------------------- +public abstract class DataModel {} + +public class DataModelBool <: DataModel { + public init(bv: Bool) + public func getValue(): Bool +} + +public class DataModelFloat <: DataModel { + public init(fv: Float64) + public init(v: Int64) + public func getValue(): Float64 +} + +public class DataModelInt <: DataModel { + public init(iv: Int64) + public func getValue(): Int64 +} + +public class DataModelNull <: DataModel {} + +public class DataModelSeq <: DataModel { + public init() + public init(list: ArrayList) + public func add(dm: DataModel) + public func getItems(): ArrayList +} + +public class DataModelString <: DataModel { + public init(sv: String) + public func getValue(): String +} + +public class DataModelStruct <: DataModel { + public init() + public init(list: ArrayList) + public func add(fie: Field): DataModelStruct + public func get(key: String): DataModel + public func getFields(): ArrayList +} + +public class Field { + public init(name: String, data: DataModel) + public func getData(): DataModel + public func getName(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class DataModelException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----functions +// --------------------------- +public func field(name: String, data: T) : Field where T <: Serializable + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Serializable { + static func deserialize(dm: DataModel): T + func serialize(): DataModel +} + +extend Array <: Serializable> where T <: Serializable { + static public func deserialize(dm: DataModel): Array + public func serialize(): DataModel +} + +extend ArrayList <: Serializable> where T <: Serializable { + static public func deserialize(dm: DataModel): ArrayList + public func serialize(): DataModel +} + +extend Bool <: Serializable { + static public func deserialize(dm: DataModel): Bool + public func serialize(): DataModel +} + +extend Float16 <: Serializable { + static public func deserialize(dm: DataModel): Float16 + public func serialize(): DataModel +} + +extend Float32 <: Serializable { + static public func deserialize(dm: DataModel): Float32 + public func serialize(): DataModel +} + +extend Float64 <: Serializable { + static public func deserialize(dm: DataModel): Float64 + public func serialize(): DataModel +} + +extend HashMap <: Serializable> where K <: Serializable & Hashable & Equatable, V <: Serializable { + static public func deserialize(dm: DataModel): HashMap + public func serialize(): DataModel +} + +extend HashSet <: Serializable> where T <: Serializable & Hashable & Equatable { + static public func deserialize(dm: DataModel): HashSet + public func serialize(): DataModel +} + +extend Int16 <: Serializable { + static public func deserialize(dm: DataModel): Int16 + public func serialize(): DataModel +} + +extend Int32 <: Serializable { + static public func deserialize(dm: DataModel): Int32 + public func serialize(): DataModel +} + +extend Int64 <: Serializable { + static public func deserialize(dm: DataModel): Int64 + public func serialize(): DataModel +} + +extend Int8 <: Serializable { + static public func deserialize(dm: DataModel): Int8 + public func serialize(): DataModel +} + +extend Option <: Serializable> where T <: Serializable { + static public func deserialize(dm: DataModel): Option + public func serialize(): DataModel +} + +extend Rune <: Serializable { + static public func deserialize(dm: DataModel): Rune + public func serialize(): DataModel +} + +extend String <: Serializable { + static public func deserialize(dm: DataModel): String + public func serialize(): DataModel +} + +extend UInt16 <: Serializable { + static public func deserialize(dm: DataModel): UInt16 + public func serialize(): DataModel +} + +extend UInt32 <: Serializable { + static public func deserialize(dm: DataModel): UInt32 + public func serialize(): DataModel +} + +extend UInt64 <: Serializable { + static public func deserialize(dm: DataModel): UInt64 + public func serialize(): DataModel +} + +extend UInt8 <: Serializable { + static public func deserialize(dm: DataModel): UInt8 + public func serialize(): DataModel +} + + diff --git a/cangjie_libs/std/argopt.cjd b/cangjie_libs/std/argopt.cjd new file mode 100644 index 0000000000000000000000000000000000000000..18cf6132b6223c19d226039e54b6b315398a2e4d --- /dev/null +++ b/cangjie_libs/std/argopt.cjd @@ -0,0 +1,16 @@ +package std.argopt + +// --------------------------- +// -----classes +// --------------------------- +public class ArgOpt { + public init(longArgList: Array) + public init(args: Array, shortArgFormat: String, longArgList: Array) + public init(shortArgFormat: String) + public init(shortArgFormat: String, longArgList: Array) + public func getArg(arg: String): Option + public func getArgumentsMap(): HashMap + public func getUnparseArgs(): Array +} + + diff --git a/cangjie_libs/std/ast.cjd b/cangjie_libs/std/ast.cjd new file mode 100644 index 0000000000000000000000000000000000000000..45fe96a1dbbd410f795b4f25fc3db75d655dafd7 --- /dev/null +++ b/cangjie_libs/std/ast.cjd @@ -0,0 +1,1163 @@ +package std.ast + +// --------------------------- +// -----classes +// --------------------------- +public class Annotation <: Node { + public mut prop arguments: ArrayList + public mut prop at: Token + public mut prop attributes: Tokens + public mut prop condition: Expr + public mut prop identifier: Token + public init() + public init(inputs: Tokens) +} + +public class Argument <: Node { + public mut prop colon: Token + public mut prop expr: Expr + public mut prop identifier: Token + public mut prop keyword: Token + public init() +} + +public class ArrayLiteral <: Expr { + public mut prop elements: ArrayList + public mut prop lSquare: Token + public mut prop rSquare: Token + public init() + public init(inputs: Tokens) +} + +public class AsExpr <: Expr { + public mut prop expr: Expr + public mut prop keyword: Token + public mut prop shiftType: TypeNode + public init() + public init(inputs: Tokens) +} + +public class AssignExpr <: Expr { + public mut prop assign: Token + public mut prop leftExpr: Expr + public mut prop rightExpr: Expr + public init() + public init(inputs: Tokens) +} + +public class BinaryExpr <: Expr { + public mut prop leftExpr: Expr + public mut prop op: Token + public mut prop rightExpr: Expr + public init() + public init(inputs: Tokens) +} + +public class Block <: Expr { + public mut prop lBrace: Token + public mut prop nodes: ArrayList + public mut prop rBrace: Token + public init() +} + +public class Body <: Node { + public mut prop decls: ArrayList + public mut prop lBrace: Token + public mut prop rBrace: Token + public init() + public init(decls: ArrayList) +} + +public class CallExpr <: Expr { + public mut prop arguments: ArrayList + public mut prop callFunc: Expr + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class ClassDecl <: Decl { + public mut prop body: Body + public mut prop superTypeBitAnds: Tokens + public mut prop superTypes: ArrayList + public mut prop upperBound: Token + public init() + public init(inputs: Tokens) +} + +public class ConstPattern <: Pattern { + public mut prop litConstExpr: LitConstExpr + public init() + public init(inputs: Tokens) +} + +public class Constructor <: Node { + public mut prop identifier: Token + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop typeArguments: ArrayList + public init() +} + +public open class Decl <: Node { + public mut prop annotations: ArrayList + public mut prop constraintCommas: Tokens + public mut prop genericConstraint: ArrayList + public mut prop genericParam: GenericParam + public mut open prop identifier: Token + public mut prop isGenericDecl: Bool + public mut prop keyword: Token + public mut prop modifiers: ArrayList + public func getAttrs(): Tokens + public func hasAttr(attr: String): Bool +} + +public class DoWhileExpr <: Expr { + public mut prop block: Block + public mut prop condition: Expr + public mut prop keywordD: Token + public mut prop keywordW: Token + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class EnumDecl <: Decl { + public mut prop constructors: ArrayList + public mut prop decls: ArrayList + public mut prop lBrace: Token + public mut prop rBrace: Token + public mut prop superTypeBitAnds: Tokens + public mut prop superTypes: ArrayList + public mut prop upperBound: Token + public init() + public init(inputs: Tokens) +} + +public class EnumPattern <: Pattern { + public mut prop commas: Tokens + public mut prop constructor: Expr + public mut prop lParen: Token + public mut prop patterns: ArrayList + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class ExceptTypePattern <: Pattern { + public mut prop colon: Token + public mut prop pattern: Pattern + public mut prop types: ArrayList + public init() + public init(inputs: Tokens) +} + +public open class Expr <: Node {} + +public class ExtendDecl <: Decl { + public mut prop body: Body + public mut prop extendType: TypeNode + public mut override prop identifier: Token + public mut prop superTypeBitAnds: Tokens + public mut prop superTypes: ArrayList + public mut prop upperBound: Token + public init() + public init(inputs: Tokens) +} + +public class ForInExpr <: Expr { + public mut prop block: Block + public mut prop expr: Expr + public mut prop keywordF: Token + public mut prop keywordI: Token + public mut prop keywordW: Token + public mut prop lParen: Token + public mut prop pattern: Pattern + public mut prop patternGuard: Expr + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class FuncDecl <: Decl { + public mut prop block: Block + public mut prop colon: Token + public mut prop declType: TypeNode + public mut prop funcParams: ArrayList + public mut prop lParen: Token + public mut prop overloadOp: Tokens + public mut prop rParen: Token + public init() + public init(inputs: Tokens) + public func isConst(): Bool +} + +public open class FuncParam <: Decl { + public mut prop assign: Token + public mut prop colon: Token + public mut prop expr: Expr + public mut prop not: Token + public mut prop paramType: TypeNode + public init() + public init(inputs: Tokens) + public func isMemberParam(): Bool +} + +public class FuncType <: TypeNode { + public mut prop arrow: Token + public mut prop commas: Tokens + public mut prop keyword: Token + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop returnType: TypeNode + public mut prop types: ArrayList + public init() + public init(inputs: Tokens) +} + +public class GenericConstraint <: Node { + public mut prop bitAnds: Tokens + public mut prop keyword: Token + public mut prop typeArgument: TypeNode + public mut prop upperBound: Token + public mut prop upperBounds: ArrayList + public init() +} + +public class GenericParam <: Node { + public mut prop lAngle: Token + public mut prop parameters: Tokens + public mut prop rAngle: Token + public init() + public init(parameters: Tokens) +} + +public class IfExpr <: Expr { + public mut prop condition: Expr + public mut prop elseExpr: Expr + public mut prop ifBlock: Block + public mut prop keywordE: Token + public mut prop keywordI: Token + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class ImportList <: Node { + public mut prop modifier: Token + public mut prop keywordI: Token + public mut prop content: ImportContent + public init() + public init(inputs: Tokens) + public func isImportMulti(): Bool +} + +public class ImportContent <: Node { + public mut prop importKind: ImportKind + public mut prop prefixPaths: Tokens + public mut prop prefixDots: Tokens + public mut prop identifier: Token + public mut prop importAlias: Tokens + public mut prop lBrace: Token + public mut prop items: ArrayList + public mut prop commas: Tokens + public mut prop rBrace: Token + public init() + public func isImportAlias(): Bool + public func isImportAll(): Bool + public func isImportMulti(): Bool + public func isImportSingle(): Bool +} + +public class IncOrDecExpr <: Expr { + public mut prop expr: Expr + public mut prop op: Token + public init() + public init(inputs: Tokens) +} + +public class InterfaceDecl <: Decl { + public mut prop body: Body + public mut prop superTypeBitAnds: Tokens + public mut prop superTypes: ArrayList + public mut prop upperBound: Token + public init() + public init(inputs: Tokens) +} + +public class IsExpr <: Expr { + public mut prop expr: Expr + public mut prop keyword: Token + public mut prop shiftType: TypeNode + public init() + public init(inputs: Tokens) +} + +public class JumpExpr <: Expr { + public mut prop keyword: Token + public init() + public init(kind: Tokens) +} + +public class LambdaExpr <: Expr { + public mut prop doubleArrow: Token + public mut prop funcParams: ArrayList + public mut prop lBrace: Token + public mut prop nodes: ArrayList + public mut prop rBrace: Token + public init() + public init(inputs: Tokens) +} + +public class LetPatternExpr <: Expr { + public mut prop backArrow: Token + public mut prop expr: Expr + public mut prop keyword: Token + public mut prop pattern: Pattern + public init() + public init(inputs: Tokens) +} + +public class LitConstExpr <: Expr { + public mut prop literal: Token + public init() + public init(inputs: Tokens) +} + +public class MacroDecl <: Decl { + public mut prop block: Block + public mut prop colon: Token + public mut prop declType: TypeNode + public mut prop funcParams: ArrayList + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class MacroExpandDecl <: Decl { + public mut prop fullIdentifier: Token + public mut prop lParen: Token + public mut prop lSquare: Token + public mut prop macroAttrs: Tokens + public mut prop macroInputDecl: Decl + public mut prop macroInputs: Tokens + public mut prop rParen: Token + public mut prop rSquare: Token + public init() + public init(inputs: Tokens) +} + +public class MacroExpandExpr <: Expr { + public mut prop at: Token + public mut prop identifier: Token + public mut prop lParen: Token + public mut prop lSquare: Token + public mut prop macroAttrs: Tokens + public mut prop macroInputs: Tokens + public mut prop rParen: Token + public mut prop rSquare: Token + public init() + public init(inputs: Tokens) +} + +public class MacroExpandParam <: FuncParam { + public mut prop fullIdentifier: Token + public mut prop lParen: Token + public mut prop lSquare: Token + public mut prop macroAttrs: Tokens + public mut prop macroInputDecl: Decl + public mut prop macroInputs: Tokens + public mut prop rParen: Token + public mut prop rSquare: Token + public init() +} + +public class MacroMessage { + public func getBool(key: String): Bool + public func getInt64(key: String): Int64 + public func getString(key: String): String + public func hasItem(key: String): Bool +} + +public class MainDecl <: Decl { + public mut prop block: Block + public mut prop colon: Token + public mut prop declType: TypeNode + public mut prop funcParams: ArrayList + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class MatchCase <: Node { + public mut prop arrow: Token + public mut prop bitOrs: Tokens + public mut prop block: Block + public mut prop expr: Expr + public mut prop keywordC: Token + public mut prop keywordW: Token + public mut prop patternGuard: Expr + public mut prop patterns: ArrayList + public init() +} + +public class MatchExpr <: Expr { + public mut prop keyword: Token + public mut prop lBrace: Token + public mut prop lParen: Token + public mut prop matchCases: ArrayList + public mut prop rBrace: Token + public mut prop rParen: Token + public mut prop selector: Expr + public init() + public init(inputs: Tokens) +} + +public class MemberAccess <: Expr { + public mut prop baseExpr: Expr + public mut prop commas: Tokens + public mut prop dot: Token + public mut prop field: Token + public mut prop lAngle: Token + public mut prop rAngle: Token + public mut prop typeArguments: ArrayList + public init() + public init(inputs: Tokens) +} + +public class Modifier <: Node { + public mut prop keyword: Token + public init() + public init(keyword: Token) +} + +abstract sealed class Node <: ToTokens { + public mut prop beginPos: Position + public mut prop endPos: Position + public func dump(): Unit + public func toTokens(): Tokens + public func traverse(v: Visitor): Unit +} + +public class OptionalExpr <: Expr { + public mut prop baseExpr: Expr + public mut prop quest: Token + public init() + public init(inputs: Tokens) +} + +public class PackageHeader <: Node { + public mut prop accessible: Token + public mut prop keywordM: Token + public mut prop keywordP: Token + public mut prop prefixPaths: Tokens + public mut prop prefixDots: Tokens + public mut prop packageIdentifier: Token + public init() + public init(inputs: Tokens) +} + +public class ParenExpr <: Expr { + public mut prop lParen: Token + public mut prop parenthesizedExpr: Expr + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class ParenType <: TypeNode { + public mut prop lParen: Token + public mut prop parenthesizedType: TypeNode + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public open class Pattern <: Node {} + +public class PrefixType <: TypeNode { + public mut prop baseType: TypeNode + public mut prop prefixOps: Tokens + public init() + public init(inputs: Tokens) +} + +public class PrimaryCtorDecl <: Decl { + public mut prop block: Block + public mut prop funcParams: ArrayList + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) + public func isConst(): Bool +} + +public class PrimitiveType <: TypeNode { + public mut prop keyword: Token + public init() + public init(inputs: Tokens) +} + +public class PrimitiveTypeExpr <: Expr { + public mut prop keyword: Token + public init() + public init(kind: Tokens) +} + +public class Program <: Node { + public mut prop decls: ArrayList + public mut prop importLists: ArrayList + public mut prop packageHeader: PackageHeader + public init() + public init(inputs: Tokens) +} + +public class PropDecl <: Decl { + public mut prop colon: Token + public mut prop declType : TypeNode + public mut prop getter: FuncDecl + public mut prop lBrace: Token + public mut prop rBrace: Token + public mut prop setter: FuncDecl + public init() + public init(inputs: Tokens) +} + +public class QualifiedType <: TypeNode { + public mut prop baseType: TypeNode + public mut prop commas: Tokens + public mut prop dot: Token + public mut prop identifier: Token + public mut prop lAngle: Token + public mut prop rAngle: Token + public mut prop typeArguments: ArrayList + public init() + public init(inputs: Tokens) +} + +public class QuoteExpr <: Expr { + public mut prop exprs: ArrayList + public mut prop keyword: Token + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class QuoteToken <: Expr { + public mut prop tokens: Tokens +} + +public class RangeExpr <: Expr { + public mut prop colon: Token + public mut prop end: Expr + public mut prop op: Token + public mut prop start: Expr + public mut prop step: Expr + public init() + public init(inputs: Tokens) +} + +public class RefExpr <: Expr { + public mut prop commas: Tokens + public mut prop identifier: Token + public mut prop lAngle: Token + public mut prop rAngle: Token + public mut prop typeArguments: ArrayList + public init() + public init(inputs: Tokens) +} + +public class RefType <: TypeNode { + public mut prop commas: Tokens + public mut prop identifier: Token + public mut prop lAngle: Token + public mut prop rAngle: Token + public mut prop typeArguments: ArrayList + public init() + public init(inputs: Tokens) +} + +public class ReturnExpr <: Expr { + public mut prop expr: Expr + public mut prop keyword: Token + public init() + public init(inputs: Tokens) +} + +public class SpawnExpr <: Expr { + public mut prop keyword: Token + public mut prop lParen: Token + public mut prop lambdaExpr: LambdaExpr + public mut prop rParen: Token + public mut prop threadContext: Expr + public init() + public init(inputs: Tokens) +} + +public class StructDecl <: Decl { + public mut prop body: Body + public mut prop superTypeBitAnds: Tokens + public mut prop superTypes: ArrayList + public mut prop upperBound: Token + public init() + public init(inputs: Tokens) +} + +public class SubscriptExpr <: Expr { + public mut prop baseExpr: Expr + public mut prop indexList: ArrayList + public mut prop lSquare: Token + public mut prop rSquare: Token + public init() + public init(inputs: Tokens) +} + +public class SynchronizedExpr <: Expr { + public mut prop block: Block + public mut prop keyword: Token + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop structuredMutex: Expr + public init() + public init(inputs: Tokens) +} + +public class ThisType <: TypeNode { + public mut prop keyword: Token + public init() + public init(inputs: Tokens) +} + +public class ThrowExpr <: Expr { + public mut prop expr: Expr + public mut prop keyword: Token + public init() + public init(inputs: Tokens) +} + +public open class Tokens <: ToString & Iterable & ToBytes { + public open prop size: Int64 + public init() + public init(tokArray: Array) + public init(tokArrayList: ArrayList) + public func append(node: Node): Tokens + public open func append(token: Token): Tokens + public open func append(tokens: Tokens): Tokens + public func concat(tokens: Tokens): Tokens + public func dump(): Unit + public open func get(index: Int64): Token + public func iterator(): TokensIterator + public func remove(index: Int64): Tokens + public func toBytes(): Array + public func toString(): String + public operator func +(r: Token): Tokens + public operator func +(r: Tokens): Tokens + public operator func [](index: Int64): Token + public open operator func [](range: Range): Tokens +} + +public class TokensIterator <: Iterator { + public init(tokens: Tokens) + public func iterator(): Iterator + public func next(): Option + public func peek(): Option + public func seeing(kind: TokenKind): Bool +} + +public class TrailingClosureExpr <: Expr { + public mut prop expr: Expr + public mut prop lambdaExpr: LambdaExpr + public init() + public init(inputs: Tokens) +} + +public class TryExpr <: Expr { + public mut prop catchBlocks: ArrayList + public mut prop catchPatterns: ArrayList + public mut prop finallyBlock: Block + public mut prop keywordF: Token + public mut prop keywordT: Token + public mut prop keywordsC: Tokens + public mut prop resourceSpec: ArrayList + public mut prop tryBlock: Block + public init() + public init(inputs: Tokens) +} + +public class TupleLiteral <: Expr { + public mut prop elements: ArrayList + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class TuplePattern <: Pattern { + public mut prop commas: Tokens + public mut prop lParen: Token + public mut prop patterns: ArrayList + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class TupleType <: TypeNode { + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop types: ArrayList + public init() + public init(inputs: Tokens) +} + +public class TypeAliasDecl <: Decl { + public mut prop aliasType: TypeNode + public mut prop assign: Token + public init() + public init(inputs: Tokens) +} + +public class TypeConvExpr <: Expr { + public mut prop expr: Expr + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop targetType: PrimitiveType + public init() + public init(inputs: Tokens) +} + +public open class TypeNode <: Node { + public mut prop typeParameterName: Token + public mut prop colon: Token +} + +public class TypePattern <: Pattern { + public mut prop colon: Token + public mut prop pattern: Pattern + public mut prop patternType: TypeNode + public init() + public init(inputs: Tokens) +} + +public class UnaryExpr <: Expr { + public mut prop expr: Expr + public mut prop op: Token + public init() + public init(inputs: Tokens) +} + +public class VArrayExpr <: Expr { + public mut prop arguments: ArrayList + public mut prop lParen: Token + public mut prop rParen: Token + public mut prop vArrayType: VArrayType + public init() + public init(inputs: Tokens) +} + +public class VArrayType <: TypeNode { + public mut prop dollar: Token + public mut prop elementTy: TypeNode + public mut prop keyword: Token + public mut prop lAngle: Token + public mut prop rAngle: Token + public mut prop size: Token + public init() + public init(inputs: Tokens) +} + +public class VarDecl <: Decl { + public mut prop assign: Token + public mut prop colon: Token + public mut prop declType: TypeNode + public mut prop expr: Expr + public mut prop pattern: Pattern + public init() + public init(inputs: Tokens) + public func isConst(): Bool +} + +public class VarOrEnumPattern <: Pattern { + public mut prop identifier: Token + public init() + public init(identifier: Token) +} + +public class VarPattern <: Pattern { + public mut prop identifier: Token + public init() + public init(identifier: Token) +} + +public abstract class Visitor { + public func breakTraverse(): Unit +} + +public class WhileExpr <: Expr { + public mut prop block: Block + public mut prop condition: Expr + public mut prop keyword: Token + public mut prop lParen: Token + public mut prop rParen: Token + public init() + public init(inputs: Tokens) +} + +public class WildcardExpr <: Expr { + public mut prop keyword: Token + public init() + public init(keyword: Tokens) +} + +public class WildcardPattern <: Pattern { + public mut prop wildcard: Token + public init() + public init(keyword: Tokens) +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum DiagReportLevel { + ERROR + WARNING + public func level(): Int32 +} + +public enum TokenKind <: ToString { + ABSTRACT + ADD + ADD_ASSIGN + AND + AND_ASSIGN + ANNOTATION + ARROW + AS + ASSIGN + AT + BACKARROW + BITAND + BITAND_ASSIGN + BITNOT + BITOR + BITOR_ASSIGN + BITXOR + BITXOR_ASSIGN + BOOLEAN + BOOL_LITERAL + BREAK + CASE + CATCH + CFUNC + CLASS + CLOSEDRANGEOP + COALESCING + COLON + COMMA + COMMENT + COMPOSITION + CONST + CONTINUE + DECR + DIV + DIV_ASSIGN + DO + DOLLAR + DOLLAR_IDENTIFIER + DOT + DOUBLE_ARROW + ELLIPSIS + ELSE + END + ENUM + EQUAL + EXP + EXP_ASSIGN +} + +EXTEND { + FINALLY + FLOAT16 + FLOAT32 + FLOAT64 + FLOAT_LITERAL + FOR + FOREIGN + FUNC + GE + GT + HASH + IDENTIFIER + PACKAGE_IDENTIFIER + IF + ILLEGAL + IMPORT + IN + INCR + INIT + INOUT + INT16 + INT32 + INT64 + INT8 + INTEGER_LITERAL + INTERFACE + INTERNAL + INTNATIVE + IS + JSTRING_LITERAL + LCURL + LE + LET + LPAREN + LSHIFT + LSHIFT_ASSIGN + LSQUARE + LT + MACRO + MAIN + MATCH + MOD + MOD_ASSIGN + MUL + MULTILINE_RAW_STRING + MULTILINE_STRING + MUL_ASSIGN + MUT + NL + NOT + NOTEQ + NOTHING + NOT_IN + OPEN + OPERATOR + OR + OR_ASSIGN + OVERRIDE + PACKAGE + PIPELINE + PRIVATE + PROP + PROTECTED + PUBLIC + QUEST + QUOTE + RANGEOP + RCURL + REDEF + RETURN + RPAREN + RSHIFT + RSHIFT_ASSIGN + RSQUARE + RUNE + RUNE_BYTE_LITERAL + RUNE_LITERAL + SEALED + SEMI + SENTINEL + SPAWN + STATIC + STRING_LITERAL + STRUCT + SUB + SUB_ASSIGN + SUPER + SYNCHRONIZED + THIS + THISTYPE + THROW + TRY + TYPE + UINT16 + UINT32 + UINT64 + UINT8 + UINTNATIVE + UNIT + UNIT_LITERAL + UNSAFE + UPPERBOUND + VAR + VARRAY + WHERE + WHILE + WILDCARD + WITH + public operator func !=(right: TokenKind): Bool + public operator func ==(right: TokenKind): Bool + public func toString(): String +} + +public enum ImportKind <: ToString { + Single + Alias + All + Multi + public func toString(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ASTException <: Exception { + public init() + public init(message: String) +} + +public class MacroContextException <: Exception { + public init() + public init(message: String) +} + +public class ParseASTException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func assertParentContext(parentMacroName: String): Unit +public func cangjieLex(code: String): Tokens +public func cangjieLex(code: String, truncated: Bool): Tokens +public func compareTokens(tokens1: Tokens, tokens2: Tokens): Bool +public func diagReport(level: DiagReportLevel, tokens: Tokens, message: String, hint: String): Unit +public func getChildMessages(children:String): ArrayList +public func getTokenKind(no: UInt16): TokenKind +public func insideParentContext(parentMacroName: String): Bool +public func parseDecl(input: Tokens, astKind!: String = ""): Decl +public func parseDeclFragment(input: Tokens, startFrom !: Int64 = 0): (Decl, Int64) +public func parseExpr(input: Tokens): Expr +public func parseExprFragment(input: Tokens, startFrom !: Int64 = 0): (Expr, Int64) +public func parseProgram(input: Tokens): Program +public func setItem(key: String, value: Bool): Unit +public func setItem(key: String, value: Int64): Unit +public func setItem(key: String, value: String): Unit + +// --------------------------- +// -----interfaces +// --------------------------- +public interface ToBytes { + func toBytes(): Array +} + +public interface ToTokens { + func toTokens(): Tokens +} + +extend Array <: ToTokens { + public func toTokens(): Tokens +} + +extend ArrayList <: ToTokens { + public func toTokens(): Tokens +} + +extend Bool <: ToTokens { + public func toTokens(): Tokens +} + +extend Float16 <: ToTokens { + public func toTokens(): Tokens +} + +extend Float32 <: ToTokens { + public func toTokens(): Tokens +} + +extend Float64 <: ToTokens { + public func toTokens(): Tokens +} + +extend Int16 <: ToTokens { + public func toTokens(): Tokens +} + +extend Int32 <: ToTokens { + public func toTokens(): Tokens +} + +extend Int64 <: ToTokens { + public func toTokens(): Tokens +} + +extend Int8 <: ToTokens { + public func toTokens(): Tokens +} + +extend Rune <: ToTokens { + public func toTokens(): Tokens +} + +extend String <: ToTokens { + public func toTokens(): Tokens +} + +extend Token <: ToTokens { + public func toTokens(): Tokens +} + +extend Tokens <: ToTokens { + public func toTokens(): Tokens +} + +extend UInt16 <: ToTokens { + public func toTokens(): Tokens +} + +extend UInt32 <: ToTokens { + public func toTokens(): Tokens +} + +extend UInt64 <: ToTokens { + public func toTokens(): Tokens +} + +extend UInt8 <: ToTokens { + public func toTokens(): Tokens +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct Position <: ToBytes { + public let column: Int32 + public let fileID: UInt32 + public let line: Int32 + public init() + public init(fileID: UInt32, line: Int32, column: Int32) + public func dump(): Unit + public func isEmpty(): Bool + public func toBytes(): Array + public operator func !=(r: Position): Bool + public operator func ==(r: Position): Bool +} + +public struct Token <: ToBytes { + public let kind: TokenKind + public let pos: Position + public let value: String + public var delimiterNum: UInt16 = 1 + public init() + public init(kind: TokenKind) + public init(kind: TokenKind, value: String) + public func addPosition(fileID: UInt32, line: Int32, colum: Int32): Token + public func dump(): Unit + public func toBytes(): Array + public operator func !=(r: Token): Bool + public operator func +(r: Token): Tokens + public operator func +(r: Tokens): Tokens + public operator func ==(r: Token): Bool +} + + diff --git a/cangjie_libs/std/binary.cjd b/cangjie_libs/std/binary.cjd new file mode 100644 index 0000000000000000000000000000000000000000..45d049740f4e014c259f185aeab3df9d1545f2b7 --- /dev/null +++ b/cangjie_libs/std/binary.cjd @@ -0,0 +1,172 @@ +package std.binary + +// --------------------------- +// -----interfaces +// --------------------------- +public interface BigEndianOrder { + static func readBigEndian(buffer: Array): T + func writeBigEndian(buffer: Array): Int64 +} + +extend Bool <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Bool + public func writeBigEndian(buffer: Array): Int64 +} + +extend Float16 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Float16 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Float32 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Float32 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Float64 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Float64 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Int16 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Int16 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Int32 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Int32 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Int64 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Int64 + public func writeBigEndian(buffer: Array): Int64 +} + +extend Int8 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): Int8 + public func writeBigEndian(buffer: Array): Int64 +} + +extend UInt16 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): UInt16 + public func writeBigEndian(buffer: Array): Int64 +} + +extend UInt32 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): UInt32 + public func writeBigEndian(buffer: Array): Int64 +} + +extend UInt64 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): UInt64 + public func writeBigEndian(buffer: Array): Int64 +} + +extend UInt8 <: BigEndianOrder { + public static func readBigEndian(buffer: Array): UInt8 + public func writeBigEndian(buffer: Array): Int64 +} + +public interface LittleEndianOrder { + static func readLittleEndian(buffer: Array): T + func writeLittleEndian(buffer: Array): Int64 +} + +extend Bool <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Bool + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Float16 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Float16 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Float32 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Float32 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Float64 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Float64 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Int16 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Int16 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Int32 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Int32 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Int64 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Int64 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend Int8 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): Int8 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend UInt16 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): UInt16 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend UInt32 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): UInt32 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend UInt64 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): UInt64 + public func writeLittleEndian(buffer: Array): Int64 +} + +extend UInt8 <: LittleEndianOrder { + public static func readLittleEndian(buffer: Array): UInt8 + public func writeLittleEndian(buffer: Array): Int64 +} + +public interface SwapEndianOrder { + func swapBytes(): T +} + +extend Int16 <: SwapEndianOrder { + public func swapBytes(): Int16 +} + +extend Int32 <: SwapEndianOrder { + public func swapBytes(): Int32 +} + +extend Int64 <: SwapEndianOrder { + public func swapBytes(): Int64 +} + +extend Int8 <: SwapEndianOrder { + public func swapBytes(): Int8 +} + +extend UInt16 <: SwapEndianOrder { + public func swapBytes(): UInt16 +} + +extend UInt32 <: SwapEndianOrder { + public func swapBytes(): UInt32 +} + +extend UInt64 <: SwapEndianOrder { + public func swapBytes(): UInt64 +} + +extend UInt8 <: SwapEndianOrder { + public func swapBytes(): UInt8 +} + + diff --git a/cangjie_libs/std/collection.cjd b/cangjie_libs/std/collection.cjd new file mode 100644 index 0000000000000000000000000000000000000000..d82da40da6d014381512aea3141db450c38bdb3b --- /dev/null +++ b/cangjie_libs/std/collection.cjd @@ -0,0 +1,311 @@ +package std.collection + +// --------------------------- +// -----struct +// --------------------------- +public struct EntryView where K <: Hashable & Equatable { + public func getKey(): K + public func getValue(): ?V + public func isAbsent(): Bool + public mut func setValue(v: V): V +} + +public struct TreeMapNode where K <: Comparable { + public prop key: K + public mut prop value: V + public func backward(bound: K, inclusive!:Bool = true): Iterator<(K, V)> + public func forward(bound: K, inclusive!:Bool = true): Iterator<(K, V)> + public func next(): Option> + public func prev(): Option> +} + + +// --------------------------- +// -----class +// --------------------------- +public class ArrayList <: Collection { + public prop size: Int64 + public init() + public init(elements: Array) + public init(elements: Collection) + public init(capacity: Int64) + public init(size: Int64, initElement: (Int64) -> T) + public func append(element: T): Unit + public func appendAll(elements: Collection): Unit + public func capacity(): Int64 + public func clear(): Unit + public func clone(): ArrayList + public func get(index: Int64): ?T + public unsafe func getRawArray(): Array + public func insert(index: Int64, element: T): Unit + public func insertAll(index: Int64, elements: Collection): Unit + public func isEmpty(): Bool + public func iterator(): Iterator + public func prepend(element: T): Unit + public func prependAll(elements: Collection): Unit + public func remove(index: Int64): T + public func remove(range: Range): Unit + public func removeIf(predicate: (T) -> Bool): Unit + public func reserve(additional: Int64): Unit + public func reverse(): Unit + public func set(index: Int64, element: T): Unit + public func slice(range: Range): ArrayList + public func sortBy(stable!: Bool = false, comparator!: (T, T) -> Ordering): Unit + public func toArray(): Array + public operator func [](index: Int64): T + public operator func [](index: Int64, value!: T): Unit + public operator func [](range: Range): ArrayList +} + +extend ArrayList <: Equatable> where T <: Equatable { + public operator func ==(that: ArrayList): Bool + public operator func !=(that: ArrayList): Bool + public func contains(element: T): Bool +} + +extend ArrayList <: SortExtension where T <: Comparable { + public func sort(stable!: Bool = false): Unit + public func sortDescending(stable!: Bool = false): Unit +} + +extend ArrayList <: ToString where T <: ToString { + public func toString(): String +} + +public class ArrayListIterator <: Iterator { + public init(data: ArrayList) + public func next(): Option + public func iterator(): Iterator +} + +public class HashMapIterator <: Iterator<(K, V)> where K <: Hashable & Equatable { + public init(map: HashMap) + public func iterator(): Iterator<(K, V)> + public func next(): ?(K, V) + public func remove(): Option<(K, V)> +} + +public class HashMap <: Map where K <: Hashable & Equatable { + public prop size: Int64 + public init() + public init(elements: Array<(K, V)>) + public init(elements: Collection<(K, V)>) + public init(capacity: Int64) + public init(size: Int64, initElement: (Int64) -> (K, V)) + public func capacity(): Int64 + public func clear(): Unit + public func clone(): HashMap + public func contains(key: K): Bool + public func containsAll(keys: Collection): Bool + public func entryView(key: K): EntryView + public func get(key: K): Option + public func isEmpty(): Bool + public func iterator(): HashMapIterator + public func keys(): EquatableCollection + public func put(key: K, value: V): Option + public func putAll(elements: Collection<(K, V)>): Unit + public func putIfAbsent(key: K, value: V): Bool + public func remove(key: K): Option + public func removeAll(keys: Collection): Unit + public func removeIf(predicate: (K, V) -> Bool): Unit + public func reserve(additional: Int64): Unit + public func toArray(): Array<(K, V)> + public func values(): Collection + public operator func [](key: K, value!: V): Unit + public operator func [](key: K): V +} + +extend HashMap <: Equatable> where V <: Equatable { + public operator func ==(right: HashMap): Bool + public operator func !=(right: HashMap): Bool +} + +extend HashMap <: ToString where V <: ToString, K <: ToString { + public func toString(): String +} + +public class HashSet <: Set where T <: Hashable & Equatable { + public prop size: Int64 + public init(size: Int64, initElement: (Int64) -> T) + public init() + public init(elements: Array) + public init(elements: Collection) + public init(capacity: Int64) + public func capacity(): Int64 + public func clear(): Unit + public func clone(): HashSet + public func contains(element: T): Bool + public func containsAll(elements: Collection): Bool + public func isEmpty(): Bool + public func iterator(): Iterator + public func put(element: T): Bool + public func putAll(elements: Collection): Unit + public func remove(element: T): Bool + public func removeAll(elements: Collection): Unit + public func removeIf(predicate: (T) -> Bool): Unit + public func reserve(additional: Int64): Unit + public func retainAll(elements: Set): Unit + public func subsetOf(other: Set): Bool + public func toArray(): Array +} + +extend HashSet <: Equatable> { + public operator func ==(that: HashSet): Bool + public operator func !=(that: HashSet): Bool +} + +extend HashSet <: ToString where T <: ToString { + public func toString(): String +} + +public class LinkedListNode { + public prop next: Option> + public prop prev: Option> + public mut prop value: T + public func backward(): Iterator + public func forward(): Iterator +} + +public class LinkedList <: Collection { + public prop first: ?T + public prop last: ?T + public prop size: Int64 + public init() + public init(elements: Array) + public init(elements: Collection) + public init(size: Int64, initElement: (Int64)-> T) + public func append(element: T): LinkedListNode + public func clear(): Unit + public func firstNode(): Option> + public func insertAfter(node: LinkedListNode, element: T): LinkedListNode + public func insertBefore(node: LinkedListNode, element: T): LinkedListNode + public func isEmpty(): Bool + public func iterator(): Iterator + public func lastNode(): Option> + public func nodeAt(index: Int64): Option> + public func popFirst() : ?T + public func popLast() : ?T + public func prepend(element: T): LinkedListNode + public func remove(node: LinkedListNode): T + public func removeIf(predicate: (T)-> Bool): Unit + public func reverse(): Unit + public func splitOff(node: LinkedListNode): LinkedList + public func toArray(): Array +} + +extend LinkedList <: Equatable> where T <: Equatable { + public operator func ==(right: LinkedList): Bool + public operator func !=(right: LinkedList): Bool +} + +extend LinkedList <: ToString where T <: ToString { + public func toString(): String +} + +public class TreeMap <: Map where K <: Comparable { + public prop size: Int64 + public init() + public init(elements: Array<(K,V)>) + public init(elements: Collection<(K, V)>) + public init(size: Int64, initElement: (Int64) -> (K, V)) + public func clear(): Unit + public func clone(): TreeMap + public func contains(key: K): Bool + public func containsAll(keys: Collection): Bool + public func findLower(bound: K, inclusive!: Bool = false): Option> + public func findUpper(bound: K, inclusive!: Bool = false): Option> + public func firstEntry(): Option<(K, V)> + public func get(key: K): Option + public func isEmpty(): Bool + public func iterator(): Iterator<(K, V)> + public func keys(): EquatableCollection + public func lastEntry(): Option<(K, V)> + public func popFirstEntry(): Option<(K, V)> + public func popLastEntry(): Option<(K, V)> + public func put(key: K, value: V): Option + public func putAll(elements: Collection<(K, V)>): Unit + public func remove(key: K): Option + public func removeAll(keys: Collection): Unit + public func removeIf(predicate: (K, V) -> Bool): Unit + public func values(): Collection + public operator func [](key: K, value!: V): Unit + public operator func [](key: K): V +} + +extend TreeMap <: Equatable> where V <: Equatable { + public operator func ==(right: TreeMap): Bool + public operator func !=(right: TreeMap): Bool +} + +extend TreeMap <: ToString where V <: ToString, K <: ToString & Comparable { + public func toString(): String +} + + +// --------------------------- +// -----exception +// --------------------------- +public class ConcurrentModificationException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----function +// --------------------------- +public func all(predicate: (T) -> Bool): (Iterable) -> Bool +public func any(predicate: (T) -> Bool): (Iterable) -> Bool +public func at(n: Int64): (Iterable) -> Option +public func collectArrayList(it: Iterable): ArrayList +public func collectArray(it: Iterable): Array +public func collectHashMap(it: Iterable<(K, V)>): HashMap where K <: Hashable & Equatable +public func collectHashSet(it: Iterable): HashSet where T <: Hashable & Equatable +public func collectString(delimiter!: String = ""): (Iterable) -> String where T <: ToString +public func concat(other: Iterable): (Iterable) -> Iterator +public func contains(element: T): (Iterable) -> Bool where T <: Equatable +public func count(it: Iterable): Int64 +public func enumerate(it: Iterable): Iterator<(Int64, T)> +public func filter(predicate: (T) -> Bool): (Iterable) -> Iterator +public func filterMap(transform: (T)-> ?R): (Iterable) ->Iterator +public func first(it: Iterable): Option +public func flatMap(transform: (T) -> Iterable): (Iterable) -> Iterator +public func flatten(it: Iterable): Iterator where T <: Iterable +public func fold(initial: R, operation: (R, T) -> R): (Iterable) -> R +public func forEach(action: (T) -> Unit): (Iterable) -> Unit +public func inspect(action: (T)->Unit): (Iterable) ->Iterator +public func isEmpty(it: Iterable): Bool +public func last(it: Iterable): Option +public func map(transform: (T) -> R): (Iterable) -> Iterator +public func max(it: Iterable): Option where T <: Comparable +public func min(it: Iterable): Option where T <: Comparable +public func none(predicate: (T) -> Bool): (Iterable) -> Bool +public func reduce(operation: (T, T) -> T): (Iterable) -> Option +public func skip(count: Int64): (Iterable) -> Iterator +public func step(count: Int64): (Iterable) -> Iterator +public func take(count: Int64): (Iterable) -> Iterator +public func zip(other: Iterable): (Iterable) -> Iterator<(T, R)> + +// --------------------------- +// -----interface +// --------------------------- +public interface EquatableCollection <: Collection where T <: Equatable { + func contains(element: T): Bool + func containsAll(elements: Collection): Bool +} + +public interface Set <: Collection where T <: Equatable { + mut func clear(): Unit + func clone(): Set + func contains(element: T): Bool + func containsAll(elements: Collection): Bool + mut func put(element: T): Bool + mut func putAll(elements: Collection): Unit + mut func remove(element: T): Bool + mut func removeAll(elements: Collection): Unit + mut func removeIf(predicate: (T) -> Bool): Unit + mut func retainAll(elements: Set): Unit + func subsetOf(other: Set): Bool +} + + diff --git a/cangjie_libs/std/collection.concurrent.cjd b/cangjie_libs/std/collection.concurrent.cjd new file mode 100644 index 0000000000000000000000000000000000000000..30a3c6cc08066b5ec949fb3fa17671d55ac3c8e9 --- /dev/null +++ b/cangjie_libs/std/collection.concurrent.cjd @@ -0,0 +1,88 @@ +package std.collection.concurrent + +// --------------------------- +// -----class +// --------------------------- +public class ArrayBlockingQueue { + public prop size: Int64 + public let capacity: Int64 + public init(capacity: Int64) + public init(capacity: Int64, elements: Collection) + public func dequeue(): E + public func dequeue(timeout: Duration): Option + public func enqueue(element: E): Unit + public func enqueue(element: E, timeout: Duration): Bool + public func head(): Option + public func tryDequeue(): Option + public func tryEnqueue(element: E): Bool +} + +public class BlockingQueue { + public let capacity: Int64 + public prop size: Int64 + public init() + public init(capacity: Int64) + public init(capacity: Int64, elements: Array) + public init(capacity: Int64, elements: Collection) + public func dequeue(): E + public func dequeue(timeout: Duration): Option + public func enqueue(element: E): Unit + public func enqueue(element: E, timeout: Duration): Bool + public func head(): Option + public func tryDequeue(): Option + public func tryEnqueue(element: E): Bool +} + +public class ConcurrentHashMapIterator <: Iterator<(K, V)> where K <: Hashable & Equatable { + public init(cmap: ConcurrentHashMap) + public func iterator(): Iterator<(K, V)> + public func next(): Option<(K, V)> +} + +public class ConcurrentHashMap <: ConcurrentMap & Collection<(K, V)> where K <: Hashable & Equatable { + public prop size: Int64 + public init(elements: Collection<(K, V)>, concurrencyLevel!: Int64 = 16) + public init(concurrencyLevel!: Int64 = 16) + public init(size: Int64, initElement: (Int64) -> (K, V), concurrencyLevel!: Int64 = 16) + public init(capacity: Int64, concurrencyLevel!: Int64 = 16) + public func contains(key: K): Bool + public func get(key: K): ?V + public func isEmpty(): Bool + public func iterator(): ConcurrentHashMapIterator + public func put(key: K, value: V): ?V + public func putIfAbsent(key: K, value: V): ?V + public func remove(key: K, predicate: (V) -> Bool): ?V + public func remove(key: K): ?V + public func replace(key: K, predicate: (V) -> Bool, eval: (V) -> V): ?V + public func replace(key: K, eval: (V) -> V): ?V + public func replace(key: K, value: V): ?V + public operator func [](key: K): V + public operator func [](key: K, value!: V): Unit +} + +public class NonBlockingQueue { + public prop size: Int64 + public init() + public init(elements: Collection) + public func dequeue(): Option + public func enqueue(element: E): Bool + public func head(): Option +} + + +// --------------------------- +// -----interface +// --------------------------- +public interface ConcurrentMap where K <: Equatable { + func contains(key: K): Bool + func get(key: K): Option + mut func put(key: K, value: V): Option + mut func putIfAbsent(key: K, value: V): Option + mut func remove(key: K): Option + mut func remove(key: K, predicate: (V) -> Bool): Option + mut func replace(key: K, predicate: (V) -> Bool, eval: (V) -> V): Option + mut func replace(key: K, eval: (V) -> V): Option + mut func replace(key: K, value: V): Option +} + + diff --git a/cangjie_libs/std/console.cjd b/cangjie_libs/std/console.cjd new file mode 100644 index 0000000000000000000000000000000000000000..2dd97be6333e5fd34132002bc5c5bb808f13bce8 --- /dev/null +++ b/cangjie_libs/std/console.cjd @@ -0,0 +1,57 @@ +package std.console + +// --------------------------- +// -----class +// --------------------------- +public class Console { + public static prop stdErr: ConsoleWriter + public static prop stdIn: ConsoleReader + public static prop stdOut: ConsoleWriter +} + +public class ConsoleReader <: InputStream { + public func read(): ?Rune + public func read(arr: Array): Int64 + public func readToEnd(): ?String + public func readUntil(predicate: (Rune) -> Bool): ?String + public func readUntil(ch: Rune): ?String + public func readln(): ?String +} + +public class ConsoleWriter <: OutputStream { + public func flush(): Unit + public func write(buffer: Array): Unit + public func write(v: Bool): Unit + public func write(v: Float16): Unit + public func write(v: Float32): Unit + public func write(v: Float64): Unit + public func write(v: Int16): Unit + public func write(v: Int32): Unit + public func write(v: Int64): Unit + public func write(v: Int8): Unit + public func write(v: Rune): Unit + public func write(v: String): Unit + public func write(v: UInt16): Unit + public func write(v: UInt32): Unit + public func write(v: UInt64): Unit + public func write(v: UInt8): Unit + public func write(v: T): Unit where T <: ToString + public func writeln(buffer: Array): Unit + public func writeln(v: Bool): Unit + public func writeln(v: Float16): Unit + public func writeln(v: Float32): Unit + public func writeln(v: Float64): Unit + public func writeln(v: Int16): Unit + public func writeln(v: Int32): Unit + public func writeln(v: Int64): Unit + public func writeln(v: Int8): Unit + public func writeln(v: Rune): Unit + public func writeln(v: String): Unit + public func writeln(v: UInt16): Unit + public func writeln(v: UInt32): Unit + public func writeln(v: UInt64): Unit + public func writeln(v: UInt8): Unit + public func writeln(v: T): Unit where T <: ToString +} + + diff --git a/cangjie_libs/std/convert.cjd b/cangjie_libs/std/convert.cjd new file mode 100644 index 0000000000000000000000000000000000000000..99944595bdf2b088571bb1f1f69d405588897783 --- /dev/null +++ b/cangjie_libs/std/convert.cjd @@ -0,0 +1,76 @@ +package std.convert + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Parsable { + static func parse(value: String): T + static func tryParse(value: String): Option +} + +extend Bool <: Parsable { + public static func parse(data: String): Bool + public static func tryParse(data: String): Option +} + +extend Float16 <: Parsable { + public static func parse(data: String): Float16 + public static func tryParse(data: String): Option +} + +extend Float32 <: Parsable { + public static func parse(data: String): Float32 + public static func tryParse(data: String): Option +} + +extend Float64 <: Parsable { + public static func parse(data: String): Float64 + public static func tryParse(data: String): Option +} + +extend Int16 <: Parsable { + public static func parse(data: String): Int16 + public static func tryParse(data: String): Option +} + +extend Int32 <: Parsable { + public static func parse(data: String): Int32 + public static func tryParse(data: String): Option +} + +extend Int64 <: Parsable { + public static func parse(data: String): Int64 + public static func tryParse(data: String): Option +} + +extend Int8 <: Parsable { + public static func parse(data: String): Int8 + public static func tryParse(data: String): Option +} + +extend Rune <: Parsable { + public static func parse(data: String): Rune + public static func tryParse(data: String): Option +} + +extend UInt16 <: Parsable { + public static func parse(data: String): UInt16 + public static func tryParse(data: String): Option +} + +extend UInt32 <: Parsable { + public static func parse(data: String): UInt32 + public static func tryParse(data: String): Option +} + +extend UInt64 <: Parsable { + public static func parse(data: String): UInt64 + public static func tryParse(data: String): Option +} + +extend UInt8 <: Parsable { + public static func parse(data: String): UInt8 + public static func tryParse(data: String): Option +} + + diff --git a/cangjie_libs/std/core.cjd b/cangjie_libs/std/core.cjd new file mode 100644 index 0000000000000000000000000000000000000000..ddf065c343478098e6d9b5b97d771341c1eecc08 --- /dev/null +++ b/cangjie_libs/std/core.cjd @@ -0,0 +1,964 @@ +package std.core + +// --------------------------- +// -----classes +// --------------------------- +public class ArrayIterator <: Iterator { + public init(data: Array) + public func iterator(): Iterator + public func next(): Option +} + +public class Box { + public var value: T + public init(v: T) +} + +extend Box <: Comparable> where T <: Comparable { + public func compare(that: Box): Ordering + public operator func !=(that: Box): Bool + public operator func <(that: Box): Bool + public operator func <=(that: Box): Bool + public operator func ==(that: Box): Bool + public operator func >(that: Box): Bool + public operator func >=(that: Box): Bool +} + +extend Box <: Hashable where T <: Hashable { + public func hashCode(): Int64 +} + +extend Box <: ToString where T <: ToString { + public func toString(): String +} + +public class Future { + public prop thread: Thread + public func cancel(): Unit + public func get(): T + public func get(ns: Int64): Option + public func tryGet(): Option +} + +public abstract class Iterator <: Iterable { + public func iterator() : Iterator + public func next(): Option +} + +extend Iterator { + public func all(predicate: (T)-> Bool): Bool + public func any(predicate: (T)-> Bool): Bool + public func at(n: Int64): Option + public func concat(other: Iterator): Iterator + public func count(): Int64 + public func enumerate(): Iterator<(Int64, T)> + public func filter(predicate: (T)-> Bool): Iterator + public func filterMap(transform: (T)-> Option): Iterator + public func first(): Option + public func flatMap(transform: (T)-> Iterator): Iterator + public func fold(initial: R, operation: (R, T)->R): R + public func forEach(action: (T)-> Unit): Unit + public func inspect(action: (T) -> Unit): Iterator + public func isEmpty(): Bool + public func last(): Option + public func map(transform: (T)-> R): Iterator + public func none(predicate: (T)-> Bool): Bool + public func reduce(operation: (T, T) -> T): Option + public func skip(count: Int64): Iterator + public func step(count: Int64): Iterator + public func take(count: Int64): Iterator + public func zip(it: Iterator): Iterator<(T, R)> +} + +extend Iterator where T <: Comparable { + public func max(): Option + public func min(): Option +} + +extend Iterator where T <: Equatable { + public func contains(element: T): Bool +} + +public open class Object <: Any { + public const init() +} + +public class RangeIterator <: Iterator where T <: Countable & Comparable & Equatable { + public func iterator(): Iterator + public func next(): Option +} + +public open class StackTraceElement { + public let declaringClass: String + public let fileName: String + public let lineNumber: Int64 + public let methodName: String + public init(declaringClass: String, methodName: String, fileName: String, lineNumber: Int64) +} + +public class StringBuilder <: ToString { + public prop capacity: Int64 + public prop size: Int64 + public init() + public init(value: Array) + public init(capacity: Int64) + public init(r: Rune, n: Int64) + public init(str: String) + public func append(runeArr: Array): Unit + public func append(val: Array): Unit where T <: ToString + public func append(b: Bool): Unit + public func append(cstr: CString): Unit + public func append(n: Float16): Unit + public func append(n: Float32): Unit + public func append(n: Float64): Unit + public func append(n: Int16): Unit + public func append(n: Int32): Unit + public func append(n: Int64): Unit + public func append(n: Int8): Unit + public func append(r: Rune): Unit + public func append(str: String): Unit + public func append(sb: StringBuilder): Unit + public func append(v: T): Unit where T <: ToString + public func append(n: UInt16): Unit + public func append(n: UInt32): Unit + public func append(n: UInt64): Unit + public func append(n: UInt8): Unit + public func appendFromUtf8(arr: Array): Unit + public unsafe func appendFromUtf8Unchecked(arr: Array): Unit + public func reserve(additional: Int64): Unit + public func reset(capacity!: Option = None): Unit + public func toString(): String +} + +public class Thread { + public static prop currentThread: Thread + public prop hasPendingCancellation: Bool + public prop id: Int64 + public mut prop name: String + public static func handleUncaughtExceptionBy(exHandler: (Thread, Exception) -> Unit): Unit +} + +public class ThreadLocal { + public func get(): ?T + public func set(value: ?T): Unit +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum AnnotationKind { + Init + MemberFunction + MemberProperty + MemberVariable + Parameter + Type +} + +public enum Endian { + Big + Little + public static prop Platform: Endian +} + +public enum Option { + None + Some(T) + public func getOrDefault(other: ()->T): T + public func getOrThrow(exception: ()->Exception): T + public func getOrThrow(): T + public func isNone(): Bool + public func isSome(): Bool +} + +extend Option <: Equatable> where T <: Equatable { + public operator func !=(that: Option): Bool + public operator func ==(that: Option): Bool +} + +extend Option <: Hashable where T <: Hashable { + public func hashCode(): Int64 +} + +extend Option <: ToString where T <: ToString { + public func toString(): String +} + +public enum Ordering { + EQ + GT + LT +} + +extend Ordering <: Comparable { + public func compare(that: Ordering): Ordering + public operator func !=(that: Ordering): Bool + public operator func <(that: Ordering): Bool + public operator func <=(that: Ordering): Bool + public operator func ==(that: Ordering): Bool + public operator func >(that: Ordering): Bool + public operator func >=(that: Ordering): Bool +} + +extend Ordering <: Hashable { + public func hashCode(): Int64 +} + +extend Ordering <: ToString { + public func toString(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public open class ArithmeticException <: Exception { + public init() + public init(message: String) + protected open override func getClassName(): String +} + +public open class Error <: ToString { + public open prop message: String + public func getStackTrace(): Array + public open func printStackTrace(): Unit + public open func toString(): String +} + +public open class Exception <: ToString { + public open prop message: String + public init() + public init(message: String) + protected open func getClassName(): String + public func getStackTrace(): Array + public func printStackTrace(): Unit + public open func toString(): String +} + +public open class IllegalArgumentException <: Exception { + public init() + public init(message: String) + protected override open func getClassName(): String +} + +public open class IllegalFormatException <: IllegalArgumentException { + public init() + public init(message: String) +} + +public class IllegalMemoryException <: Exception { + public init() + public init(message: String) +} + +public class IllegalStateException <: Exception { + public init() + public init(message: String) +} + +public class IndexOutOfBoundsException <: Exception { + public init() + public init(message: String) +} + +public class InternalError <: Error {} + +public class NegativeArraySizeException <: Exception { + public init() + public init(message: String) +} + +public class NoneValueException <: Exception { + public init() + public init(message: String) +} + +public class OutOfMemoryError <: Error {} + +public class OverflowException <: ArithmeticException { + public init() + public init(message: String) +} + +public class SpawnException <: Exception { + public init() + public init(message: String) +} + +public class StackOverflowError <: Error { + public override func printStackTrace(): Unit +} + +public class UnsupportedException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func CJ_CORE_AddAtexitCallback(callback: () -> Unit): Unit +public func CJ_CORE_ExecAtexitCallbacks(): Unit +public unsafe func acquireArrayRawData(arr: Array): CPointerHandle where T <: CType +public func alignOf(): UIntNative where T <: CType +public func eprint(str: String, flush!: Bool = true): Unit +public func eprintln(str: String): Unit +public func ifNone(o: Option, action: () -> Unit): Unit +public func ifSome(o: Option, action: (T) -> Unit): Unit +public func print(b: Bool, flush!: Bool = false): Unit +public func print(f: Float16, flush!: Bool = false): Unit +public func print(f: Float32, flush!: Bool = false): Unit +public func print(f: Float64, flush!: Bool = false): Unit +public func print(i: Int16, flush!: Bool = false): Unit +public func print(i: Int32, flush!: Bool = false): Unit +public func print(i: Int64, flush!: Bool = false): Unit +public func print(i: Int8, flush!: Bool = false): Unit +public func print(c: Rune, flush!: Bool = false): Unit +public func print(str: String, flush!: Bool = false): Unit +public func print(i: UInt16, flush!: Bool = false): Unit +public func print(i: UInt32, flush!: Bool = false): Unit +public func print(i: UInt64, flush!: Bool = false): Unit +public func print(i: UInt8, flush!: Bool = false): Unit +public func print(arg: T, flush!: Bool = false): Unit where T <: ToString +public func println(): Unit +public func println(b: Bool): Unit +public func println(f: Float16): Unit +public func println(f: Float32): Unit +public func println(f: Float64): Unit +public func println(i: Int16): Unit +public func println(i: Int32): Unit +public func println(i: Int64): Unit +public func println(i: Int8): Unit +public func println(c: Rune): Unit +public func println(str: String): Unit +public func println(i: UInt16): Unit +public func println(i: UInt32): Unit +public func println(i: UInt64): Unit +public func println(i: UInt8): Unit +public func println(arg: T): Unit where T <: ToString +public func refEq(a: Object, b: Object): Bool +public unsafe func releaseArrayRawData(handle: CPointerHandle): Unit where T <: CType +public func sizeOf(): UIntNative where T <: CType +public unsafe func zeroValue(): T + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Any {} + +public interface ByteExtension {} + +extend Byte <: ByteExtension { + public func isAscii(): Bool + public func isAsciiControl(): Bool + public func isAsciiGraphic(): Bool + public func isAsciiHex(): Bool + public func isAsciiLetter(): Bool + public func isAsciiLowerCase(): Bool + public func isAsciiNumber(): Bool + public func isAsciiNumberOrLetter(): Bool + public func isAsciiOct(): Bool + public func isAsciiPunctuation(): Bool + public func isAsciiUpperCase(): Bool + public func isAsciiWhiteSpace(): Bool + public func toAsciiLowerCase(): Byte + public func toAsciiUpperCase(): Byte +} + +sealed interface CType {} + +public interface Collection <: Iterable { + prop size: Int64 + func isEmpty(): Bool + func toArray(): Array +} + +public interface Comparable <: Equatable & Less & Greater & LessOrEqual & GreaterOrEqual { + func compare(that: T): Ordering +} + +public interface Countable { + func next(right: Int64): T + func position(): Int64 +} + +public interface Equal { + operator func ==(rhs: T): Bool +} + +public interface Equatable <: Equal & NotEqual {} + +public interface FloatToBits {} + +public interface GreaterOrEqual { + operator func >=(rhs: T): Bool +} + +public interface Greater { + operator func >(rhs: T): Bool +} + +public interface Hashable { + func hashCode(): Int64 +} + +public interface Hasher { + func finish(): Int64 + mut func reset(): Unit + mut func write(value: Bool): Unit + mut func write(value: Float16): Unit + mut func write(value: Float32): Unit + mut func write(value: Float64): Unit + mut func write(value: Int16): Unit + mut func write(value: Int32): Unit + mut func write(value: Int64): Unit + mut func write(value: Int8): Unit + mut func write(value: Rune): Unit + mut func write(value: String): Unit + mut func write(value: UInt16): Unit + mut func write(value: UInt32): Unit + mut func write(value: UInt64): Unit + mut func write(value: UInt8): Unit +} + +public interface Iterable { + func iterator(): Iterator +} + +public interface LessOrEqual { + operator func <=(rhs: T): Bool +} + +public interface Less { + operator func <(rhs: T): Bool +} + +public interface NotEqual { + operator func !=(rhs: T): Bool +} + +public interface Resource { + func isClosed(): Bool + func close(): Unit +} + +public interface RuneExtension {} + +public interface ThreadContext { + func end(): Unit + func hasEnded(): Bool +} + +public interface ToString { + func toString(): String +} + + +// --------------------------- +// -----intrinsics +// --------------------------- +extend Bool <: Equatable {} + +extend Bool <: Hashable { + public func hashCode(): Int64 +} + +extend Bool <: ToString { + public func toString(): String +} + +extend CPointer { + public func asResource(): CPointerResource + public func isNotNull(): Bool + public func isNull(): Bool + public unsafe func read(): T + public unsafe func read(idx: Int64): T + public func toUIntNative(): UIntNative + public unsafe func write(idx: Int64, value: T): Unit + public unsafe func write(value: T): Unit + public unsafe operator func +(offset: Int64): CPointer + public unsafe operator func -(offset: Int64): CPointer +} + +extend CString <: ToString { + public func asResource(): CStringResource + public func compare(str: CString): Int32 + public func endsWith(suffix: CString): Bool + public func equals(rhs: CString): Bool + public func equalsLower(rhs: CString): Bool + public func getChars(): CPointer + public func isEmpty(): Bool + public func isNotEmpty(): Bool + public func isNull(): Bool + public func size(): Int64 + public func startsWith(prefix: CString): Bool + public func subCString(beginIndex: UIntNative): CString + public func subCString(beginIndex: UIntNative, subLen: UIntNative): CString + public func toString(): String +} + +extend Float16 <: Comparable { + public func compare(rhs: Float16): Ordering +} + +extend Float16 <: FloatToBits { + public static func fromBits(bits: UInt16): Float16 + public func toBits(): UInt16 +} + +extend Float16 <: Hashable { + public func hashCode(): Int64 +} + +extend Float16 <: ToString { + public func toString(): String +} + +extend Float32 <: Comparable { + public func compare(rhs: Float32): Ordering +} + +extend Float32 <: FloatToBits { + public static func fromBits(bits: UInt32): Float32 + public func toBits(): UInt32 +} + +extend Float32 <: Hashable { + public func hashCode(): Int64 +} + +extend Float32 <: ToString { + public func toString(): String +} + +extend Float64 <: Comparable { + public func compare(rhs: Float64): Ordering +} + +extend Float64 <: FloatToBits { + public static func fromBits(bits: UInt64): Float64 + public func toBits(): UInt64 +} + +extend Float64 <: Hashable { + public func hashCode(): Int64 +} + +extend Float64 <: ToString { + public func toString(): String +} + +extend Int16 <: Comparable { + public func compare(rhs: Int16): Ordering +} + +extend Int16 <: Countable { + public func next(right: Int64): Int16 + public func position(): Int64 +} + +extend Int16 <: Hashable { + public func hashCode(): Int64 +} + +extend Int16 <: ToString { + public func toString(): String +} + +extend Int32 <: Comparable { + public func compare(rhs: Int32): Ordering +} + +extend Int32 <: Countable { + public func next(right: Int64): Int32 + public func position(): Int64 +} + +extend Int32 <: Hashable { + public func hashCode(): Int64 +} + +extend Int32 <: ToString { + public func toString(): String +} + +extend Int64 <: Comparable { + public func compare(rhs: Int64): Ordering +} + +extend Int64 <: Countable { + public func next(right: Int64): Int64 + public func position(): Int64 +} + +extend Int64 <: Hashable { + public func hashCode(): Int64 +} + +extend Int64 <: ToString { + public func toString(): String +} + +extend Int8 <: Comparable { + public func compare(rhs: Int8): Ordering +} + +extend Int8 <: Countable { + public func next(right: Int64): Int8 + public func position(): Int64 +} + +extend Int8 <: Hashable { + public func hashCode(): Int64 +} + +extend Int8 <: ToString { + public func toString(): String +} + +extend IntNative <: Comparable { + public func compare(rhs: IntNative): Ordering +} + +extend IntNative <: Countable { + public func next(right: Int64): IntNative + public func position(): Int64 +} + +extend IntNative <: Hashable { + public func hashCode(): Int64 +} + +extend IntNative <: ToString { + public func toString(): String +} + +extend Rune <: RuneExtension { + public static func fromUtf8(arr: Array, index: Int64): (Rune, Int64) + public static func getPreviousFromUtf8(arr: Array, index: Int64): (Rune, Int64) + public static func intoUtf8Array(c: Rune, arr: Array, index: Int64): Int64 + public static func utf8Size(arr: Array, index: Int64): Int64 + public static func utf8Size(c: Rune): Int64 + public func isAscii(): Bool + public func isAsciiControl(): Bool + public func isAsciiGraphic(): Bool + public func isAsciiHex(): Bool + public func isAsciiLetter(): Bool + public func isAsciiLowerCase(): Bool + public func isAsciiNumber(): Bool + public func isAsciiNumberOrLetter(): Bool + public func isAsciiOct(): Bool + public func isAsciiPunctuation(): Bool + public func isAsciiUpperCase(): Bool + public func isAsciiWhiteSpace(): Bool + public func toAsciiLowerCase(): Rune + public func toAsciiUpperCase(): Rune +} + +extend Rune <: Comparable { + public func compare(rhs: Rune): Ordering +} + +extend Rune <: Countable { + public func next(right: Int64): Rune + public func position(): Int64 +} + +extend Rune <: Hashable { + public func hashCode(): Int64 +} + +extend Rune <: ToString { + public func toString(): String +} + +extend UInt16 <: Comparable { + public func compare(rhs: UInt16): Ordering +} + +extend UInt16 <: Countable { + public func next(right: Int64): UInt16 + public func position(): Int64 +} + +extend UInt16 <: Hashable { + public func hashCode(): Int64 +} + +extend UInt16 <: ToString { + public func toString(): String +} + +extend UInt32 <: Comparable { + public func compare(rhs: UInt32): Ordering +} + +extend UInt32 <: Countable { + public func next(right: Int64): UInt32 + public func position(): Int64 +} + +extend UInt32 <: Hashable { + public func hashCode(): Int64 +} + +extend UInt32 <: ToString { + public func toString(): String +} + +extend UInt64 <: Comparable { + public func compare(rhs: UInt64): Ordering +} + +extend UInt64 <: Countable { + public func next(right: Int64): UInt64 + public func position(): Int64 +} + +extend UInt64 <: Hashable { + public func hashCode(): Int64 +} + +extend UInt64 <: ToString { + public func toString(): String +} + +extend UInt8 <: Comparable { + public func compare(rhs: UInt8): Ordering +} + +extend UInt8 <: Countable { + public func next(right: Int64): UInt8 + public func position(): Int64 +} + +extend UInt8 <: Hashable { + public func hashCode(): Int64 +} + +extend UInt8 <: ToString { + public func toString(): String +} + +extend UIntNative <: Comparable { + public func compare(rhs: UIntNative): Ordering +} + +extend UIntNative <: Countable { + public func next(right: Int64): UIntNative + public func position(): Int64 +} + +extend UIntNative <: Hashable { + public func hashCode(): Int64 +} + +extend UIntNative <: ToString { + public func toString(): String +} + +extend Unit <: Equatable {} + +extend Unit <: Hashable { + public func hashCode(): Int64 +} + +extend Unit <: ToString { + public func toString(): String +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct Array { + public const init() + public init(elements: Collection) + public init(size: Int64, initElement: (Int64) -> T) + public init(size: Int64, item!: T) + public func clone(): Array + public func clone(range: Range) : Array + public func concat(other: Array): Array + public func copyTo(dst: Array, srcStart: Int64, dstStart: Int64, copyLen: Int64): Unit + public func get(index: Int64): Option + public func reverse(): Unit + public func set(index: Int64, element: T): Unit + public func slice(start: Int64, len: Int64): Array + public operator func [](index: Int64): T + public operator func [](index: Int64, value!: T): Unit + public operator func [](range: Range): Array + public operator func [](range: Range, value!: Array): Unit + public operator func [](range: Range, value!: T): Unit +} + +extend Array <: Collection { + public prop size: Int64 + public func isEmpty(): Bool + public func iterator(): Iterator + public func toArray(): Array +} + +extend Array <: Equatable> where T <: Equatable { + public func contains(element: T): Bool + public func indexOf(elements: Array): Option + public func indexOf(elements: Array, fromIndex: Int64): Option + public func indexOf(element: T): Option + public func indexOf(element: T, fromIndex: Int64): Option + public func lastIndexOf(elements: Array): Option + public func lastIndexOf(elements: Array, fromIndex: Int64): Option + public func lastIndexOf(element: T): Option + public func lastIndexOf(element: T, fromIndex: Int64): Option + public func trimLeft(prefix: Array): Array + public func trimRight(suffix: Array): Array + public operator const func !=(that: Array): Bool + public operator const func ==(that: Array): Bool +} + +extend Array <: ToString where T <: ToString { + public func toString(): String +} + +public struct CPointerHandle where T <: CType { + public let array: Array + public let pointer: CPointer + public init() + public init(ptr: CPointer, arr: Array) +} + +public struct CPointerResource <: Resource where T <: CType { + public let value: CPointer + public func close(): Unit + public func isClosed(): Bool +} + +public struct CStringResource <: Resource { + public let value: CString + public func close(): Unit + public func isClosed(): Bool +} + +public struct DefaultHasher <: Hasher { + public init(res!: Int64 = 0) + public func finish(): Int64 + public mut func reset(): Unit + public mut func write(value: Bool): Unit + public mut func write(value: Float16): Unit + public mut func write(value: Float32): Unit + public mut func write(value: Float64): Unit + public mut func write(value: Int16): Unit + public mut func write(value: Int32): Unit + public mut func write(value: Int64): Unit + public mut func write(value: Int8): Unit + public mut func write(value: Rune): Unit + public mut func write(value: String): Unit + public mut func write(value: UInt16): Unit + public mut func write(value: UInt32): Unit + public mut func write(value: UInt64): Unit + public mut func write(value: UInt8): Unit +} + +public struct LibC { + public static unsafe func free(p: CPointer): Unit where T <: CType + public static unsafe func free(cstr: CString): Unit + public static unsafe func mallocCString(str: String): CString + public static func malloc(count!: Int64 = 1): CPointer where T <: CType +} + +public struct Range <: Iterable where T <: Countable & Comparable & Equatable { + public let end: T + public let hasEnd: Bool + public let hasStart: Bool + public let isClosed: Bool + public let start: T + public let step: Int64 + public const init(start: T, end: T, step: Int64, hasStart: Bool, hasEnd: Bool, isClosed: Bool) + public const func isEmpty(): Bool + public func iterator(): Iterator +} + +extend Range <: Equatable> where T <: Countable & Comparable & Equatable { + public operator func !=(that: Range): Bool + public operator func ==(that: Range): Bool +} + +extend Range <: Hashable where T <: Hashable & Countable & Comparable & Equatable { + public func hashCode(): Int64 +} + +public struct String <: Collection & Equatable & Comparable & Hashable & ToString { + public static const empty: String = String() + public prop size: Int64 + public const init() + public init(value: Array) + public init(value: Collection) + public static func fromUtf8(utf8Data: Array): String + public static unsafe func fromUtf8Unchecked(utf8Data: Array): String + public static func join(strArray: Array, delimiter!: String = String.empty): String + public func clone(): String + public func compare(str: String): Ordering + public func contains(str: String): Bool + public func count(str: String): Int64 + public func endsWith(suffix: String): Bool + public unsafe func getRaw(): CPointerHandle + public func hashCode(): Int64 + public func indexOf(b: Byte): Option + public func indexOf(b: Byte, fromIndex: Int64): Option + public func indexOf(str: String): Option + public func indexOf(str: String, fromIndex: Int64): Option + public func isAscii(): Bool + public func isAsciiBlank(): Bool + public func isEmpty(): Bool + public func iterator(): Iterator + public func lastIndexOf(b: Byte): Option + public func lastIndexOf(b: Byte, fromIndex: Int64): Option + public func lastIndexOf(str: String): Option + public func lastIndexOf(str: String, fromIndex: Int64): Option + public func lazySplit(str: String, removeEmpty!: Bool = false): Iterator + public func lazySplit(str: String, maxSplits: Int64, removeEmpty!: Bool = false): Iterator + public func lines(): Iterator + public func padLeft(totalWidth: Int64, padding!: String = " "): String + public func padRight(totalWidth: Int64, padding!: String = " "): String + public unsafe func rawData(): Array + public unsafe func releaseRaw(cp: CPointerHandle): Unit + public func replace(old: String, new: String): String + public func runes(): Iterator + public func split(str: String, removeEmpty!: Bool = false): Array + public func split(str: String, maxSplits: Int64, removeEmpty!: Bool = false): Array + public func startsWith(prefix: String): Bool + public func toArray(): Array + public func toAsciiLower(): String + public func toAsciiTitle(): String + public func toAsciiUpper(): String + public func toRuneArray(): Array + public func toString(): String + public func trimAscii(): String + public func trimAsciiLeft(): String + public func trimAsciiRight(): String + public func trimLeft(prefix: String): String + public func trimRight(suffix: String): String + public func tryGet(index: Int64): Option + public const operator func !=(right: String): Bool + public const operator func *(count: Int64): String + public const operator func +(right: String): String + public const operator func <(right: String): Bool + public const operator func <=(right: String): Bool + public const operator func ==(right: String): Bool + public const operator func >(right: String): Bool + public const operator func >=(right: String): Bool + public const operator func [](index: Int64): Byte + public const operator func [](range: Range): String +} + + +// --------------------------- +// -----types +// --------------------------- +public type Byte = UInt8 {} + +public type Int = Int64 {} + +public type UInt = UInt64 {} + + diff --git a/cangjie_libs/std/crypto.cipher.cjd b/cangjie_libs/std/crypto.cipher.cjd new file mode 100644 index 0000000000000000000000000000000000000000..a1f398b9f6d0fe07c273eb59480504b24cfe7430 --- /dev/null +++ b/cangjie_libs/std/crypto.cipher.cjd @@ -0,0 +1,12 @@ +package std.crypto.cipher + +// --------------------------- +// -----interfaces +// --------------------------- +public interface BlockCipher { + prop blockSize: Int64 + func encrypt(input: Array): Array + func decrypt(input: Array): Array +} + + diff --git a/cangjie_libs/std/crypto.digest.cjd b/cangjie_libs/std/crypto.digest.cjd new file mode 100644 index 0000000000000000000000000000000000000000..ab5f1af054cdfd75ec718af14a80acc557df94a1 --- /dev/null +++ b/cangjie_libs/std/crypto.digest.cjd @@ -0,0 +1,20 @@ +package std.crypto.digest + +// --------------------------- +// -----funcs +// --------------------------- +public func digest(algorithm: T, data: Array): Array where T <: Digest +public func digest(algorithm: T, data: String): Array where T <: Digest + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Digest { + prop blockSize: Int64 + prop size: Int64 + func finish(): Array + mut func reset(): Unit + mut func write(buffer: Array): Unit +} + + diff --git a/cangjie_libs/std/database.sql.cjd b/cangjie_libs/std/database.sql.cjd new file mode 100644 index 0000000000000000000000000000000000000000..59844cf4bcc3db51cf05c170ba0082001b22d2d7 --- /dev/null +++ b/cangjie_libs/std/database.sql.cjd @@ -0,0 +1,411 @@ +package std.database.sql + +// --------------------------- +// -----classes +// --------------------------- +public class DriverManager { + public static func deregister(driverName: String): Unit + public static func drivers(): Array + public static func getDriver(driverName: String): Option + public static func register(driverName: String, driver: Driver): Unit +} + +public class PooledDatasource <: Datasource { + public mut prop connectionTimeout: Duration + public mut prop idleTimeout: Duration + public mut prop keepaliveTime: Duration + public mut prop maxIdleSize: Int32 + public mut prop maxLifeTime: Duration + public mut prop maxSize: Int32 + public init(datasource: Datasource) + public func close(): Unit + public func connect(): Connection + public func isClosed(): Bool + public func setOption(key: String, value: String): Unit +} + +public class SqlBigInt <: SqlDbType { + public prop name: String + public mut prop value: Int64 + public init(v: Int64) +} + +public class SqlBinary <: SqlDbType { + public prop name: String + public mut prop value: Array + public init(v: Array) +} + +public class SqlBlob <: SqlDbType { + public prop name: String + public mut prop value: InputStream + public init(v: InputStream) +} + +public class SqlBool <: SqlDbType { + public prop name: String + public mut prop value: Bool + public init(v: Bool) +} + +public class SqlByte <: SqlDbType { + public prop name: String + public mut prop value: Int8 + public init(v: Int8) +} + +public class SqlChar <: SqlDbType { + public prop name: String + public mut prop value: String + public init(v: String) +} + +public class SqlClob <: SqlDbType { + public prop name: String + public mut prop value: InputStream + public init(v: InputStream) +} + +public class SqlDate <: SqlDbType { + public prop name: String + public mut prop value: DateTime + public init(v: DateTime) +} + +public class SqlDecimal <: SqlDbType { + public prop name: String + public mut prop value: Decimal + public init(v: Decimal) +} + +public class SqlDouble <: SqlDbType { + public prop name: String + public mut prop value: Float64 + public init(v: Float64) +} + +public class SqlInteger <: SqlDbType { + public prop name: String + public mut prop value: Int32 + public init(v: Int32) +} + +public class SqlInterval <: SqlDbType { + public prop name: String + public mut prop value: Duration + public init(v: Duration) +} + +public class SqlNullableBigInt <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Int64 + public init(v: ?Int64) +} + +public class SqlNullableBinary <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Array + public init(v: ?Array) +} + +public class SqlNullableBlob <: SqlNullableDbType { + public prop name: String + public mut prop value: ?InputStream + public init(v: ?InputStream) +} + +public class SqlNullableBool <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Bool + public init(v: ?Bool) +} + +public class SqlNullableByte <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Int8 + public init(v: ?Int8) +} + +public class SqlNullableChar <: SqlNullableDbType { + public prop name: String + public mut prop value: ?String + public init(v: ?String) +} + +public class SqlNullableClob <: SqlNullableDbType { + public prop name: String + public mut prop value: ?InputStream + public init(v: ?InputStream) +} + +public class SqlNullableDate <: SqlNullableDbType { + public prop name: String + public mut prop value: ?DateTime + public init(v: ?DateTime) +} + +public class SqlNullableDecimal <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Decimal + public init(v: ?Decimal) +} + +public class SqlNullableDouble <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Float64 + public init(v: ?Float64) +} + +public class SqlNullableInteger <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Int32 + public init(v: ?Int32) +} + +public class SqlNullableInterval <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Duration + public init(v: ?Duration) +} + +public class SqlNullableReal <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Float32 + public init(v: ?Float32) +} + +public class SqlNullableSmallInt <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Int16 + public init(v: ?Int16) +} + +public class SqlNullableTime <: SqlNullableDbType { + public prop name: String + public mut prop value: ?DateTime + public init(v: ?DateTime) +} + +public class SqlNullableTimeTz <: SqlNullableDbType { + public prop name: String + public mut prop value: ?DateTime + public init(v: ?DateTime) +} + +public class SqlNullableTimestamp <: SqlNullableDbType { + public prop name: String + public mut prop value: ?DateTime + public init(v: ?DateTime) +} + +public class SqlNullableVarBinary <: SqlNullableDbType { + public prop name: String + public mut prop value: ?Array + public init(v: ?Array) +} + +public class SqlNullableVarchar <: SqlNullableDbType { + public prop name: String + public mut prop value: ?String + public init(v: ?String) +} + +public class SqlOption { + public static const ConnectionTimeout = "connection_timeout" + public static const Database = "database" + public static const Driver = "driver" + public static const Encoding = "encoding" + public static const FetchRows = "fetch_rows" + public static const Host = "host" + public static const Password = "password" + public static const QueryTimeout = "query_timeout" + public static const SSLCA = "ssl.ca" + public static const SSLCert = "ssl.cert" + public static const SSLKey = "ssl.key" + public static const SSLKeyPassword = "ssl.key.password" + public static const SSLMode = "ssl.mode" + public static const SSLModeDisabled = "ssl.mode.disabled" + public static const SSLModePreferred = "ssl.mode.preferred" + public static const SSLModeRequired = "ssl.mode.required" + public static const SSLModeVerifyCA = "ssl.mode.verify_ca" + public static const SSLModeVerifyFull = "ssl.mode.verify_full" + public static const SSLSni = "ssl.sni" + public static const Tls12Ciphersuites = "tls1.2.ciphersuites" + public static const Tls13Ciphersuites = "tls1.3.ciphersuites" + public static const TlsVersion = "tls.version" + public static const URL = "url" + public static const UpdateTimeout = "update_timeout" + public static const Username = "username" +} + +public class SqlReal <: SqlDbType { + public prop name: String + public mut prop value: Float32 + public init(v: Float32) +} + +public class SqlSmallInt <: SqlDbType { + public prop name: String + public mut prop value: Int16 + public init(v: Int16) +} + +public class SqlTime <: SqlDbType { + public prop name: String + public mut prop value: DateTime + public init(v: DateTime) +} + +public class SqlTimeTz <: SqlDbType { + public prop name: String + public mut prop value: DateTime + public init(v: DateTime) +} + +public class SqlTimestamp <: SqlDbType { + public prop name: String + public mut prop value: DateTime + public init(v: DateTime) +} + +public class SqlVarBinary <: SqlDbType { + public prop name: String + public mut prop value: Array + public init(v: Array) +} + +public class SqlVarchar <: SqlDbType { + public prop name: String + public mut prop value: String + public init(v: String) +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum ConnectionState <: Equatable { + Broken + Closed + Connected + Connecting + public operator func !=(rhs: ConnectionState): Bool + public operator func ==(rhs: ConnectionState): Bool +} + +public enum TransactionAccessMode <: ToString & Hashable & Equatable { + ReadOnly + ReadWrite + Unspecified + public func hashCode(): Int64 + public func toString(): String + public operator func != (rhs: TransactionAccessMode): Bool + public operator func == (rhs: TransactionAccessMode): Bool +} + +public enum TransactionDeferrableMode <: ToString & Hashable & Equatable { + Deferrable + NotDeferrable + Unspecified + public func hashCode(): Int64 + public func toString(): String + public operator func != (rhs: TransactionDeferrableMode): Bool + public operator func == (rhs: TransactionDeferrableMode): Bool +} + +public enum TransactionIsoLevel <: ToString & Hashable & Equatable { + Chaos + Linearizable + ReadCommitted + ReadUncommitted + RepeatableRead + Serializable + Snapshot + Unspecified + public func hashCode(): Int64 + public func toString(): String + public operator func != (rhs: TransactionIsoLevel): Bool + public operator func == (rhs: TransactionIsoLevel): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public open class SqlException <: Exception { + public prop errorCode: Int64 + public override prop message: String + public prop sqlState: String + public init() + public init(message: String) + public init(message: String, sqlState: String, errorCode: Int64) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface ColumnInfo { + prop displaySize: Int64 + prop length: Int64 + prop name: String + prop nullable: Bool + prop scale: Int64 + prop typeName: String +} + +public interface Connection <: Resource { + prop state: ConnectionState + func createTransaction(): Transaction + func getMetaData(): Map + func prepareStatement(sql: String): Statement +} + +public interface Datasource <: Resource { + func connect(): Connection + func setOption(key: String, value: String): Unit +} + +public interface Driver { + prop name: String + prop preferredPooling: Bool + prop version: String + func open(connectionString: String, opts: Array<(String, String)>): Datasource +} + +public interface QueryResult <: Resource { + prop columnInfos: Array + func next(values: Array): Bool +} + +public interface SqlDbType { + prop name: String +} + +public interface SqlNullableDbType <: SqlDbType {} + +public interface Statement <: Resource { + prop parameterColumnInfos: Array + func query(params: Array): QueryResult + func setOption(key: String, value: String): Unit + func update(params: Array): UpdateResult +} + +public interface Transaction { + mut prop accessMode: TransactionAccessMode + mut prop deferrableMode: TransactionDeferrableMode + mut prop isoLevel: TransactionIsoLevel + func begin(): Unit + func commit(): Unit + func release(savePointName: String): Unit + func rollback(): Unit + func rollback(savePointName: String): Unit + func save(savePointName: String): Unit +} + +public interface UpdateResult { + prop lastInsertId: Int64 + prop rowCount: Int64 +} + + diff --git a/cangjie_libs/std/deriving.cjd b/cangjie_libs/std/deriving.cjd new file mode 100644 index 0000000000000000000000000000000000000000..e842934f4e8eae8cdbb734d461a264098b8d6a17 --- /dev/null +++ b/cangjie_libs/std/deriving.cjd @@ -0,0 +1,10 @@ +package std.deriving + +// --------------------------- +// -----macros +// --------------------------- +public macro @Derive(input: Tokens): Tokens +public macro @DeriveExclude(input: Tokens): Tokens +public macro @DeriveInclude(input: Tokens): Tokens +public macro @DeriveOrder(input: Tokens): Tokens + diff --git a/cangjie_libs/std/ffi.python.cjd b/cangjie_libs/std/ffi.python.cjd new file mode 100644 index 0000000000000000000000000000000000000000..5c0b9c7e8f21ee1431cdead0c1390fa8c7be16fc --- /dev/null +++ b/cangjie_libs/std/ffi.python.cjd @@ -0,0 +1,56 @@ +package std.ffi.python + +// --------------------------- +// -----classes +// --------------------------- +public class PyBool <: PyObj {} + +public class PyCFunc <: PyObj {} + +public class PyDict <: PyObj where K <: Hashable & Equatable & PyFFIType {} + +public class PyFloat <: PyObj {} + +public class PyList <: PyObj where T <: PyFFIType {} + +public class PyLong <: PyObj {} + +public open class PyObj <: ToString & PyFFIType & Hashable & Equatable {} + +public class PyObjIterator <: Iterator {} + +public class PySet <: PyObj where T <: Hashable & Equatable & PyFFIType {} + +public class PySlice <: PyObj where T <: Countable & Comparable & Equatable & CjObj {} + +public class PyString <: PyObj {} + +public class PyTuple <: PyObj {} + +public class PythonBuiltins {} + +public class PythonLogger <: Logger {} + + +// --------------------------- +// -----vars +// --------------------------- +public let PYLOG: PythonLogger = PythonLogger() {} + +public let Python: PythonBuiltins = PythonBuiltins() {} + + +// --------------------------- +// -----exception +// --------------------------- +public class PythonException <: Exception {} + + +// --------------------------- +// -----interface +// --------------------------- +public interface CjObj <: PyFFIType {} + +public interface PyFFIType {} + + diff --git a/cangjie_libs/std/format.cjd b/cangjie_libs/std/format.cjd new file mode 100644 index 0000000000000000000000000000000000000000..920ccf20964597219cd208516eb5bbd5582b1301 --- /dev/null +++ b/cangjie_libs/std/format.cjd @@ -0,0 +1,58 @@ +package std.format + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Formatter { + func format(fmt: String): String +} + +extend Float16 <: Formatter { + public func format(fmt: String): String +} + +extend Float32 <: Formatter { + public func format(fmt: String): String +} + +extend Float64 <: Formatter { + public func format(fmt: String): String +} + +extend Int16 <: Formatter { + public func format(fmt: String): String +} + +extend Int32 <: Formatter { + public func format(fmt: String): String +} + +extend Int64 <: Formatter { + public func format(fmt: String): String +} + +extend Int8 <: Formatter { + public func format(fmt: String): String +} + +extend Rune <: Formatter { + public func format(fmt: String): String +} + +extend UInt16 <: Formatter { + public func format(fmt: String): String +} + +extend UInt32 <: Formatter { + public func format(fmt: String): String +} + +extend UInt64 <: Formatter { + public func format(fmt: String): String +} + +extend UInt8 <: Formatter { + public func format(fmt: String): String +} + + diff --git a/cangjie_libs/std/fs.cjd b/cangjie_libs/std/fs.cjd new file mode 100644 index 0000000000000000000000000000000000000000..6f3c175af5ff54f0c3aa12ff8172ab9aa9dfea65 --- /dev/null +++ b/cangjie_libs/std/fs.cjd @@ -0,0 +1,143 @@ +package std.fs + +// --------------------------- +// -----classes +// --------------------------- +public class Directory <: Iterable { + public prop info: FileInfo + public init(path: Path) + public init(path: String) + public static func copy(sourceDirPath: Path, destinationDirPath: Path, overwrite: Bool): Unit + public static func copy(sourceDirPath: String, destinationDirPath: String, overwrite: Bool): Unit + public static func create(path: Path, recursive!: Bool = false): Directory + public static func create(path: String, recursive!: Bool = false): Directory + public static func createTemp(directoryPath: Path): Directory + public static func createTemp(directoryPath: String): Directory + public static func delete(path: Path, recursive!: Bool = false): Unit + public static func delete(path: String, recursive!: Bool = false): Unit + public static func exists(path: Path): Bool + public static func exists(path: String): Bool + public static func move(sourceDirPath: Path, destinationDirPath: Path, overwrite: Bool): Unit + public static func move(sourceDirPath: String, destinationDirPath: String, overwrite: Bool): Unit + public func createFile(name: String): File + public func createSubDirectory(name: String): Directory + public func directories(): Iterator + public func directoryList(): ArrayList + public func entryList(): ArrayList + public func fileList(): ArrayList + public func files(): Iterator + public func isEmpty(): Bool + public func iterator(): Iterator +} + +public class File <: Resource & IOStream & Seekable { + public prop fileDescriptor: FileDescriptor + public prop info: FileInfo + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public init(path: Path, openOption: OpenOption) + public init(path: String, openOption: OpenOption) + public static func copy(sourcePath: Path, destinationPath: Path, overwrite: Bool): Unit + public static func copy(sourcePath: String, destinationPath: String, overwrite: Bool): Unit + public static func create(path: Path): File + public static func create(path: String): File + public static func createTemp(directoryPath: Path): File + public static func createTemp(directoryPath: String): File + public static func delete(path: Path): Unit + public static func delete(path: String): Unit + public static func exists(path: Path): Bool + public static func exists(path: String): Bool + public static func move(sourcePath: Path, destinationPath: Path, overwrite: Bool): Unit + public static func move(sourcePath: String, destinationPath: String, overwrite: Bool): Unit + public static func openRead(path: Path): File + public static func openRead(path: String): File + public static func readFrom(path: Path): Array + public static func readFrom(path: String): Array + public static func writeTo(path: Path, buffer: Array, openOption!: OpenOption = CreateOrAppend): Unit + public static func writeTo(path: String, buffer: Array, openOption!: OpenOption = CreateOrAppend): Unit + public func canRead(): Bool + public func canWrite(): Bool + public func close(): Unit + public func copyTo(out: OutputStream): Unit + public func flush(): Unit + public func isClosed(): Bool + public func read(buffer: Array): Int64 + public func readToEnd(): Array + public func seek(sp: SeekPosition): Int64 + public func write(buffer: Array): Unit +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum OpenOption { + Append + Create(Bool) + CreateOrAppend + CreateOrTruncate(Bool) + Open(Bool, Bool) + Truncate(Bool) +} + + +// --------------------------- +// -----exceptions +// --------------------------- + +// --------------------------- +// -----structs +// --------------------------- +public struct FileDescriptor { + public prop fileHandle: CPointer + public prop fileHandle: Int32 +} + +public struct FileInfo <: Equatable { + public prop creationTime: DateTime + public prop lastAccessTime: DateTime + public prop lastModificationTime: DateTime + public prop length: Int64 + public prop parentDirectory: Option + public prop path: Path + public prop symbolicLinkTarget: Option + public init(path: Path) + public init(path: String) + public func canExecute(): Bool + public func canRead(): Bool + public func canWrite(): Bool + public func isDirectory(): Bool + public func isFile(): Bool + public func isHidden(): Bool + public func isReadOnly(): Bool + public func isSymbolicLink(): Bool + public func setExecutable(executable: Bool): Bool + public func setReadable(readable: Bool): Bool + public func setWritable(writable: Bool): Bool + public operator func !=(that: FileInfo): Bool + public operator func ==(that: FileInfo): Bool +} + +public struct Path <: Equatable & Hashable & ToString { + public prop directoryName: Option + public prop extensionName: Option + public prop fileName: Option + public prop fileNameWithoutExtension: Option + public init(rawPath: String) + public func hashCode(): Int64 + public func isAbsolute(): Bool + public func isDirectory(): Bool + public func isFile(): Bool + public func isRelative(): Bool + public func isSymbolicLink(): Bool + public func join(path: Path): Path + public func join(path: String): Path + public func split(): (Option, Option) + public func toCanonical(): Path + public func toString(): String + public operator func !=(that: Path): Bool + public operator func ==(that: Path): Bool +} + + diff --git a/cangjie_libs/std/io.cjd b/cangjie_libs/std/io.cjd new file mode 100644 index 0000000000000000000000000000000000000000..1d2845853893aa0f1842485758f859628a44c96c --- /dev/null +++ b/cangjie_libs/std/io.cjd @@ -0,0 +1,196 @@ +package std.io + +// --------------------------- +// -----classes +// --------------------------- +public class BufferedInputStream <: InputStream where T <: InputStream { + public init(input: T) + public init(input: T, buffer: Array) + public init(input: T, capacity: Int64) + public func read(buffer: Array): Int64 + public func reset(input: T): Unit +} + +extend BufferedInputStream <: Resource where T <: Resource { + public func close(): Unit + public func isClosed(): Bool +} + +extend BufferedInputStream <: Seekable where T <: Seekable { + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public func seek(sp: SeekPosition): Int64 +} + +public class BufferedOutputStream <: OutputStream where T <: OutputStream { + public init(output: T) + public init(output: T, buffer: Array) + public init(output: T, capacity: Int64) + public func flush(): Unit + public func reset(output: T): Unit + public func write(buffer: Array): Unit +} + +extend BufferedOutputStream <: Resource where T <: Resource { + public func close(): Unit + public func isClosed(): Bool +} + +extend BufferedOutputStream <: Seekable where T <: Seekable { + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public func seek(sp: SeekPosition): Int64 +} + +public class ByteArrayStream <: IOStream & Seekable { + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public init() + public init(capacity: Int64) + public static func fromString(data: String): ByteArrayStream + public func bytes(): Array + public func capacity(): Int64 + public func clear(): Unit + public func clone(): ByteArrayStream + public func copyTo(output: OutputStream): Unit + public func read(buffer: Array): Int64 + public func readString(): String + public unsafe func readStringUnchecked(): String + public func readToEnd(): Array + public func reserve(additional: Int64): Unit + public func seek(sp: SeekPosition): Int64 + public func write(buffer: Array): Unit +} + +public class ChainedInputStream <: InputStream where T <: InputStream { + public init(input: Array) + public func read(buffer: Array): Int64 +} + +public class MultiOutputStream <: OutputStream where T <: OutputStream { + public init(output: Array) + public func flush(): Unit + public func write(buffer: Array): Unit +} + +public class StringReader where T <: InputStream { + public init(input: T) + public func lines(): Iterator + public func read(): ?Rune + public func readToEnd(): String + public func readUntil(predicate: (Rune)->Bool): Option + public func readUntil(v: Rune): Option + public func readln(): Option + public func runes(): Iterator +} + +extend StringReader <: Resource where T <: Resource { + public func close(): Unit + public func isClosed(): Bool +} + +extend StringReader <: Seekable where T <: Seekable { + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public func seek(sp: SeekPosition): Int64 +} + +public class StringWriter where T <: OutputStream { + public init(output: T) + public func flush(): Unit + public func write(v: Bool): Unit + public func write(v: Float16): Unit + public func write(v: Float32): Unit + public func write(v: Float64): Unit + public func write(v: Int16): Unit + public func write(v: Int32): Unit + public func write(v: Int64): Unit + public func write(v: Int8): Unit + public func write(v: Rune): Unit + public func write(v: String): Unit + public func write(v: UInt16): Unit + public func write(v: UInt32): Unit + public func write(v: UInt64): Unit + public func write(v: UInt8): Unit + public func write(v: T): Unit where T <: ToString + public func writeln(): Unit + public func writeln(v: Bool): Unit + public func writeln(v: Float16): Unit + public func writeln(v: Float32): Unit + public func writeln(v: Float64): Unit + public func writeln(v: Int16): Unit + public func writeln(v: Int32): Unit + public func writeln(v: Int64): Unit + public func writeln(v: Int8): Unit + public func writeln(v: Rune): Unit + public func writeln(v: String): Unit + public func writeln(v: UInt16): Unit + public func writeln(v: UInt32): Unit + public func writeln(v: UInt64): Unit + public func writeln(v: UInt8): Unit + public func writeln(v: T): Unit where T <: ToString +} + +extend StringWriter <: Resource where T <: Resource { + public func close(): Unit + public func isClosed(): Bool +} + +extend StringWriter <: Seekable where T <: Seekable { + public prop length: Int64 + public prop position: Int64 + public prop remainLength: Int64 + public func seek(sp: SeekPosition): Int64 +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum SeekPosition { + Begin(Int64) + Current(Int64) + End(Int64) +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ContentFormatException <: Exception { + public init() + public init(message: String) +} + +public class IOException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface IOStream <: InputStream & OutputStream {} + +public interface InputStream { + func read(buffer: Array): Int64 +} + +public interface OutputStream { + func flush(): Unit + func write(buffer: Array): Unit +} + +public interface Seekable { + prop length: Int64 + prop position: Int64 + prop remainLength: Int64 + func seek(sp: SeekPosition): Int64 +} + + diff --git a/cangjie_libs/std/log.cjd b/cangjie_libs/std/log.cjd new file mode 100644 index 0000000000000000000000000000000000000000..cdec49f4fab9e94ac840126076c0c1c5aa2489e4 --- /dev/null +++ b/cangjie_libs/std/log.cjd @@ -0,0 +1,52 @@ +package std.log + +// --------------------------- +// -----classes +// --------------------------- +public class SimpleLogger <: Logger { + public mut prop level: LogLevel + public init() + public init(name: String, level: LogLevel, output: OutputStream) + public func debug(msg: String): Unit + public func error(msg: String): Unit + public func flush(): Unit + public func info(msg: String): Unit + public func log(level: LogLevel, msg: String): Unit + public func setOutput(output: OutputStream): Unit + public func trace(msg: String): Unit + public func warn(msg: String): Unit +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum LogLevel <: ToString { + ALL + DEBUG + ERROR + INFO + OFF + TRACE + WARN + public func level(): Int64 + public func toString(): String + public operator func >=(target: LogLevel): Bool +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Logger { + mut prop level: LogLevel + func debug(msg: String): Unit + func error(msg: String): Unit + func info(msg: String): Unit + func log(level: LogLevel, msg: String): Unit + func setOutput(output: OutputStream): Unit + func trace(msg: String): Unit + func warn(msg: String): Unit +} + + diff --git a/cangjie_libs/std/math.cjd b/cangjie_libs/std/math.cjd new file mode 100644 index 0000000000000000000000000000000000000000..cf8a8b3f32cc088509ca417bf26126beb8b874c8 --- /dev/null +++ b/cangjie_libs/std/math.cjd @@ -0,0 +1,809 @@ +package std.math + +// --------------------------- +// -----funcs +// --------------------------- +public func abs(x: Float16): Float16 { + import std.math.absmain() { let n: Float16 = -23.0 let abs = abs(n) println(abs)} +} + +public func abs(x: Float32): Float32 { + import std.math.absmain() { let n: Float32 = -23.0 let abs = abs(n) println(abs)} +} + +public func abs(x: Float64): Float64 { + import std.math.absmain() { let n: Float64 = -23.0 let abs = abs(n) println(abs)} +} + +public func abs(x: Int16): Int16 { + import std.math.absmain() { let n: Int16 = -23 let abs = abs(n) println(abs)} +} + +public func abs(x: Int32): Int32 { + import std.math.absmain() { let n: Int32 = -23 let abs = abs(n) println(abs)} +} + +public func abs(x: Int64): Int64 { + import std.math.absmain() { let n: Int64 = -23 let abs = abs(n) println(abs)} +} + +public func abs(x: Int8): Int8 { + import std.math.absmain() { let n: Int8 = -23 let abs = abs(n) println(abs)} +} + +public func acos(x: Float16): Float16 { + import std.math.acosmain() { let n: Float16 = 1.0 let acos = acos(n) println(acos)} +} + +public func acos(x: Float32): Float32 { + import std.math.acosmain() { let n: Float32 = 1.0 let acos = acos(n) println(acos)} +} + +public func acos(x: Float64): Float64 { + import std.math.acosmain() { let n: Float64 = 1.0 let acos = acos(n) println(acos)} +} + +public func acosh(x: Float16): Float16 { + import std.math.acoshmain() { let n: Float16 = 1.0 let acosh = acosh(n) println(acosh)} +} + +public func acosh(x: Float32): Float32 { + import std.math.acoshmain() { let n: Float32 = 1.0 let acosh = acosh(n) println(acosh)} +} + +public func acosh(x: Float64): Float64 { + import std.math.acoshmain() { let n: Float64 = 1.0 let acosh = acosh(n) println(acosh)} +} + +public func asin(x: Float16): Float16 { + import std.math.asinmain() { let n: Float16 = 0.0 let asin = asin(n) println(asin)} +} + +public func asin(x: Float32): Float32 { + import std.math.asinmain() { let n: Float32 = 0.0 let asin = asin(n) println(asin)} +} + +public func asin(x: Float64): Float64 { + import std.math.asinmain() { let n: Float64 = 0.0 let asin = asin(n) println(asin)} +} + +public func asinh(x: Float16): Float16 { + import std.math.asinhmain() { let n: Float16 = 0.0 let asinh = asinh(n) println(asinh)} +} + +public func asinh(x: Float32): Float32 { + import std.math.asinhmain() { let n: Float32 = 0.0 let asinh = asinh(n) println(asinh)} +} + +public func asinh(x: Float64): Float64 { + import std.math.asinhmain() { let n: Float64 = 0.0 let asinh = asinh(n) println(asinh)} +} + +public func atan(x: Float16): Float16 { + import std.math.atanmain() { let n: Float16 = 0.0 let atan = atan(n) println(atan)} +} + +public func atan(x: Float32): Float32 { + import std.math.atanmain() { let n: Float32 = 0.0 let atan = atan(n) println(atan)} +} + +public func atan(x: Float64): Float64 { + import std.math.atanmain() { let n: Float64 = 0.0 let atan = atan(n) println(atan)} +} + +public func atanh(x: Float16): Float16 { + import std.math.atanhmain() { let n: Float16 = 0.0 let atanh = atanh(n) println(atanh)} +} + +public func atanh(x: Float32): Float32 { + import std.math.atanhmain() { let n: Float32 = 0.0 let atanh = atanh(n) println(atanh)} +} + +public func atanh(x: Float64): Float64 { + import std.math.atanhmain() { let n: Float64 = 0.0 let atanh = atanh(n) println(atanh)} +} + +public func cbrt(x: Float16): Float16 { + import std.math.cbrtmain() { let n: Float16 = -1000.0 let cbrt = cbrt(n) println(cbrt)} +} + +public func cbrt(x: Float32): Float32 { + import std.math.cbrtmain() { let n: Float32 = -1000.0 let cbrt = cbrt(n) println(cbrt)} +} + +public func cbrt(x: Float64): Float64 { + import std.math.cbrtmain() { let n: Float64 = -1000.0 let cbrt = cbrt(n) println(cbrt)} +} + +public func ceil(x: Float16): Float16 { + import std.math.ceilmain() { let n: Float16 = 0.7 let ceil = ceil(n) println(ceil)} +} + +public func ceil(x: Float32): Float32 { + import std.math.ceilmain() { let n: Float32 = 0.7 let ceil = ceil(n) println(ceil)} +} + +public func ceil(x: Float64): Float64 { + import std.math.ceilmain() { let n: Float64 = 0.7 let ceil = ceil(n) println(ceil)} +} + +public func checkedAbs(x: Int16): Option { + import std.math.checkedAbsmain() { let n: Int16 = -23 let checkedAbs = checkedAbs(n) println(checkedAbs)} +} + +public func checkedAbs(x: Int32): Option { + import std.math.checkedAbsmain() { let n: Int32 = -23 let checkedAbs = checkedAbs(n) println(checkedAbs)} +} + +public func checkedAbs(x: Int64): Option { + import std.math.checkedAbsmain() { let n: Int64 = -23 let checkedAbs = checkedAbs(n) println(checkedAbs)} +} + +public func checkedAbs(x: Int8): Option { + import std.math.checkedAbsmain() { let n: Int8 = -23 let checkedAbs = checkedAbs(n) println(checkedAbs)} +} + +public func clamp(v: Float16, min: Float16, max: Float16): Float16 { + import std.math.clampmain() { let n: Float16 = -23.0 let clamp = clamp(n, -100.0, 100.0) println(clamp)} +} + +public func clamp(v: Float32, min: Float32, max: Float32): Float32 { + import std.math.clampmain() { let n: Float32 = -23.0 let clamp = clamp(n, -100.0, 100.0) println(clamp)} +} + +public func clamp(v: Float64, min: Float64, max: Float64): Float64 { + import std.math.clampmain() { let n: Float64 = -23.0 let clamp = clamp(n, -100.0, 100.0) println(clamp)} +} + +public func cos(x: Float16): Float16 { + import std.math.cosmain() { let n: Float16 = 3.14159265 let cos = cos(n) println(cos)} +} + +public func cos(x: Float32): Float32 { + import std.math.cosmain() { let n: Float32 = 3.14159265 let cos = cos(n) println(cos)} +} + +public func cos(x: Float64): Float64 { + import std.math.cosmain() { let n: Float64 = 3.14159265 let cos = cos(n) println(cos)} +} + +public func cosh(x: Float16): Float16 { + import std.math.coshmain() { let n: Float16 = 0.0 let cosh = cosh(n) println(cosh)} +} + +public func cosh(x: Float32): Float32 { + import std.math.coshmain() { let n: Float32 = 0.0 let cosh = cosh(n) println(cosh)} +} + +public func cosh(x: Float64): Float64 { + import std.math.coshmain() { let n: Float64 = 0.0 let cosh = cosh(n) println(cosh)} +} + +public func countOne(x: Int16): Int8 { + import std.math.countOnemain() { let n: Int16 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: Int32): Int8 { + import std.math.countOnemain() { let n: Int32 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: Int64): Int8 { + import std.math.countOnemain() { let n: Int64 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: Int8): Int8 { + import std.math.countOnemain() { let n: Int8 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: UInt16): Int8 { + import std.math.countOnemain() { let n: UInt16 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: UInt32): Int8 { + import std.math.countOnemain() { let n: UInt32 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: UInt64): Int8 { + import std.math.countOnemain() { let n: UInt64 = 15 let countOne = countOne(n) println(countOne)} +} + +public func countOne(x: UInt8): Int8 { + import std.math.countOnemain() { let n: UInt8 = 15 let countOne = countOne(n) println(countOne)} +} + +public func erf(x: Float16): Float16 { + import std.math.erfmain() { let n: Float16 = 5.0 let erf = erf(n) println(erf)} +} + +public func erf(x: Float32): Float32 { + import std.math.erfmain() { let n: Float32 = 5.0 let erf = erf(n) println(erf)} +} + +public func erf(x: Float64): Float64 { + import std.math.erfmain() { let n: Float64 = 5.0 let erf = erf(n) println(erf)} +} + +public func exp(x: Float16): Float16 { + import std.math.expmain() { let n: Float16 = 1.0 let exp = exp(n) println(exp)} +} + +public func exp(x: Float32): Float32 { + import std.math.expmain() { let n: Float32 = 1.0 let exp = exp(n) println(exp)} +} + +public func exp(x: Float64): Float64 { + import std.math.expmain() { let n: Float64 = 1.0 let exp = exp(n) println(exp)} +} + +public func exp2(x: Float16): Float16 { + import std.math.exp2main() { let n: Float16 = 10.0 let exp2 = exp2(n) println(exp2)} +} + +public func exp2(x: Float32): Float32 { + import std.math.exp2main() { let n: Float32 = 10.0 let exp2 = exp2(n) println(exp2)} +} + +public func exp2(x: Float64): Float64 { + import std.math.exp2main() { let n: Float64 = 10.0 let exp = exp2(n) println(exp)} +} + +public func floor(x: Float16): Float16 { + import std.math.floormain() { let n: Float16 = 10.5 let floor = floor(n) println(floor)} +} + +public func floor(x: Float32): Float32 { + import std.math.floormain() { let n: Float32 = 10.5 let floor = floor(n) println(floor)} +} + +public func floor(x: Float64): Float64 { + import std.math.floormain() { let n: Float64 = 10.5 let floor = floor(n) println(floor)} +} + +public func gamma(x: Float16): Float16 { + import std.math.gammamain() { let n: Float16 = -1.1 let gamma = gamma(n) println(gamma)} +} + +public func gamma(x: Float32): Float32 { + import std.math.gammamain() { let n: Float32 = -1.1 let gamma = gamma(n) println(gamma)} +} + +public func gamma(x: Float64): Float64 { + import std.math.gammamain() { let n: Float64 = -1.1 let gamma = gamma(n) println(gamma)} +} + +public func gcd(x: Int16, y: Int16): Int16 { + import std.math.gcdmain() { let x: Int16 = 15 let y: Int16 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: Int32, y: Int32): Int32 { + import std.math.gcdmain() { let x: Int32 = 15 let y: Int32 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: Int64, y: Int64): Int64 { + import std.math.gcdmain() { let x: Int64 = 15 let y: Int64 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: Int8, y: Int8): Int8 { + import std.math.gcdmain() { let x: Int8 = 15 let y: Int8= 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: UInt16, y: UInt16): UInt16 { + import std.math.gcdmain() { let x: UInt16 = 15 let y: UInt16 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: UInt32, y: UInt32): UInt32 { + import std.math.gcdmain() { let x: UInt32 = 15 let y: UInt32 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: UInt64, y: UInt64): UInt64 { + import std.math.gcdmain() { let x: UInt64 = 15 let y: UInt64 = 9 let gcd = gcd(x, y) println(gcd)} +} + +public func gcd(x: UInt8, y: UInt8): UInt8 { + import std.math.gcdmain() { let x: UInt8 = 15 let y: UInt8= 9 let gcd = gcd(x, y) println(gcd)} +} + +public func lcm(x: Int16, y: Int16): Int16 { + import std.math.lcmmain() { let x: Int16 = -15 let y: Int16 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: Int32, y: Int32): Int32 { + import std.math.lcmmain() { let x: Int32 = -15 let y: Int32 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: Int64, y: Int64): Int64 { + import std.math.lcmmain() { let x: Int64 = 15 let y: Int64 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: Int8, y: Int8): Int8 { + import std.math.lcmmain() { let x: Int8 = 15 let y: Int8= 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: UInt16, y: UInt16): UInt16 { + import std.math.lcmmain() { let x: UInt16 = 15 let y: UInt16 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: UInt32, y: UInt32): UInt32 { + import std.math.lcmmain() { let x: UInt32 = 15 let y: UInt32 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: UInt64, y: UInt64): UInt64 { + import std.math.lcmmain() { let x: UInt64 = 15 let y: UInt64 = 9 let lcm = lcm(x, y) println(lcm)} +} + +public func lcm(x: UInt8, y: UInt8): UInt8 { + import std.math.lcmmain() { let x: UInt8 = 15 let y: UInt8= 9 let lcm = lcm(x, y) println(lcm)} +} + +public func leadingZeros(x: Int16): Int8 { + import std.math.leadingZerosmain() { let x: Int16 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: Int32): Int8 { + import std.math.leadingZerosmain() { let x: Int32 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: Int64): Int8 { + import std.math.leadingZerosmain() { let x: Int64 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: Int8): Int8 { + import std.math.leadingZerosmain() { let x: Int8 = 4 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: UInt16): Int8 { + import std.math.leadingZerosmain() { let x: UInt16 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: UInt32): Int8 { + import std.math.leadingZerosmain() { let x: UInt32 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: UInt64): Int8 { + import std.math.leadingZerosmain() { let x: UInt64 = 512 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func leadingZeros(x: UInt8): Int8 { + import std.math.leadingZerosmain() { let x: UInt8 = 64 let leadingZeros = leadingZeros(x) println(leadingZeros)} +} + +public func log(x: Float16): Float16 { + import std.math.logmain() { let x: Float16 = 2.718282 let log = log(x) println(log)} +} + +public func log(x: Float32): Float32 { + import std.math.logmain() { let x: Float32 = 2.718282 let log = log(x) println(log)} +} + +public func log(x: Float64): Float64 { + import std.math.logmain() { let x: Float64 = 2.718282 let log = log(x) println(log)} +} + +public func log10(x: Float16): Float16 { + import std.math.log10main() { let x: Float16 = 1000.0 let log10 = log10(x) println(log10)} +} + +public func log10(x: Float32): Float32 { + import std.math.log10main() { let x: Float32 = 1000.0 let log10 = log10(x) println(log10)} +} + +public func log10(x: Float64): Float64 { + import std.math.log10main() { let x: Float64 = 1000.0 let log10 = log10(x) println(log10)} +} + +public func log2(x: Float16): Float16 { + import std.math.log2main() { let x: Float16 = 1024.0 let log2 = log2(x) println(log2)} +} + +public func log2(x: Float32): Float32 { + import std.math.log2main() { let x: Float32 = 1024.0 let log2 = log2(x) println(log2)} +} + +public func log2(x: Float64): Float64 { + import std.math.log2main() { let x: Float64 = 1024.0 let log2 = log2(x) println(log2)} +} + +public func logBase(x: Float16, base: Float16): Float16 { + import std.math.logBasemain() { let x: Float16 = 512.0 let base: Float16 = 2.0 let logBase = logBase(x, base) println(logBase)} +} + +public func logBase(x: Float32, base: Float32): Float32 { + import std.math.logBasemain() { let x: Float32 = 1024.0 let base: Float32 = 2.0 let logBase = logBase(x, base) println(logBase)} +} + +public func logBase(x: Float64, base: Float64): Float64 { + import std.math.logBasemain() { let x: Float64 = 1024.0 let base: Float64 = 2.0 let logBase = logBase(x, base) println(logBase)} +} + +public func max(a: Float16, b: Float16): Float16 { + import std.math.maxmain() { let a: Float16 = 1.0 let b: Float16 = 2.0 let max = max(a, b) println(max)} +} + +public func max(a: Float32, b: Float32): Float32 { + import std.math.maxmain() { let a: Float32 = 1.0 let b: Float32 = 2.0 let max = max(a, b) println(max)} +} + +public func max(a: Float64, b: Float64): Float64 { + import std.math.maxmain() { let a: Float64 = 1.0 let b: Float64 = 2.0 let max = max(a, b) println(max)} +} + +public func max(a: Int16, b: Int16): Int16 { + import std.math.maxmain() { let a: Int16 = -1 let b: Int16 = 2 let max = max(a, b) println(max)} +} + +public func max(a: Int32, b: Int32): Int32 { + import std.math.maxmain() { let a: Int32 = -1 let b: Int32 = 2 let max = max(a, b) println(max)} +} + +public func max(a: Int64, b: Int64): Int64 { + import std.math.maxmain() { let a: Int64 = -1 let b: Int64 = 2 let max = max(a, b) println(max)} +} + +public func max(a: Int8, b: Int8): Int8 { + import std.math.maxmain() { let a: Int8 = -1 let b: Int8 = 2 let max = max(a, b) println(max)} +} + +public func max(a: UInt16, b: UInt16): UInt16 { + import std.math.maxmain() { let a: UInt16 = 1 let b: UInt16 = 2 let max = max(a, b) println(max)} +} + +public func max(a: UInt32, b: UInt32): UInt32 { + import std.math.maxmain() { let a: UInt32 = 1 let b: UInt32 = 2 let max = max(a, b) println(max)} +} + +public func max(a: UInt64, b: UInt64): UInt64 { + import std.math.maxmain() { let a: UInt64 = 1 let b: UInt64 = 2 let max = max(a, b) println(max)} +} + +public func max(a: UInt8, b: UInt8): UInt8 { + import std.math.maxmain() { let a: UInt8 = 1 let b: UInt8 = 2 let max = max(a, b) println(max)} +} + +public func maxNaN(a: Float16, b: Float16): Float16 { + import std.math.maxNaNmain() { let a: Float16 = 1.0 let b: Float16 = 2.0 let maxNaN = maxNaN(a, b) println(maxNaN)} +} + +public func maxNaN(a: Float32, b: Float32): Float32 { + import std.math.maxNaNmain() { let a: Float32 = 1.0 let b: Float32 = 2.0 let maxNaN = maxNaN(a, b) println(maxNaN)} +} + +public func maxNaN(a: Float64, b: Float64): Float64 { + import std.math.maxNaNmain() { let a: Float64 = 1.0 let b: Float64 = 2.0 let maxNaN = maxNaN(a, b) println(maxNaN)} +} + +public func min(a: Float16, b: Float16): Float16 { + import std.math.minmain() { let a: Float16 = 1.0 let b: Float16 = 2.0 let min = min(a, b) println(min)} +} + +public func min(a: Float32, b: Float32): Float32 { + import std.math.minmain() { let a: Float32 = 1.0 let b: Float32 = 2.0 let min = min(a, b) println(min)} +} + +public func min(a: Float64, b: Float64): Float64 { + import std.math.minmain() { let a: Float64 = 1.0 let b: Float64 = 2.0 let min = min(a, b) println(min)} +} + +public func min(a: Int16, b: Int16): Int16 { + import std.math.minmain() { let a: Int16 = -1 let b: Int16 = 2 let min = min(a, b) println(min)} +} + +public func min(a: Int32, b: Int32): Int32 { + import std.math.minmain() { let a: Int32 = -1 let b: Int32 = 2 let min = min(a, b) println(min)} +} + +public func min(a: Int64, b: Int64): Int64 { + import std.math.minmain() { let a: Int64 = -1 let b: Int64 = 2 let min = min(a, b) println(min)} +} + +public func min(a: Int8, b: Int8): Int8 { + import std.math.minmain() { let a: Int8 = -1 let b: Int8 = 2 let min = min(a, b) println(min)} +} + +public func min(a: UInt16, b: UInt16): UInt16 { + import std.math.minmain() { let a: UInt16 = 1 let b: UInt16 = 2 let min = min(a, b) println(min)} +} + +public func min(a: UInt32, b: UInt32): UInt32 { + import std.math.minmain() { let a: UInt32 = 1 let b: UInt32 = 2 let min = min(a, b) println(min)} +} + +public func min(a: UInt64, b: UInt64): UInt64 { + import std.math.minmain() { let a: UInt64 = 1 let b: UInt64 = 2 let min = min(a, b) println(min)} +} + +public func min(a: UInt8, b: UInt8): UInt8 { + import std.math.minmain() { let a: UInt8 = 1 let b: UInt8 = 2 let min = min(a, b) println(min)} +} + +public func minNaN(a: Float16, b: Float16): Float16 { + import std.math.minNaNmain() { let a: Float16 = 1.0 let b: Float16 = 2.0 let minNaN = minNaN(a, b) println(minNaN)} +} + +public func minNaN(a: Float32, b: Float32): Float32 { + import std.math.minNaNmain() { let a: Float32 = 1.0 let b: Float32 = 2.0 let minNaN = minNaN(a, b) println(minNaN)} +} + +public func minNaN(a: Float64, b: Float64): Float64 { + import std.math.minNaNmain() { let a: Float64 = 1.0 let b: Float64 = 2.0 let minNaN = minNaN(a, b) println(minNaN)} +} + +public func pow(base: Float32, exponent: Float32): Float32 { + import std.math.powmain() { let base: Float32 = -1.0 let exponent: Float32 = 0.5 let pow = pow(base, exponent) println(pow)} +} + +public func pow(base: Float32, exponent: Int32): Float32 { + import std.math.powmain() { let base: Float32 = -1.0 let exponent: Int32 = 2 let pow = pow(base, exponent) println(pow)} +} + +public func pow(base: Float64, exponent: Float64): Float64 { + import std.math.powmain() { let base: Float64 = -1.0 let exponent: Float64 = 0.5 let pow = pow(base, exponent) println(pow)} +} + +public func pow(base: Float64, exponent: Int64): Float64 { + import std.math.powmain() { let base: Float64 = -1.0 let exponent: Int64 = 2 let pow = pow(base, exponent) println(pow)} +} + +public func reverse(x: UInt16): UInt16 { + import std.math.reversemain() { let n: UInt16 = 0x8000 let reverse = reverse(n) println(reverse)} +} + +public func reverse(x: UInt32): UInt32 { + import std.math.reversemain() { let n: UInt32 = 0x8000_0000 let reverse = reverse(n) println(reverse)} +} + +public func reverse(x: UInt64): UInt64 { + import std.math.reversemain() { let n: UInt64 = 0x8000_0000_0000_0000 let reverse = reverse(n) println(reverse)} +} + +public func reverse(x: UInt8): UInt8 { + import std.math.reversemain() { let n: UInt8 = 0x80 let reverse = reverse(n) println(reverse)} +} + +public func rotate(num: Int16, d: Int8): Int16 { + import std.math.rotatemain() { let n: Int16 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: Int32, d: Int8): Int32 { + import std.math.rotatemain() { let n: Int32 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: Int64, d: Int8): Int64 { + import std.math.rotatemain() { let n: Int64 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: Int8, d: Int8): Int8 { + import std.math.rotatemain() { let n: Int8 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: UInt16, d: Int8): UInt16 { + import std.math.rotatemain() { let n: UInt16 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: UInt32, d: Int8): UInt32 { + import std.math.rotatemain() { let n: UInt32 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: UInt64, d: Int8): UInt64 { + import std.math.rotatemain() { let n: UInt64 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func rotate(num: UInt8, d: Int8): UInt8 { + import std.math.rotatemain() { let n: UInt8 = 1 let rotate = rotate(n, 2) println(rotate)} +} + +public func round(x: Float16): Float16 { + import std.math.roundmain() { let n: Float16 = 1.5 let round = round(n) println(round)} +} + +public func round(x: Float32): Float32 { + import std.math.roundmain() { let n: Float32 = 1.5 let round = round(n) println(round)} +} + +public func round(x: Float64): Float64 { + import std.math.roundmain() { let n: Float64 = 1.5 let round = round(n) println(round)} +} + +public func sin(x: Float16): Float16 { + import std.math.sinmain() { let n: Float16 = 3.1415926/2.0 let sin = sin(n) println(sin)} +} + +public func sin(x: Float32): Float32 { + import std.math.sinmain() { let n: Float32 = 3.1415926/2.0 let sin = sin(n) println(sin)} +} + +public func sin(x: Float64): Float64 { + import std.math.sinmain() { let n: Float64 = 3.1415926/2.0 let sin = sin(n) println(sin)} +} + +public func sinh(x: Float16): Float16 { + import std.math.sinhmain() { let n: Float16 = 0.0 let sinh = sinh(n) println(sinh)} +} + +public func sinh(x: Float32): Float32 { + import std.math.sinhmain() { let n: Float32 = 0.0 let sinh = sinh(n) println(sinh)} +} + +public func sinh(x: Float64): Float64 { + import std.math.sinhmain() { let n: Float64 = 0.0 let sinh = sinh(n) println(sinh)} +} + +public func sqrt(x: Float16): Float16 { + import std.math.sqrtmain() { let n: Float16 = 16.0 let sqrt = sqrt(n) println(sqrt)} +} + +public func sqrt(x: Float32): Float32 { + import std.math.sqrtmain() { let n: Float32 = 16.0 let sqrt = sqrt(n) println(sqrt)} +} + +public func sqrt(x: Float64): Float64 { + import std.math.sqrtmain() { let n: Float64 = 16.0 let sqrt = sqrt(n) println(sqrt)} +} + +public func tan(x: Float16): Float16 { + import std.math.tanmain() { let n: Float16 = 0.0 let tan = tan(n) println(tan)} +} + +public func tan(x: Float32): Float32 { + import std.math.tanmain() { let n: Float32 = 0.0 let tan = tan(n) println(tan)} +} + +public func tan(x: Float64): Float64 { + import std.math.tanmain() { let n: Float64 = 0.0 let tan = tan(n) println(tan)} +} + +public func tanh(x: Float16): Float16 { + import std.math.tanhmain() { let n: Float16 = 0.0 let tanh = tanh(n) println(tanh)} +} + +public func tanh(x: Float32): Float32 { + import std.math.tanhmain() { let n: Float32 = 0.0 let tanh = tanh(n) println(tanh)} +} + +public func tanh(x: Float64): Float64 { + import std.math.tanhmain() { let n: Float64 = 0.0 let tanh = tanh(n) println(tanh)} +} + +public func throwIllegalArgumentException(): Int64 +public func trailingZeros(x: Int16): Int8 { + import std.math.trailingZerosmain() { let x: Int16 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: Int32): Int8 { + import std.math.trailingZerosmain() { let x: Int32 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: Int64): Int8 { + import std.math.trailingZerosmain() { let x: Int64 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: Int8): Int8 { + import std.math.trailingZerosmain() { let x: Int8 = 64 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: UInt16): Int8 { + import std.math.trailingZerosmain() { let x: UInt16 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: UInt32): Int8 { + import std.math.trailingZerosmain() { let x: UInt32 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: UInt64): Int8 { + import std.math.trailingZerosmain() { let x: UInt64 = 512 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trailingZeros(x: UInt8): Int8 { + import std.math.trailingZerosmain() { let x: UInt8 = 64 let trailingZeros = trailingZeros(x) println(trailingZeros)} +} + +public func trunc(x: Float16): Float16 { + import std.math.truncmain() { let x: Float16 = 64.555566 let trunc = trunc(x) println(trunc)} +} + +public func trunc(x: Float32): Float32 { + import std.math.truncmain() { let x: Float32 = 64.555566 let trunc = trunc(x) println(trunc)} +} + +public func trunc(x: Float64): Float64 { + import std.math.truncmain() { let x: Float64 = 64.555566 let trunc = trunc(x) println(trunc)} +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface MathExtension {} + +extend Float16 <: MathExtension { + public static prop E: Float16 + public static prop Inf: Float16 + public static prop Max: Float16 + public static prop Min: Float16 + public static prop MinDenormal: Float16 + public static prop MinNormal: Float16 + public static prop NaN: Float16 + public static prop PI: Float16 + public func isInf(): Bool + public func isNaN(): Bool + public func isNormal(): Bool +} + +extend Float32 <: MathExtension { + public static prop E: Float32 + public static prop Inf: Float32 + public static prop Max: Float32 + public static prop Min: Float32 + public static prop MinDenormal: Float32 + public static prop MinNormal: Float32 + public static prop NaN: Float32 + public static prop PI: Float32 + public func isInf(): Bool + public func isNaN(): Bool + public func isNormal(): Bool +} + +extend Float64 <: MathExtension { + public static prop E: Float64 + public static prop Inf: Float64 + public static prop Max: Float64 + public static prop Min: Float64 + public static prop MinDenormal: Float64 + public static prop MinNormal: Float64 + public static prop NaN: Float64 + public static prop PI: Float64 + public func isInf(): Bool + public func isNaN(): Bool + public func isNormal(): Bool +} + +extend Int16 <: MathExtension { + public static prop Max: Int16 + public static prop Min: Int16 +} + +extend Int32 <: MathExtension { + public static prop Max: Int32 + public static prop Min: Int32 +} + +extend Int64 <: MathExtension { + public static prop Max: Int64 + public static prop Min: Int64 +} + +extend Int8 <: MathExtension { + public static prop Max: Int8 + public static prop Min: Int8 +} + +extend IntNative <: MathExtension { + public static prop Max: IntNative + public static prop Min: IntNative +} + +extend UInt16 <: MathExtension { + public static prop Max: UInt16 + public static prop Min: UInt16 +} + +extend UInt32 <: MathExtension { + public static prop Max: UInt32 + public static prop Min: UInt32 +} + +extend UInt64 <: MathExtension { + public static prop Max: UInt64 + public static prop Min: UInt64 +} + +extend UInt8 <: MathExtension { + public static prop Max: UInt8 + public static prop Min: UInt8 +} + +extend UIntNative <: MathExtension { + public static prop Max: UIntNative + public static prop Min: UIntNative +} + + diff --git a/cangjie_libs/std/math.numeric.cjd b/cangjie_libs/std/math.numeric.cjd new file mode 100644 index 0000000000000000000000000000000000000000..cf8bbb53e23b7fd41419a91c7b51df22dee9d7b5 --- /dev/null +++ b/cangjie_libs/std/math.numeric.cjd @@ -0,0 +1,278 @@ +package std.math.numeric + +// --------------------------- +// -----enums +// --------------------------- +public enum OverflowStrategy { + saturating + throwing + wrapping +} + +public enum RoundingMode { + CEILING + DOWN + FLOOR + HALF_EVEN + HALF_UP + UP +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func abs(i: BigInt): BigInt { + import std.math.numeric.*main() { let n: BigInt = BigInt(-23) let abs = abs(n) println(abs)} +} + +public func countOne(i: BigInt): Int64 { + import std.math.numeric.*main() { let i: BigInt = BigInt(255) let countOne = countOne(i) println(countOne)} +} + +public func gcd(i1: BigInt, i2: BigInt): BigInt { + import std.math.numeric.*main() { let i1: BigInt = BigInt(-36) let i2: BigInt = BigInt(48) let gcd = gcd(i1, i2) println(gcd)} +} + +public func lcm(i1: BigInt, i2: BigInt): BigInt { + import std.math.numeric.*main() { let i1: BigInt = BigInt(-36) let i2: BigInt = BigInt(48) let lcm = lcm(i1, i2) println(lcm)} +} + +public func max(i1: BigInt, i2: BigInt): BigInt { + import std.math.numeric.*main() { let i1: BigInt = BigInt(-36) let i2: BigInt = BigInt(48) let max = max(i1, i2) println(max)} +} + +public func min(i1: BigInt, i2: BigInt): BigInt { + import std.math.numeric.*main() { let i1: BigInt = BigInt(-36) let i2: BigInt = BigInt(48) let min = min(i1, i2) println(min)} +} + +public func sqrt(i: BigInt): BigInt { + import std.math.numeric.*main() { let n: BigInt = BigInt(23) let sqrt = sqrt(n) println(sqrt)} +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct BigInt <: Comparable & Hashable & ToString { + public prop bitLen: Int64 + public prop sign: Int64 + public init(bytes: Array) + public init(sign: Bool, magnitude: Array) + public init(sign: Bool, bitLen: Int64, rand!: Random = Random()) + public init(n: Int16) + public init(n: Int32) + public init(n: Int64) + public init(n: Int8) + public init(n: IntNative) + public init(s: String, base!: Int64 = 10) + public init(n: UInt16) + public init(n: UInt32) + public init(n: UInt64) + public init(n: UInt8) + public init(n: UIntNative) + public static func randomProbablePrime(bitLen: Int64, certainty: UInt64, rand!: Random = Random()): BigInt + import std.math.numeric.BigIntmain() { let randomProbablePrime = BigInt.randomProbablePrime(6, 3) println(randomProbablePrime)} + public func clearBit(index: Int64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1024) let clearBit = bigInt.clearBit(10) println(clearBit)} + public func compare(that: BigInt): Ordering + public func divAndMod(that: BigInt): (BigInt, BigInt) + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1025) let that = BigInt(512) let (div, mod) = bigInt.divAndMod(that) println(div) println(mod)} + public func flipBit(index: Int64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1024) let flipBit = bigInt.flipBit(10) println(flipBit)} + public func hashCode(): Int64 + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1024) let hashCode = bigInt.hashCode() println(hashCode)} + public func isProbablePrime(certainty: UInt64): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1024) let isProbablePrime = bigInt.isProbablePrime(10) println(isProbablePrime)} + public func lowestOneBit(): Int64 + import std.math.numeric.BigIntmain() { let bigInt = BigInt(-1) let lowestOneBit = bigInt.lowestOneBit() println(lowestOneBit)} + public func modInverse(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1025) let that = BigInt(512) let modInverse = bigInt.modInverse(that) println(modInverse)} + public func modPow(n: BigInt, m!: ?BigInt = None): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(2) let n = BigInt(10) let modPow = bigInt.modPow(n) println(modPow)} + public func quo(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1025) let that = BigInt(512) let quo = bigInt.quo(that) println(quo)} + public func quoAndRem(that: BigInt): (BigInt, BigInt) + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1025) let that = BigInt(512) let (quo, rem) = bigInt.quoAndRem(that) println(quo) println(rem)} + public func rem(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(1025) let that = BigInt(512) let rem = bigInt.rem(that) println(rem)} + public func setBit(index: Int64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt(0) let setBit = bigInt.setBit(10) println(setBit)} + public func testBit(index: Int64): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt(-1) let testBit = bigInt.testBit(100) println(testBit)} + public func toBytes(): Array + import std.math.numeric.BigIntmain() { let bigInt = BigInt(0x400) let toBytes = bigInt.toBytes() println(toBytes)} + public func toInt16(overflowHandling!: OverflowStrategy = throwing): Int16 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt(0x8000_0000_0000) let toInt16 = bigInt.toInt16(overflowHandling: saturating) println(toInt16)} + public func toInt32(overflowHandling!: OverflowStrategy = throwing): Int32 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt(0x8000_0000_00FF) let toInt32 = bigInt.toInt32(overflowHandling: wrapping) println(toInt32)} + public func toInt64(overflowHandling!: OverflowStrategy = throwing): Int64 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("800000000000000000", base: 16) let toInt64 = bigInt.toInt64(overflowHandling: wrapping) println(toInt64)} + public func toInt8(overflowHandling!: OverflowStrategy = throwing): Int8 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt(1024) let toInt8 = bigInt.toInt8(overflowHandling: saturating) println(toInt8)} + public func toIntNative(overflowHandling!: OverflowStrategy = throwing): IntNative + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("800000000000000000", base: 16) let toIntNative = bigInt.toIntNative(overflowHandling: wrapping) println(toIntNative)} + public func toString(): String + import std.math.numeric.BigIntmain() { let bigInt = BigInt(0x400) let toString = bigInt.toString() println(toString)} + public func toString(base: Int64): String + import std.math.numeric.BigIntmain() { let bigInt = BigInt(0x400) let toString = bigInt.toString(2) println(toString)} + public func toUInt16(overflowHandling!: OverflowStrategy = throwing): UInt16 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("800000000000000000", base: 16) let toUInt16 = bigInt.toUInt16(overflowHandling: wrapping) println(toUInt16)} + public func toUInt32(overflowHandling!: OverflowStrategy = throwing): UInt32 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("800000000000000000", base: 16) let toUInt32 = bigInt.toUInt32(overflowHandling: wrapping) println(toUInt32)} + public func toUInt64(overflowHandling!: OverflowStrategy = throwing): UInt64 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("-800000000000000000", base: 16) let toUInt64 = bigInt.toUInt64(overflowHandling: saturating) println(toUInt64)} + public func toUInt8(overflowHandling!: OverflowStrategy = throwing): UInt8 + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("800000000000000000", base: 16) try { bigInt.toUInt8(overflowHandling: throwing) } catch (e: OverflowException) { println(e.message) } return} + public func toUIntNative(overflowHandling!: OverflowStrategy = throwing): UIntNative + import std.math.numeric.BigIntimport std.math.numeric.OverflowStrategymain() { let bigInt = BigInt("-800000000000000000", base: 16) let toUIntNative = bigInt.toUIntNative(overflowHandling: saturating) println(toUIntNative)} + public operator func !(): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let no = !bigInt println(no)} + public operator func !=(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt != that)} + public operator func %(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-23456789123456789") let that = BigInt("-23456789123456789") let mod = bigInt % that println(mod)} + public operator func &(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("8") let that = BigInt("7") let and = bigInt & that println(and)} + public operator func *(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-23456789123456789") let mul = bigInt * that println(mul)} + public operator func **(n: UInt64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-2") let power = bigInt ** 64 println(power.toString(16))} + public operator func +(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("123456789123456789") let that = BigInt("-23456789123456789") let plus = bigInt + that println(plus)} + public operator func -(): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-23456789123456789") let opposite = -bigInt println(opposite)} + public operator func -(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("100000000000000000") let that = BigInt("-23456789123456789") let sub = bigInt - that println(sub)} + public operator func <(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt < that)} + public operator func <<(n: Int64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let leftShift = bigInt << 64 println(leftShift.toString(16))} + public operator func <=(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt <= that)} + public operator func ==(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt == that)} + public operator func >(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt > that)} + public operator func >=(that: BigInt): Bool + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("-2") println(bigInt >= that)} + public operator func >>(n: Int64): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let rightShift = bigInt >> 10000 println(rightShift)} + public operator func /(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-23456789123456789") let that = BigInt("-23456789123456789") let div = bigInt / that println(div)} + public operator func ^(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("-1") let that = BigInt("7") let xor = bigInt ^ that println(xor)} + public operator func |(that: BigInt): BigInt + import std.math.numeric.BigIntmain() { let bigInt = BigInt("8") let that = BigInt("7") let or = bigInt | that println(or)} +} + +public struct Decimal <: Comparable & Hashable & ToString { + public static let defaultDecimalContext: DecimalContext + public prop precision: Int64 + public prop scale: Int32 + public prop sign: Int64 + public prop value: BigInt + public init(val: BigInt, scale: Int32, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Float16, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Float32, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Float64, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Int16, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Int32, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Int64, ctx!: DecimalContext = defaultDecimalContext) + public init(val: Int8, ctx!: DecimalContext = defaultDecimalContext) + public init(val: IntNative, ctx!: DecimalContext = defaultDecimalContext) + public init(val: String, ctx!: DecimalContext = defaultDecimalContext) + public init(val: UInt16, ctx!: DecimalContext = defaultDecimalContext) + public init(val: UInt32, ctx!: DecimalContext = defaultDecimalContext) + public init(val: UInt64, ctx!: DecimalContext = defaultDecimalContext) + public init(val: UInt8, ctx!: DecimalContext = defaultDecimalContext) + public init(val: UIntNative, ctx!: DecimalContext = defaultDecimalContext) + public func abs(): Decimal + public func add(d: Decimal): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A.add(B) println("C = ${C}")} + public func add(d: Decimal, ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A.add(B, Decimal.defaultDecimalContext) println("C = ${C}")} + public func compare(d: Decimal): Ordering + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(-5) let B = Decimal(3) let C = A.compare(B) println(C)} + public func div(d: Decimal): Decimal + public func div(d: Decimal, ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A.div(B, Decimal.defaultDecimalContext) println("C = ${C}")} + public func divAndRem(d: Decimal): (BigInt, Decimal) + public func divAndRem(d: Decimal, ctx: DecimalContext): (BigInt, Decimal) + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(5) let B = Decimal(3) let (C, D)= A.divAndRem(B, Decimal.defaultDecimalContext) println("C = ${C}, D = ${D}")} + public func hashCode(): Int64 + public func isInteger(): Bool + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(100) println("${A}.isInteger() = ${A.isInteger()}")} + public func mul(d: Decimal): Decimal + public func mul(d: Decimal, ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A.mul(B, Decimal.defaultDecimalContext) println("C = ${C}")} + public func neg(): Decimal + public func neg(ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(-5) let B = Decimal(3) let C = A.neg() let D = B.neg(Decimal.defaultDecimalContext) println("C = ${C}, D = ${D}")} + public func pow(n: Int64): Decimal + public func pow(n: Int64, ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2.5) println("A.pow(3, DecimalContext) = ${A.pow(3, Decimal.defaultDecimalContext)}")} + public func reScale(newScale: Int32, rm!: RoundingMode = HALF_EVEN): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(1.234568) println("A.reScale(3) = ${A.reScale(3)}")} + public func removeTrailingZeros(): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(1.00) println("A.removeTrailingZeros() = ${A.removeTrailingZeros()}")} + public func round(ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(1.0) println("A.round(1.0) = ${A.round(Decimal.defaultDecimalContext)}")} + public func scaleUnit(): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(100) println("A.scaleUnit() = ${A.scaleUnit()}")} + public func shiftPoint(n: Int32): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(25) println("A.shiftPoint(1) = ${A.shiftPoint(1)}")} + public func sqrt(ctx!: DecimalContext = defaultDecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(0.25) println("A.abs() = ${A.abs()}") println("A.sqrt() = ${A.sqrt()}")} + public func sub(d: Decimal): Decimal + public func sub(d: Decimal, ctx: DecimalContext): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A.sub(B, Decimal.defaultDecimalContext) println("C = ${C}")} + public func toBigInt(): BigInt + public func toEngString(): String + public func toSciString(): String + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(6.25) println("A.toFloat16() = ${A.toFloat16()}") println("A.toFloat32() = ${A.toFloat32()}") println("A.toFloat64() = ${A.toFloat64()}") println("A.toBigInt() = ${A.toBigInt()}") println("A.toEngString() = ${A.toEngString()}") println("A.toSciString() = ${A.toSciString()}")} + public func toFloat16(): Float16 + public func toFloat32(): Float32 + public func toFloat64(): Float64 + public func toInt16(overflowHandling!: OverflowStrategy = throwing): Int16 + public func toInt32(overflowHandling!: OverflowStrategy = throwing): Int32 + public func toInt64(overflowHandling!: OverflowStrategy = throwing): Int64 + public func toInt8(overflowHandling!: OverflowStrategy = throwing): Int8 + public func toIntNative(overflowHandling!: OverflowStrategy = throwing): IntNative + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(6.25) println("A.toInt8() = ${A.toInt8()}") println("A.toInt16() = ${A.toInt16()}") println("A.toInt32() = ${A.toInt32()}") println("A.toInt64() = ${A.toInt64()}") println("A.toIntNative() = ${A.toIntNative()}")} + public func toString(): String + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(-5) let B = Decimal(3 ** 5) println("A.hashCode() = ${A.hashCode()}") println("B.toString() = ${B.toString()}")} + public func toUInt16(overflowHandling!: OverflowStrategy = throwing): UInt16 + public func toUInt32(overflowHandling!: OverflowStrategy = throwing): UInt32 + public func toUInt64(overflowHandling!: OverflowStrategy = throwing): UInt64 + public func toUInt8(overflowHandling!: OverflowStrategy = throwing): UInt8 + public func toUIntNative(overflowHandling!: OverflowStrategy = throwing): UIntNative + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(6.25) println("A.toUInt8() = ${A.toUInt8()}") println("A.toUInt16() = ${A.toUInt16()}") println("A.toUInt32() = ${A.toUInt32()}") println("A.toUInt64() = ${A.toUInt64()}") println("A.toUIntNative() = ${A.toUIntNative()}")} + public operator func !=(d: Decimal): Bool + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(-5) let B = Decimal(3) println(" -A = ${-A}") println(" A <= B = ${ A <= B}") println(" A != B = ${ A != B}")} + -A = 5A <= B = trueA != B = true + public operator func *(d: Decimal): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A * B println("C = ${C}")} + public operator func **(n: Int64): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2.5) println("A ** 3 = ${A ** 3}")} + public operator func +(d: Decimal): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A + B println("C = ${C}")} + public operator func -(): Decimal + public operator func -(d: Decimal): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A - B println("C = ${C}")} + public operator func <(d: Decimal): Bool + public operator func <=(d: Decimal): Bool + public operator func ==(d: Decimal): Bool + public operator func >(d: Decimal): Bool + public operator func >=(d: Decimal): Bool + public operator func /(d: Decimal): Decimal + import std.math.numeric.Decimalmain(): Unit { let A = Decimal(2) let B = Decimal(3) let C = A / B println("C = ${C}")} +} + +public struct DecimalContext { + public let precision: Int64 + public let roundingMode: RoundingMode + public init(precision: Int64, roundingMode: RoundingMode) +} + + diff --git a/cangjie_libs/std/net.cjd b/cangjie_libs/std/net.cjd new file mode 100644 index 0000000000000000000000000000000000000000..cfcf1cff9b0afd89010e3e5f888e20ea33d51796 --- /dev/null +++ b/cangjie_libs/std/net.cjd @@ -0,0 +1,532 @@ +package std.net + +// --------------------------- +// -----classes +// --------------------------- +abstract sealed class IPAddress <: ToString & Equatable & Hashable & BigEndianOrder { + public prop hostName: Option + public prop size: Int64 + public static func parse(s: String): IPAddress + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: IPAddress = IPAddress.parse("192.168.1.2") let v6: IPAddress = IPAddress.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10") @Assert(v4.toString(), "192.168.1.2") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10")} + public static func readBigEndian(buffer: Array): IPAddress + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let bufferV4: Array = [0xC0, 0xA8, 0x1, 0x2] let bufferV6: Array = [0x20, 0x01, 0x02, 0x50, 0x10, 0x06, 0xdf, 0xf0, 0x49, 0x13, 0x2a, 0xa5, 0x80, 0x75, 0x7c, 0x10] let v4: IPAddress = IPAddress.readBigEndian(bufferV4) let v6: IPAddress = IPAddress.readBigEndian(bufferV6) @Assert(v4.toString(), "192.168.1.2") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10")} + public static func resolve(domain: String): Array + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let iplist: Array = IPAddress.resolve("localhost") println(iplist)}// may output: [127.0.0.1, ::1] + public static func tryParse(s: String): Option + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: ?IPAddress = IPAddress.tryParse("192.168.1.2") let v6: ?IPAddress = IPAddress.tryParse("2001:0250:1006:dff0:4913:2aa5:8075:7c10") @Assert(v4.toString(), "Some(192.168.1.2)") @Assert(v6.toString(), "Some(2001:250:1006:dff0:4913:2aa5:8075:7c10)")} + public func getAddressBytes(): Array + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let expectV4: Array = [0xC0, 0xA8, 0x1, 0x2] let expectV6: Array = [0x20, 0x01, 0x02, 0x50, 0x10, 0x06, 0xdf, 0xf0, 0x49, 0x13, 0x2a, 0xa5, 0x80, 0x75, 0x7c, 0x10] let v4: IPAddress = IPAddress.parse("192.168.1.2") let v6: IPAddress = IPAddress.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10") @Assert(v4.getAddressBytes(), expectV4) @Assert(v6.getAddressBytes(), expectV6)} + public func getPrefix(prefixLen: UInt8): IPPrefix + public func hashCode(): Int64 + public func isGlobalUnicast(): Bool + public func isIPv4(): Bool + public func isIPv6(): Bool + public func isLinkLocal(): Bool + public func isLoopback(): Bool + public func isMulticast(): Bool + public func isPrivate(): Bool + public func isUnspecified(): Bool + public open func writeBigEndian(buffer: Array): Int64 + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let buffer = Array(128, item: 0) let expectV4: Array = [0xC0, 0xA8, 0x1, 0x2] let expectV6: Array = [0x20, 0x01, 0x02, 0x50, 0x10, 0x06, 0xdf, 0xf0, 0x49, 0x13, 0x2a, 0xa5, 0x80, 0x75, 0x7c, 0x10] let v4: IPAddress = IPAddress.parse("192.168.1.2") let v6: IPAddress = IPAddress.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10") var len = v4.writeBigEndian(buffer) @Assert(buffer[..len], expectV4) len = v6.writeBigEndian(buffer) @Assert(buffer[..len], expectV6)} + public func toString(): String + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let bufferV4: Array = [0xC0, 0xA8, 0x1, 0x2] let bufferV6: Array = [0x20, 0x01, 0x02, 0x50, 0x10, 0x06, 0xdf, 0xf0, 0x49, 0x13, 0x2a, 0xa5, 0x80, 0x75, 0x7c, 0x10] let v4: IPAddress = IPAddress.readBigEndian(bufferV4) let v6: IPAddress = IPAddress.readBigEndian(bufferV6) @Assert(v4.toString(), "192.168.1.2") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10")} + public operator func ==(rhs: IPAddress): Bool + public operator func !=(rhs: IPAddress): Bool +} + +abstract sealed class IPPrefix <: Equatable & Hashable & ToString { + public prop address: IPAddress + public prop prefixLength: UInt8 + public static func parse(s: String): IPPrefix + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: IPPrefix = IPPrefix.parse("192.168.1.2/24") let v6: IPPrefix = IPPrefix.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10/32") @Assert(v4.toString(), "192.168.1.2/24") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10/32")} + public static func tryParse(s: String): Option + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: ?IPPrefix = IPPrefix.tryParse("192.168.1.2/24") let v6: ?IPPrefix = IPPrefix.tryParse("2001:0250:1006:dff0:4913:2aa5:8075:7c10/32") @Assert(v4.toString(), "Some(192.168.1.2/24)") @Assert(v6.toString(), "Some(2001:250:1006:dff0:4913:2aa5:8075:7c10/32)")} + public func contains(rhs: IPAddress): Bool + public func contains(rhs: IPPrefix): Bool + public func overlaps(rhs: IPPrefix): Bool + public func netmask(): IPAddress + public func hostmask(): IPAddress + public func broadcast(): IPAddress + public func network(): IPAddress + public func masked(): IPPrefix + public func toString(): String + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: IPPrefix = IPAddress.parse("192.168.1.2").getPrefix(24) let v6: IPPrefix = IPAddress.parse("2001:0250:1006:dff0:4913:2aa5:8075:7c10").getPrefix(32) @Assert(v4.toString(), "192.168.1.2/24") @Assert(v6.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10/32")} + public operator func ==(rhs: IPPrefix): Bool + public operator func !=(rhs: IPPrefix): Bool +} + +public class IPSocketAddress <: SocketAddress & Equatable { + public prop address: IPAddress + public prop family: AddressFamily + public prop port: UInt16 + public prop size: Int64 + public init(address: Array, port: UInt16) + public init(address: String, port: UInt16) + public init(address: IPAddress, port: UInt16) + public static func parse(s: String): IPSocketAddress + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: IPSocketAddress = IPSocketAddress.parse("192.168.1.2:8080") let v6: IPSocketAddress = IPSocketAddress.parse("[2001:0250:1006:dff0:4913:2aa5:8075:7c10]:8080") @Assert(v4.address.toString(), "192.168.1.2") @Assert(v4.port, 8080u16) @Assert(v6.address.toString(), "2001:250:1006:dff0:4913:2aa5:8075:7c10") @Assert(v6.port, 8080u16) @Assert(v4.toString(), "192.168.1.2:8080") @Assert(v6.toString(), "[2001:250:1006:dff0:4913:2aa5:8075:7c10]:8080")} + public static func tryParse(s: String): Option + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: ?IPAddress = IPAddress.tryParse("192.168.1.2") let v6: ?IPAddress = IPAddress.tryParse("2001:0250:1006:dff0:4913:2aa5:8075:7c10") @Assert(v4.toString(), "Some(192.168.1.2)") @Assert(v6.toString(), "Some(2001:250:1006:dff0:4913:2aa5:8075:7c10)")} + public func getAddressBytes(): Array + public func hashCode(): Int64 + public func isIPv4(): Bool + public func isIPv6(): Bool + public func toString(): String + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: IPSocketAddress = IPSocketAddress.parse("192.168.1.2:8080") let v6: IPSocketAddress = IPSocketAddress.parse("[2001:0250:1006:dff0:4913:2aa5:8075:7c10]:8080") @Assert(v4.toString(), "192.168.1.2:8080") @Assert(v6.toString(), "[2001:250:1006:dff0:4913:2aa5:8075:7c10]:8080")} + public operator func ==(rhs: IPSocketAddress): Bool + public operator func !=(rhs: IPSocketAddress): Bool +} + +public class IPv4Address <: IPAddress & ToString & Equatable & LessOrEqual { + public static let broadcast: IPv4Address + public static let localhost: IPv4Address + public static let unspecified: IPv4Address + public init(bits: UInt32) + public init(a: Byte, b: Byte, c: Byte, d: Byte) + public static func readBigEndian(buffer: Array): IPv4Address + public func getPrefix(prefixLen: UInt8): IPPrefix + public func hashCode(): Int64 + public func isBroadcast(): Bool + public func isGlobalUnicast(): Bool + public func isLinkLocal(): Bool + public func isLoopback(): Bool + public func isMulticast(): Bool + public func isPrivate(): Bool + public func isUnspecified(): Bool + public func toBits(): UInt32 + public func toIPv6Compatible(): IPv6Address + public func toIPv6Mapped(): IPv6Address + public func writeBigEndian(buffer: Array): Int64 + public func toString(): String + public operator func <=(rhs: IPv4Address): Bool + public operator func ==(rhs: IPv4Address): Bool + public operator func !=(rhs: IPv4Address): Bool +} + +public class IPv6Address <: IPAddress & ToString & Equatable & LessOrEqual { + public static let localhost: IPv6Address + public static let unspecified: IPv4Address + public prop scopeId: ?UInt32 + public init(octets: Array, scopeId!: ?UInt32 = None) + public init(a: UInt16, b: UInt16, c: UInt16, d: UInt16, e: UInt16, f: UInt16, g: UInt16, h: UInt16, scopeId!: ?UInt32 = None) + public static func readBigEndian(buffer: Array): IPv6Address + public func getPrefix(prefixLen: UInt8): IPPrefix + public func hashCode(): Int64 + public func isGlobalUnicast(): Bool + public func isIPv4Mapped(): Bool + public func isLinkLocal(): Bool + public func isLoopback(): Bool + public func isMulticast(): Bool + public func isPrivate(): Bool + public func isTeredo(): Bool + public func isUnspecified(): Bool + public func scope(scopeId: ?UInt32): IPv6Address + public func toIPv4(): ?IPv4Address + public func toIPv4Mapped(): ?IPv4Address + public func writeBigEndian(buffer: Array): Int64 + public func toString(): String + public operator func <=(rhs: IPv6Address): Bool + public operator func ==(rhs: IPv6Address): Bool + public operator func !=(rhs: IPv6Address): Bool +} + +public class RawSocket { + public prop localAddr: RawAddress + public mut prop readTimeout: ?Duration + public prop remoteAddr: RawAddress + public mut prop writeTimeout: ?Duration + public init(domain: SocketDomain, `type`: SocketType, protocol: ProtocolType) + public func accept(timeout!: ?Duration = None): RawSocket + public func bind(addr: RawAddress): Unit + public func close(): Unit + public func connect(addr: RawAddress, timeout!: ?Duration = None): Unit + public unsafe func getSocketOption(level: Int32, option: Int32, value: CPointer, len: CPointer): Unit + public func listen(backlog: Int32): Unit + public func receive(buffer: Array, flags: Int32): Int64 + public func receiveFrom(buffer: Array, flags: Int32): (RawAddress, Int64) + public func send(buffer: Array, flags: Int32): Unit + public func sendTo(addr: RawAddress, buffer: Array, flags: Int32): Unit + public unsafe func setSocketOption(level: Int32, option: Int32, value: CPointer, len: Int32): Unit +} + +abstract sealed class SocketAddress <: ToString & Equatable & Hashable { + public prop size: Int64 + public prop family: AddressFamily + public func getAddressBytes(): Array + public func hashCode(): Int64 + public func toString(): String + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let v4: SocketAddress = IPSocketAddress.parse("192.168.1.2:8080") let v6: SocketAddress = IPSocketAddress.parse("[2001:0250:1006:dff0:4913:2aa5:8075:7c10]:8080") @Assert(v4.toString(), "192.168.1.2:8080") @Assert(v6.toString(), "[2001:250:1006:dff0:4913:2aa5:8075:7c10]:8080")} + public operator func ==(rhs: SocketAddress): Bool + public operator func !=(rhs: SocketAddress): Bool +} + +public class TcpServerSocket <: ServerSocket { + public mut prop backlogSize: Int64 + public mut prop bindToDevice: ?String + public override prop localAddress: SocketAddress + public mut prop receiveBufferSize: Int64 + public mut prop reuseAddress: Bool + public mut prop reusePort: Bool + public mut prop sendBufferSize: Int64 + public init(bindAt!: SocketAddress) + public init(bindAt!: UInt16) + public override func accept(): TcpSocket + public override func accept(timeout!: ?Duration): TcpSocket + public override func bind(): Unit + public override func close(): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public override func isClosed(): Bool + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public override func toString(): String +} + +public class TcpSocket <: StreamingSocket & Equatable & Hashable { + public mut prop bindToDevice: ?String + public mut prop keepAlive: ?SocketKeepAliveConfig + public mut prop linger: ?Duration + public override prop localAddress: SocketAddress + public mut prop noDelay: Bool + public mut prop quickAcknowledge: Bool + public override mut prop readTimeout: ?Duration + public mut prop receiveBufferSize: Int64 + public override prop remoteAddress: SocketAddress + public mut prop sendBufferSize: Int64 + public override mut prop writeTimeout: ?Duration + public init(address: SocketAddress) + public init(address: SocketAddress, localAddress!: ?SocketAddress) + public init(address: String, port: UInt16) + public func close(): Unit + public func connect(timeout!: ?Duration = None): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public override func hashCode(): Int64 + public func isClosed(): Bool + public override func read(buffer: Array): Int64 + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public override func toString(): String + public override func write(payload: Array): Unit + public override operator func !=(other: TcpSocket): Bool + public override operator func ==(other: TcpSocket): Bool +} + +public class UdpSocket <: DatagramSocket { + public override prop localAddress: SocketAddress + public mut prop receiveBufferSize: Int64 + public override mut prop receiveTimeout: ?Duration + public override prop remoteAddress: ?SocketAddress + public mut prop reuseAddress: Bool + public mut prop reusePort: Bool + public mut prop sendBufferSize: Int64 + public override mut prop sendTimeout: ?Duration + public init(bindAt!: SocketAddress) + public init(bindAt!: UInt16) + public func bind(): Unit + public override func close(): Unit + public func connect(remote: SocketAddress): Unit + public func disconnect(): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public override func isClosed(): Bool + public func receive(buffer: Array): Int64 + public override func receiveFrom(buffer: Array): (SocketAddress, Int64) + public func send(payload: Array): Unit + public override func sendTo(recipient: SocketAddress, payload: Array): Unit + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public override func toString(): String +} + +public class UnixDatagramSocket <: DatagramSocket { + public override prop localAddress: SocketAddress + public mut prop receiveBufferSize: Int64 + public override mut prop receiveTimeout: ?Duration + public override prop remoteAddress: ?SocketAddress + public mut prop sendBufferSize: Int64 + public override mut prop sendTimeout: ?Duration + public init(bindAt!: SocketAddress) + public init(bindAt!: String) + public func bind(): Unit + public override func close(): Unit + public func connect(remote: SocketAddress): Unit + public func connect(remotePath: String): Unit + public func disconnect(): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public override func isClosed(): Bool + public func receive(buffer: Array): Int64 + public override func receiveFrom(buffer: Array): (SocketAddress, Int64) + public func send(payload: Array): Unit + public override func sendTo(recipient: SocketAddress, payload: Array): Unit + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public override func toString(): String +} + +public class UnixServerSocket <: ServerSocket { + public mut prop backlogSize: Int64 + public override prop localAddress: SocketAddress + public mut prop receiveBufferSize: Int64 + public mut prop sendBufferSize: Int64 + public init(bindAt!: SocketAddress) + public init(bindAt!: String) + public override func accept(): UnixSocket + public override func accept(timeout!: ?Duration): UnixSocket + public override func bind(): Unit + public override func close(): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public override func isClosed(): Bool + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public override func toString(): String +} + +public class UnixSocket <: StreamingSocket { + public override prop localAddress: SocketAddress + public override mut prop readTimeout: ?Duration + public mut prop receiveBufferSize: Int64 + public override prop remoteAddress: SocketAddress + public mut prop sendBufferSize: Int64 + public override mut prop writeTimeout: ?Duration + public init(address: SocketAddress) + public init(path: String) + public func close(): Unit + public func connect(timeout!: ?Duration = None): Unit + public func getSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: CPointer): Unit + public func getSocketOptionBool( level: Int32, option: Int32): Bool + public func getSocketOptionIntNative( level: Int32, option: Int32): IntNative + public func isClosed(): Bool + public override func read(buffer: Array): Int64 + public func setSocketOption( level: Int32, option: Int32, value: CPointer, valueLength: UIntNative): Unit + public func setSocketOptionBool( level: Int32, option: Int32, value: Bool): Unit + public func setSocketOptionIntNative( level: Int32, option: Int32, value: IntNative): Unit + public override func toString(): String + public override func write(buffer: Array): Unit +} + +public class UnixSocketAddress <: SocketAddress & Equatable { + public prop family: AddressFamily + public prop size: Int64 + public init(address: Array) + public init(address: String) + public func getAddressBytes(): Array + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let udsa1_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock") @Assert(udsa1_1.getAddressBytes(), "\u{1}\u{0}/tmp/server1.sock".toArray())} + public func hashCode(): Int64 + public func toString(): String + import std.net.*import std.unittest.*import std.unittest.testmacro.*main () { let expect1 = "/tmp/server1.sock" let expect2 = "\u{0}/tmp/server1.sock" let udsa1_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock") let udsa2_1: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock".toArray()) let udsa2_2: UnixSocketAddress = UnixSocketAddress("/tmp/server1.sock\u{0}\u{0}".toArray()) let udsa3_1: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock") let udsa4_1: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock".toArray()) let udsa4_2: UnixSocketAddress = UnixSocketAddress("\u{0}/tmp/server1.sock\u{0}\u{0}".toArray()) @Assert(udsa1_1.toString(), expect1) @Assert(udsa2_1.toString(), expect1) @Assert(udsa2_2.toString(), expect1) @Assert(udsa3_1.toString(), expect2) @Assert(udsa1_1, udsa2_1) @Assert(udsa1_1, udsa2_2) @Assert(udsa3_1, udsa4_1) @Assert(udsa3_1, udsa4_2) @Assert(udsa4_1.toString(), expect2) @Assert(udsa4_2.toString(), expect2) try { UnixSocketAddress("/tmp/server1\u{0}.sock") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("/tmp/server1.sock\u{0}\u{0}") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("\u{0}/tmp/server1.sock\u{0}\u{0}") } catch (e: IllegalArgumentException) { @Assert(true) } try { UnixSocketAddress("/tmp/server1\u{0}.sock".toArray()) } catch (e: IllegalArgumentException) { @Assert(true) } return} + public operator func ==(rhs: UnixSocketAddress): Bool + public operator func !=(rhs: UnixSocketAddress): Bool +} + + +// --------------------------- +// -----vars +// --------------------------- +public let IPV4_ALL_ROUTER: Array {} + +public let IPV4_ALL_SYSTEM: Array {} + +public let IPV4_BROADCAST: Array {} + +public let IPV4_LOCAL_HOST: Array {} + +public let IPV4_ZERO: Array {} + +public let IPV6_INTERFACE_LOCAL_ALL_NODES: Array {} + +public let IPV6_LINK_LOCAL_ALL_NODES: Array {} + +public let IPV6_LINK_LOCAL_ALL_ROUTERS: Array {} + +public let IPV6_LOOPBACK: Array {} + +public let IPV6_ZERO: Array {} + + +// --------------------------- +// -----enums +// --------------------------- +public enum SocketNet <: ToString & Equatable { + TCP + UDP + UNIX + public func toString(): String + public operator func !=(that: SocketNet): Bool + public operator func ==(that: SocketNet): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class SocketException <: Exception { + public init() + public init(message: String) +} + +public class SocketTimeoutException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface DatagramSocket <: Resource & ToString { + prop localAddress: SocketAddress + mut prop receiveTimeout: ?Duration + prop remoteAddress: ?SocketAddress + mut prop sendTimeout: ?Duration + func receiveFrom(buffer: Array): (SocketAddress, Int64) + func sendTo(address: SocketAddress, payload: Array): Unit +} + +public interface ServerSocket <: Resource & ToString { + prop localAddress: SocketAddress + func accept(): StreamingSocket + func accept(timeout!: ?Duration): StreamingSocket + func bind(): Unit +} + +public interface StreamingSocket <: IOStream & Resource & ToString { + prop localAddress: SocketAddress + mut prop readTimeout: ?Duration + prop remoteAddress: SocketAddress + mut prop writeTimeout: ?Duration +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct AddressFamily <: ToString & Equatable { + public static const INET: AddressFamily + public static const INET6: AddressFamily + public static const NETLINK: AddressFamily + public static const UNIX: AddressFamily + public static const UNSPEC: AddressFamily + public let name: String + public let value: Int32 + public const init(name: String, value: Int32) + public func toString(): String + public operator func ==(rhs: AddressFamily): Bool + public operator func !=(rhs: AddressFamily): Bool +} + +public struct OptionLevel { + public static const ICMP: Int32 + public static const IP: Int32 + public static const RAW: Int32 + public static const SOCKET: Int32 + public static const TCP: Int32 + public static const UDP: Int32 +} + +public struct OptionName { + public static const IP_HDRINCL: Int32 + public static const IP_TOS: Int32 + public static const IP_TTL: Int32 + public static const SO_ACCEPTCONN: Int32 + public static const SO_BROADCAST: Int32 + public static const SO_DEBUG: Int32 + public static const SO_DONTROUTE: Int32 + public static const SO_ERROR: Int32 + public static const SO_KEEPALIVE: Int32 + public static const SO_LINGER: Int32 + public static const SO_OOBINLINE: Int32 + public static const SO_RCVBUF: Int32 + public static const SO_RCVTIMEO: Int32 + public static const SO_REUSEADDR: Int32 + public static const SO_SNDBUF: Int32 + public static const SO_SNDTIMEO: Int32 + public static const TCP_KEEPCNT: Int32 + public static const TCP_KEEPIDLE: Int32 + public static const TCP_KEEPINTVL: Int32 + public static const TCP_NODELAY: Int32 +} + +public struct ProtocolType <: Equatable & ToString & Hashable { + public static let ICMP: ProtocolType + public static let IPV4: ProtocolType + public static let IPV6: ProtocolType + public static let RAW: ProtocolType + public static let TCP: ProtocolType + public static let UDP: ProtocolType + public static let Unspecified: ProtocolType + public init(protocol: Int32) + public func hashCode(): Int64 + public func toString(): String + public operator func !=(r: ProtocolType): Bool + public operator func ==(r: ProtocolType): Bool +} + +public struct RawAddress { + public prop addr: Array + public init(addr: Array) +} + +public struct SocketDomain <: Equatable & ToString & Hashable { + public static let IPV4: SocketDomain + public static let IPV6: SocketDomain + public static let NETLINK: SocketDomain + public static let PACKET: SocketDomain + public static let UNIX: SocketDomain + public init(domain: Int32) + public func hashCode(): Int64 + public func toString(): String + public operator func !=(r: SocketDomain): Bool + public operator func ==(r: SocketDomain): Bool +} + +public struct SocketKeepAliveConfig <: ToString & Equatable { + public let count: UInt32 + public let idle: Duration + public let interval: Duration + public init(idle!: Duration = Duration.second * 45, interval!: Duration = Duration.second * 5, count!: UInt32 = 5) + public override func toString(): String + public override operator func !=(other: SocketKeepAliveConfig): Bool + public override operator func ==(other: SocketKeepAliveConfig): Bool +} + +public struct SocketOptions { + public static const IPPROTO_TCP: Int32 = IPPROTO_TCP + public static const IPPROTO_UDP: Int32 = IPPROTO_UDP + public static const SOL_SOCKET: Int32 = SOL_SOCKET + public static const SO_BINDTODEVICE: Int32 = SOCK_BINDTODEVICE + public static const SO_KEEPALIVE: Int32 = SOCK_KEEPALIVE + public static const SO_LINGER: Int32 = SOCK_LINGER + public static const SO_RCVBUF: Int32 = SOCK_RCVBUF + public static const SO_REUSEADDR: Int32 = SOCK_REUSEADDR + public static const SO_REUSEPORT: Int32 = SOCK_REUSEPORT + public static const SO_SNDBUF: Int32 = SOCK_SNDBUF + public static const TCP_NODELAY: Int32 = SOCK_TCP_NODELAY + public static const TCP_QUICKACK: Int32 = SOCK_TCP_QUICKACK +} + +public struct SocketType <: Equatable & ToString & Hashable { + public static let DATAGRAM: SocketType + public static let RAW: SocketType + public static let SEQPACKET: SocketType + public static let STREAM: SocketType + public init(`type`: Int32) + public func hashCode(): Int64 + public func toString(): String + public operator func !=(r: SocketType): Bool + public operator func ==(r: SocketType): Bool +} + + diff --git a/cangjie_libs/std/objectpool.cjd b/cangjie_libs/std/objectpool.cjd new file mode 100644 index 0000000000000000000000000000000000000000..dc85b1b69558ac3b033cf8592641e7a90d945dca --- /dev/null +++ b/cangjie_libs/std/objectpool.cjd @@ -0,0 +1,12 @@ +package std.objectpool + +// --------------------------- +// -----classes +// --------------------------- +public class ObjectPool where T <: Object { + public init(newFunc: () -> T, resetFunc!: Option<(T) -> T> = None) + public func get(): T + public func put(item: T): Unit +} + + diff --git a/cangjie_libs/std/os.cjd b/cangjie_libs/std/os.cjd new file mode 100644 index 0000000000000000000000000000000000000000..a59ec505324e1331777cb976e911462c69a16564 --- /dev/null +++ b/cangjie_libs/std/os.cjd @@ -0,0 +1,15 @@ +package std.os + +// --------------------------- +// -----funcs +// --------------------------- +public func currentDir(): Directory +public func envVars(): HashMap +public func getArgs(): Array +public func getEnv(k: String): Option +public func homeDir(): Directory +public func processorCount(): Int64 +public func removeEnv(k: String): Unit +public func setEnv(k: String, v: String): Unit +public func tempDir(): Directory + diff --git a/cangjie_libs/std/os.posix.cjd b/cangjie_libs/std/os.posix.cjd new file mode 100644 index 0000000000000000000000000000000000000000..95a146df77b95d789a702bc139fd021d96d250e8 --- /dev/null +++ b/cangjie_libs/std/os.posix.cjd @@ -0,0 +1,225 @@ +package std.os.posix + +// --------------------------- +// -----vars +// --------------------------- +public const AT_EMPTY_PATH: Int32 {} + +public const AT_REMOVEDIR: Int32 {} + +public const F_OK: Int32 {} + +public const O_WRONLY: Int32 {} + +public const O_CLOEXEC: Int32 {} + +public const O_CREAT: Int32 {} + +public const O_DIRECTORY: Int32 {} + +public const O_DSYNC: Int32 {} + +public const O_EXCL: Int32 {} + +public const O_NOCTTY: Int32 {} + +public const O_NOFOLLOW: Int32 {} + +public const O_NONBLOCK: Int32 {} + +public const O_RDONLY: Int32 {} + +public const O_RDWR: Int32 {} + +public const O_RSYNC: Int32 {} + +public const O_SYNC: Int32 {} + +public const O_TRUNC: Int32 {} + +public const O_WRONLY: Int32 {} + +public const R_OK: Int32 {} + +public const SEEK_CUR: Int32 {} + +public const SEEK_END: Int32 {} + +public const SEEK_SET: Int32 {} + +public const SIGABRT: Int32 {} + +public const SIGALRM: Int32 {} + +public const SIGBUS: Int32 {} + +public const SIGCHLD: Int32 {} + +public const SIGCONT: Int32 {} + +public const SIGFPE: Int32 {} + +public const SIGHUP: Int32 {} + +public const SIGILL: Int32 {} + +public const SIGINT: Int32 {} + +public const SIGIO: Int32 {} + +public const SIGIOT: Int32 {} + +public const SIGKILL: Int32 {} + +public const SIGPIPE: Int32 {} + +public const SIGPROF: Int32 {} + +public const SIGPWR: Int32 {} + +public const SIGQUIT: Int32 {} + +public const SIGSEGV: Int32 {} + +public const SIGSTKFLT: Int32 {} + +public const SIGSTOP: Int32 {} + +public const SIGTERM: Int32 {} + +public const SIGTRAP: Int32 {} + +public const SIGTSTP: Int32 {} + +public const SIGTTIN: Int32 {} + +public const SIGTTOU: Int32 {} + +public const SIGURG: Int32 {} + +public const SIGUSR1: Int32 {} + +public const SIGUSR2: Int32 {} + +public const SIGVTALRM: Int32 {} + +public const SIGWINCH: Int32 {} + +public const SIGXCPU: Int32 {} + +public const SIGXFSZ: Int32 {} + +public const S_IFBLK: UInt32 {} + +public const S_IFCHR: UInt32 {} + +public const S_IFDIR: UInt32 {} + +public const S_IFIFO: UInt32 {} + +public const S_IFLNK: UInt32 {} + +public const S_IFREG: UInt32 {} + +public const S_IFSOCK: UInt32 {} + +public const S_IRGRP: UInt32 {} + +public const S_IROTH: UInt32 {} + +public const S_IRUSR: UInt32 {} + +public const S_IRWXG: UInt32 {} + +public const S_IRWXO: UInt32 {} + +public const S_IRWXU: UInt32 {} + +public const S_IWGRP: UInt32 {} + +public const S_IWOTH: UInt32 {} + +public const S_IWUSR: UInt32 {} + +public const S_IXGRP: UInt32 {} + +public const S_IXOTH: UInt32 {} + +public const S_IXUSR: UInt32 {} + +public const W_OK: Int32 {} + +public const X_OK: Int32 {} + + +// --------------------------- +// -----funcs +// --------------------------- +public func `open`(path: String, oflag: Int32): Int32 +public func `open`(path: String, oflag: Int32, flag: UInt32): Int32 +public func access(path: String, mode: Int32): Int32 +public func chdir(path: String): Int32 +public func chmod(path: String, mode: UInt32): Int32 +public func chown(path: String, owner: UInt32, group: UInt32): Int32 +public func close(fd: Int32): Int32 +public func creat(path: String, flag: UInt32): Int32 +public func dup(fd: Int32): Int32 +public func dup2(fd: Int32, fd2: Int32): Int32 +public func faccessat(fd: Int32, path: String, mode: Int32, flag: Int32): Int32 +public func fchdir(fd: Int32): Int32 +public func fchmod(fd: Int32, mode: UInt32): Int32 +public func fchmodat(fd: Int32, path: String, mode: UInt32, flag: Int32): Int32 +public func fchown(fd: Int32, owner: UInt32, group: UInt32): Int32 +public func fchownat(fd: Int32, path: String, owner: UInt32, group: UInt32, flag: Int32): Int32 +public func getcwd(): String +public func getgid(): UInt32 +public unsafe func getgroups(size: Int32, gidArray: CPointer): Int32 +public func gethostname(): String +public func getlogin(): String +public func getos(): String +public func getpgid(pid: Int32): Int32 +public func getpgrp(): Int32 +public func getpid(): Int32 +public func getppid(): Int32 +public func getuid(): UInt32 +public func isBlk(path: String): Bool +public func isChr(path: String): Bool +public func isDir(path: String): Bool +public func isFIFO(path: String): Bool +public func isLnk(path: String): Bool +public func isReg(path: String): Bool +public func isSock(path: String): Bool +public func isType(path: String, mode: UInt32): Bool +public func isatty(fd: Int32): Bool +public func kill(pid: Int32, sig: Int32): Int32 +public func killpg(pgid: Int32, sig: Int32): Int32 +public func lchown(path: String, owner: UInt32, group: UInt32): Int32 +public func link(path: String, newpath: String): Int32 +public func linkat(fd: Int32, path: String, nfd: Int32, newPath: String, lflag: Int32): Int32 +public func lseek(fd: Int32, offset: Int64, whence: Int32): Int64 +public func nice(inc: Int32): Int32 +public func open64(path: String, oflag: Int32): Int32 +public func open64(path: String, oflag: Int32, flag: UInt32): Int32 +public func openat(fd: Int32, path: String, oflag: Int32): Int32 +public func openat(fd: Int32, path: String, oflag: Int32, flag: UInt32): Int32 +public func openat64(fd: Int32, path: String, oflag: Int32): Int32 +public func openat64(fd: Int32, path: String, oflag: Int32, flag: UInt32): Int32 +public unsafe func pread(fd: Int32, buffer: CPointer, nbyte: UIntNative, offset: Int32): IntNative +public unsafe func pwrite(fd: Int32, buffer: CPointer, nbyte: UIntNative, offset: Int32): IntNative +public unsafe func read(fd: Int32, buffer: CPointer, nbyte: UIntNative): IntNative +public func remove(path: String): Int32 +public func rename(oldName: String, newName: String): Int32 +public func renameat(oldfd: Int32, oldName: String, newfd: Int32, newName: String): Int32 +public func setgid(id: UInt32): Int32 +public func sethostname(buf: String): Int32 +public func setpgid(pid: Int32, pgrp: Int32): Int32 +public func setpgrp(): Int32 +public func setuid(id: UInt32): Int32 +public func symlink(path: String, symPath: String): Int32 +public func symlinkat(path: String, fd: Int32, symPath: String): Int32 +public func ttyname(fd: Int32): String +public func umask(cmask: UInt32): UInt32 +public func unlink(path: String): Int32 +public func unlinkat(fd: Int32, path: String, ulflag: Int32): Int32 +public unsafe func write(fd: Int32, buffer: CPointer, nbyte: UIntNative): IntNative + diff --git a/cangjie_libs/std/os.process.cjd b/cangjie_libs/std/os.process.cjd new file mode 100644 index 0000000000000000000000000000000000000000..4d7475609892ca9e3113437bd216a4607a87cea5 --- /dev/null +++ b/cangjie_libs/std/os.process.cjd @@ -0,0 +1,57 @@ +package std.os.process + +// --------------------------- +// -----classes +// --------------------------- +public class CurrentProcess <: Process { + public prop stdErr: OutputStream + public prop stdIn: InputStream + public prop stdOut: OutputStream + public func atExit(callback: () -> Unit): Unit + public func exit(code: Int64): Nothing +} + +public open class Process { + public static prop current: CurrentProcess + public prop arguments: Array + public prop command: String + public prop commandLine: Array + public prop environment: Map + public prop name: String + public prop pid: Int64 + public prop workingDirectory: Path + public static func of(pid: Int64): Process + public static func run(command: String, arguments: Array, workingDirectory!: ?Path = None, environment!: ?Map = None, stdIn!: ProcessRedirect = Inherit, stdOut!: ProcessRedirect = Inherit, stdErr!: ProcessRedirect = Inherit, timeout!: ?Duration = None): Int64 + public static func runOutput(command: String, arguments: Array, workingDirectory!: ?Path = None, environment!: ?Map = None, stdIn!: ProcessRedirect = Inherit, stdOut!: ProcessRedirect = Pipe, stdErr!: ProcessRedirect = Pipe): (Int64, Array, Array) + public static func start(command: String, arguments: Array, workingDirectory!: ?Path = None, environment!: ?Map = None, stdIn!: ProcessRedirect = Inherit, stdOut!: ProcessRedirect = Inherit, stdErr!: ProcessRedirect = Inherit): SubProcess + public func terminate(force!: Bool = false): Unit +} + +public class SubProcess <: Process { + public prop stdErr: InputStream + public prop stdIn: OutputStream + public prop stdOut: InputStream + public func wait(timeout!: ?Duration = None): Int64 + public func waitOutput(): (Int64, Array, Array) +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum ProcessRedirect { + Discard + FromFile(File) + Inherit + Pipe +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class ProcessException <: Exception { + public init(message: String) +} + + diff --git a/cangjie_libs/std/overflow.cjd b/cangjie_libs/std/overflow.cjd new file mode 100644 index 0000000000000000000000000000000000000000..e929c183ef8916ac11721408a0064e5769f4a076 --- /dev/null +++ b/cangjie_libs/std/overflow.cjd @@ -0,0 +1,596 @@ +package std.overflow + +// --------------------------- +// -----exceptions +// --------------------------- +public class OvershiftException <: Exception { + public init() + public init(message: String) +} + +public class UndershiftException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface CheckedOp { + func checkedAdd(y: T): ?T + func checkedDec(): ?T + func checkedDiv(y: T): ?T + func checkedInc(): ?T + func checkedMod(y: T): ?T + func checkedMul(y: T): ?T + func checkedNeg(): ?T + func checkedShl(y: T): ?T + func checkedShr(y: T): ?T + func checkedSub(y: T): ?T +} + +extend Int16 <: CheckedOp { + public func checkedAdd(y: Int16): ?Int16 + public func checkedDec(): ?Int16 + public func checkedDiv(y: Int16): ?Int16 + public func checkedInc(): ?Int16 + public func checkedMod(y: Int16): ?Int16 + public func checkedMul(y: Int16): ?Int16 + public func checkedNeg(): ?Int16 + public func checkedShl(y: Int16): ?Int16 + public func checkedShr(y: Int16): ?Int16 + public func checkedSub(y: Int16): ?Int16 +} + +extend Int32 <: CheckedOp { + public func checkedAdd(y: Int32): ?Int32 + public func checkedDec(): ?Int32 + public func checkedDiv(y: Int32): ?Int32 + public func checkedInc(): ?Int32 + public func checkedMod(y: Int32): ?Int32 + public func checkedMul(y: Int32): ?Int32 + public func checkedNeg(): ?Int32 + public func checkedShl(y: Int32): ?Int32 + public func checkedShr(y: Int32): ?Int32 + public func checkedSub(y: Int32): ?Int32 +} + +extend Int64 <: CheckedOp { + public func checkedAdd(y: Int64): ?Int64 + public func checkedDec(): ?Int64 + public func checkedDiv(y: Int64): ?Int64 + public func checkedInc(): ?Int64 + public func checkedMod(y: Int64): ?Int64 + public func checkedMul(y: Int64): ?Int64 + public func checkedNeg(): ?Int64 + public func checkedPow(y: UInt64): ?Int64 + public func checkedShl(y: Int64): ?Int64 + public func checkedShr(y: Int64): ?Int64 + public func checkedSub(y: Int64): ?Int64 +} + +extend Int8 <: CheckedOp { + public func checkedAdd(y: Int8): ?Int8 + public func checkedDec(): ?Int8 + public func checkedDiv(y: Int8): ?Int8 + public func checkedInc(): ?Int8 + public func checkedMod(y: Int8): ?Int8 + public func checkedMul(y: Int8): ?Int8 + public func checkedNeg(): ?Int8 + public func checkedShl(y: Int8): ?Int8 + public func checkedShr(y: Int8): ?Int8 + public func checkedSub(y: Int8): ?Int8 +} + +extend IntNative <: CheckedOp { + public func checkedAdd(y: IntNative): ?IntNative + public func checkedDec(): ?IntNative + public func checkedDiv(y: IntNative): ?IntNative + public func checkedInc(): ?IntNative + public func checkedMod(y: IntNative): ?IntNative + public func checkedMul(y: IntNative): ?IntNative + public func checkedNeg(): ?IntNative + public func checkedShl(y: IntNative): ?IntNative + public func checkedShr(y: IntNative): ?IntNative + public func checkedSub(y: IntNative): ?IntNative +} + +extend UInt16 <: CheckedOp { + public func checkedAdd(y: UInt16): ?UInt16 + public func checkedDec(): ?UInt16 + public func checkedDiv(y: UInt16): ?UInt16 + public func checkedInc(): ?UInt16 + public func checkedMod(y: UInt16): ?UInt16 + public func checkedMul(y: UInt16): ?UInt16 + public func checkedNeg(): ?UInt16 + public func checkedShl(y: UInt16): ?UInt16 + public func checkedShr(y: UInt16): ?UInt16 + public func checkedSub(y: UInt16): ?UInt16 +} + +extend UInt32 <: CheckedOp { + public func checkedAdd(y: UInt32): ?UInt32 + public func checkedDec(): ?UInt32 + public func checkedDiv(y: UInt32): ?UInt32 + public func checkedInc(): ?UInt32 + public func checkedMod(y: UInt32): ?UInt32 + public func checkedMul(y: UInt32): ?UInt32 + public func checkedNeg(): ?UInt32 + public func checkedShl(y: UInt32): ?UInt32 + public func checkedShr(y: UInt32): ?UInt32 + public func checkedSub(y: UInt32): ?UInt32 +} + +extend UInt64 <: CheckedOp { + public func checkedAdd(y: UInt64): ?UInt64 + public func checkedDec(): ?UInt64 + public func checkedDiv(y: UInt64): ?UInt64 + public func checkedInc(): ?UInt64 + public func checkedMod(y: UInt64): ?UInt64 + public func checkedMul(y: UInt64): ?UInt64 + public func checkedNeg(): ?UInt64 + public func checkedShl(y: UInt64): ?UInt64 + public func checkedShr(y: UInt64): ?UInt64 + public func checkedSub(y: UInt64): ?UInt64 +} + +extend UInt8 <: CheckedOp { + public func checkedAdd(y: UInt8): ?UInt8 + public func checkedDec(): ?UInt8 + public func checkedDiv(y: UInt8): ?UInt8 + public func checkedInc(): ?UInt8 + public func checkedMod(y: UInt8): ?UInt8 + public func checkedMul(y: UInt8): ?UInt8 + public func checkedNeg(): ?UInt8 + public func checkedShl(y: UInt8): ?UInt8 + public func checkedShr(y: UInt8): ?UInt8 + public func checkedSub(y: UInt8): ?UInt8 +} + +extend UIntNative <: CheckedOp { + public func checkedAdd(y: UIntNative): ?UIntNative + public func checkedDec(): ?UIntNative + public func checkedDiv(y: UIntNative): ?UIntNative + public func checkedInc(): ?UIntNative + public func checkedMod(y: UIntNative): ?UIntNative + public func checkedMul(y: UIntNative): ?UIntNative + public func checkedNeg(): ?UIntNative + public func checkedShl(y: UIntNative): ?UIntNative + public func checkedShr(y: UIntNative): ?UIntNative + public func checkedSub(y: UIntNative): ?UIntNative +} + +public interface SaturatingOp { + func saturatingAdd(y: T): T + func saturatingDec(): T + func saturatingDiv(y: T): T + func saturatingInc(): T + func saturatingMod(y: T): T + func saturatingMul(y: T): T + func saturatingNeg(): T + func saturatingShl(y: T): T + func saturatingShr(y: T): T + func saturatingSub(y: T): T +} + +extend Int16 <: SaturatingOp { + public func saturatingAdd(y: Int16): Int16 + public func saturatingDec(): Int16 + public func saturatingDiv(y: Int16): Int16 + public func saturatingInc(): Int16 + public func saturatingMod(y: Int16): Int16 + public func saturatingMul(y: Int16): Int16 + public func saturatingNeg(): Int16 + public func saturatingShl(y: Int16): Int16 + public func saturatingShr(y: Int16): Int16 + public func saturatingSub(y: Int16): Int16 +} + +extend Int32 <: SaturatingOp { + public func saturatingAdd(y: Int32): Int32 + public func saturatingDec(): Int32 + public func saturatingDiv(y: Int32): Int32 + public func saturatingInc(): Int32 + public func saturatingMod(y: Int32): Int32 + public func saturatingMul(y: Int32): Int32 + public func saturatingNeg(): Int32 + public func saturatingShl(y: Int32): Int32 + public func saturatingShr(y: Int32): Int32 + public func saturatingSub(y: Int32): Int32 +} + +extend Int64 <: SaturatingOp { + public func saturatingAdd(y: Int64): Int64 + public func saturatingDec(): Int64 + public func saturatingDiv(y: Int64): Int64 + public func saturatingInc(): Int64 + public func saturatingMod(y: Int64): Int64 + public func saturatingMul(y: Int64): Int64 + public func saturatingNeg(): Int64 + public func saturatingPow(y: UInt64): Int64 + public func saturatingShl(y: Int64): Int64 + public func saturatingShr(y: Int64): Int64 + public func saturatingSub(y: Int64): Int64 +} + +extend Int8 <: SaturatingOp { + public func saturatingAdd(y: Int8): Int8 + public func saturatingDec(): Int8 + public func saturatingDiv(y: Int8): Int8 + public func saturatingInc(): Int8 + public func saturatingMod(y: Int8): Int8 + public func saturatingMul(y: Int8): Int8 + public func saturatingNeg(): Int8 + public func saturatingShl(y: Int8): Int8 + public func saturatingShr(y: Int8): Int8 + public func saturatingSub(y: Int8): Int8 +} + +extend IntNative <: SaturatingOp { + public func saturatingAdd(y: IntNative): IntNative + public func saturatingDec(): IntNative + public func saturatingDiv(y: IntNative): IntNative + public func saturatingInc(): IntNative + public func saturatingMod(y: IntNative): IntNative + public func saturatingMul(y: IntNative): IntNative + public func saturatingNeg(): IntNative + public func saturatingShl(y: IntNative): IntNative + public func saturatingShr(y: IntNative): IntNative + public func saturatingSub(y: IntNative): IntNative +} + +extend UInt16 <: SaturatingOp { + public func saturatingAdd(y: UInt16): UInt16 + public func saturatingDec(): UInt16 + public func saturatingDiv(y: UInt16): UInt16 + public func saturatingInc(): UInt16 + public func saturatingMod(y: UInt16): UInt16 + public func saturatingMul(y: UInt16): UInt16 + public func saturatingNeg(): UInt16 + public func saturatingShl(y: UInt16): UInt16 + public func saturatingShr(y: UInt16): UInt16 + public func saturatingSub(y: UInt16): UInt16 +} + +extend UInt32 <: SaturatingOp { + public func saturatingAdd(y: UInt32): UInt32 + public func saturatingDec(): UInt32 + public func saturatingDiv(y: UInt32): UInt32 + public func saturatingInc(): UInt32 + public func saturatingMod(y: UInt32): UInt32 + public func saturatingMul(y: UInt32): UInt32 + public func saturatingNeg(): UInt32 + public func saturatingShl(y: UInt32): UInt32 + public func saturatingShr(y: UInt32): UInt32 + public func saturatingSub(y: UInt32): UInt32 +} + +extend UInt64 <: SaturatingOp { + public func saturatingAdd(y: UInt64): UInt64 + public func saturatingDec(): UInt64 + public func saturatingDiv(y: UInt64): UInt64 + public func saturatingInc(): UInt64 + public func saturatingMod(y: UInt64): UInt64 + public func saturatingMul(y: UInt64): UInt64 + public func saturatingNeg(): UInt64 + public func saturatingShl(y: UInt64): UInt64 + public func saturatingShr(y: UInt64): UInt64 + public func saturatingSub(y: UInt64): UInt64 +} + +extend UInt8 <: SaturatingOp { + public func saturatingAdd(y: UInt8): UInt8 + public func saturatingDec(): UInt8 + public func saturatingDiv(y: UInt8): UInt8 + public func saturatingInc(): UInt8 + public func saturatingMod(y: UInt8): UInt8 + public func saturatingMul(y: UInt8): UInt8 + public func saturatingNeg(): UInt8 + public func saturatingShl(y: UInt8): UInt8 + public func saturatingShr(y: UInt8): UInt8 + public func saturatingSub(y: UInt8): UInt8 +} + +extend UIntNative <: SaturatingOp { + public func saturatingAdd(y: UIntNative): UIntNative + public func saturatingDec(): UIntNative + public func saturatingDiv(y: UIntNative): UIntNative + public func saturatingInc(): UIntNative + public func saturatingMod(y: UIntNative): UIntNative + public func saturatingMul(y: UIntNative): UIntNative + public func saturatingNeg(): UIntNative + public func saturatingShl(y: UIntNative): UIntNative + public func saturatingShr(y: UIntNative): UIntNative + public func saturatingSub(y: UIntNative): UIntNative +} + +public interface ThrowingOp { + func throwingAdd(y: T): T + func throwingDec(): T + func throwingDiv(y: T): T + func throwingInc(): T + func throwingMod(y: T): T + func throwingMul(y: T): T + func throwingNeg(): T + func throwingShl(y: T): T + func throwingShr(y: T): T + func throwingSub(y: T): T +} + +extend Int16 <: ThrowingOp { + public func throwingAdd(y: Int16): Int16 + public func throwingDec(): Int16 + public func throwingDiv(y: Int16): Int16 + public func throwingInc(): Int16 + public func throwingMod(y: Int16): Int16 + public func throwingMul(y: Int16): Int16 + public func throwingNeg(): Int16 + public func throwingShl(y: Int16): Int16 + public func throwingShr(y: Int16): Int16 + public func throwingSub(y: Int16): Int16 +} + +extend Int32 <: ThrowingOp { + public func throwingAdd(y: Int32): Int32 + public func throwingDec(): Int32 + public func throwingDiv(y: Int32): Int32 + public func throwingInc(): Int32 + public func throwingMod(y: Int32): Int32 + public func throwingMul(y: Int32): Int32 + public func throwingNeg(): Int32 + public func throwingShl(y: Int32): Int32 + public func throwingShr(y: Int32): Int32 + public func throwingSub(y: Int32): Int32 +} + +extend Int64 <: ThrowingOp { + public func throwingAdd(y: Int64): Int64 + public func throwingDec(): Int64 + public func throwingDiv(y: Int64): Int64 + public func throwingInc(): Int64 + public func throwingMod(y: Int64): Int64 + public func throwingMul(y: Int64): Int64 + public func throwingNeg(): Int64 + public func throwingPow(y: UInt64): Int64 + public func throwingShl(y: Int64): Int64 + public func throwingShr(y: Int64): Int64 + public func throwingSub(y: Int64): Int64 +} + +extend Int8 <: ThrowingOp { + public func throwingAdd(y: Int8): Int8 + public func throwingDec(): Int8 + public func throwingDiv(y: Int8): Int8 + public func throwingInc(): Int8 + public func throwingMod(y: Int8): Int8 + public func throwingMul(y: Int8): Int8 + public func throwingNeg(): Int8 + public func throwingShl(y: Int8): Int8 + public func throwingShr(y: Int8): Int8 + public func throwingSub(y: Int8): Int8 +} + +extend IntNative <: ThrowingOp { + public func throwingAdd(y: IntNative): IntNative + public func throwingDec(): IntNative + public func throwingDiv(y: IntNative): IntNative + public func throwingInc(): IntNative + public func throwingMod(y: IntNative): IntNative + public func throwingMul(y: IntNative): IntNative + public func throwingNeg(): IntNative + public func throwingShl(y: IntNative): IntNative + public func throwingShr(y: IntNative): IntNative + public func throwingSub(y: IntNative): IntNative +} + +extend UInt16 <: ThrowingOp { + public func throwingAdd(y: UInt16): UInt16 + public func throwingDec(): UInt16 + public func throwingDiv(y: UInt16): UInt16 + public func throwingInc(): UInt16 + public func throwingMod(y: UInt16): UInt16 + public func throwingMul(y: UInt16): UInt16 + public func throwingNeg(): UInt16 + public func throwingShl(y: UInt16): UInt16 + public func throwingShr(y: UInt16): UInt16 + public func throwingSub(y: UInt16): UInt16 +} + +extend UInt32 <: ThrowingOp { + public func throwingAdd(y: UInt32): UInt32 + public func throwingDec(): UInt32 + public func throwingDiv(y: UInt32): UInt32 + public func throwingInc(): UInt32 + public func throwingMod(y: UInt32): UInt32 + public func throwingMul(y: UInt32): UInt32 + public func throwingNeg(): UInt32 + public func throwingShl(y: UInt32): UInt32 + public func throwingShr(y: UInt32): UInt32 + public func throwingSub(y: UInt32): UInt32 +} + +extend UInt64 <: ThrowingOp { + public func throwingAdd(y: UInt64): UInt64 + public func throwingDec(): UInt64 + public func throwingDiv(y: UInt64): UInt64 + public func throwingInc(): UInt64 + public func throwingMod(y: UInt64): UInt64 + public func throwingMul(y: UInt64): UInt64 + public func throwingNeg(): UInt64 + public func throwingShl(y: UInt64): UInt64 + public func throwingShr(y: UInt64): UInt64 + public func throwingSub(y: UInt64): UInt64 +} + +extend UInt8 <: ThrowingOp { + public func throwingAdd(y: UInt8): UInt8 + public func throwingDec(): UInt8 + public func throwingDiv(y: UInt8): UInt8 + public func throwingInc(): UInt8 + public func throwingMod(y: UInt8): UInt8 + public func throwingMul(y: UInt8): UInt8 + public func throwingNeg(): UInt8 + public func throwingShl(y: UInt8): UInt8 + public func throwingShr(y: UInt8): UInt8 + public func throwingSub(y: UInt8): UInt8 +} + +extend UIntNative <: ThrowingOp { + public func throwingAdd(y: UIntNative): UIntNative + public func throwingDec(): UIntNative + public func throwingDiv(y: UIntNative): UIntNative + public func throwingInc(): UIntNative + public func throwingMod(y: UIntNative): UIntNative + public func throwingMul(y: UIntNative): UIntNative + public func throwingNeg(): UIntNative + public func throwingShl(y: UIntNative): UIntNative + public func throwingShr(y: UIntNative): UIntNative + public func throwingSub(y: UIntNative): UIntNative +} + +public interface WrappingOp { + func wrappingAdd(y: T): T + func wrappingDec(): T + func wrappingDiv(y: T): T + func wrappingInc(): T + func wrappingMod(y: T): T + func wrappingMul(y: T): T + func wrappingNeg(): T + func wrappingShl(y: T): T + func wrappingShr(y: T): T + func wrappingSub(y: T): T +} + +extend Int16 <: WrappingOp { + public func wrappingAdd(y: Int16): Int16 + public func wrappingDec(): Int16 + public func wrappingDiv(y: Int16): Int16 + public func wrappingInc(): Int16 + public func wrappingMod(y: Int16): Int16 + public func wrappingMul(y: Int16): Int16 + public func wrappingNeg(): Int16 + public func wrappingShl(y: Int16): Int16 + public func wrappingShr(y: Int16): Int16 + public func wrappingSub(y: Int16): Int16 +} + +extend Int32 <: WrappingOp { + public func wrappingAdd(y: Int32): Int32 + public func wrappingDec(): Int32 + public func wrappingDiv(y: Int32): Int32 + public func wrappingInc(): Int32 + public func wrappingMod(y: Int32): Int32 + public func wrappingMul(y: Int32): Int32 + public func wrappingNeg(): Int32 + public func wrappingShl(y: Int32): Int32 + public func wrappingShr(y: Int32): Int32 + public func wrappingSub(y: Int32): Int32 +} + +extend Int64 <: WrappingOp { + public func wrappingAdd(y: Int64): Int64 + public func wrappingDec(): Int64 + public func wrappingDiv(y: Int64): Int64 + public func wrappingInc(): Int64 + public func wrappingMod(y: Int64): Int64 + public func wrappingMul(y: Int64): Int64 + public func wrappingNeg(): Int64 + public func wrappingPow(y: UInt64): Int64 + public func wrappingShl(y: Int64): Int64 + public func wrappingShr(y: Int64): Int64 + public func wrappingSub(y: Int64): Int64 +} + +extend Int8 <: WrappingOp { + public func wrappingAdd(y: Int8): Int8 + public func wrappingDec(): Int8 + public func wrappingDiv(y: Int8): Int8 + public func wrappingInc(): Int8 + public func wrappingMod(y: Int8): Int8 + public func wrappingMul(y: Int8): Int8 + public func wrappingNeg(): Int8 + public func wrappingShl(y: Int8): Int8 + public func wrappingShr(y: Int8): Int8 + public func wrappingSub(y: Int8): Int8 +} + +extend IntNative <: WrappingOp { + public func wrappingAdd(y: IntNative): IntNative + public func wrappingDec(): IntNative + public func wrappingDiv(y: IntNative): IntNative + public func wrappingInc(): IntNative + public func wrappingMod(y: IntNative): IntNative + public func wrappingMul(y: IntNative): IntNative + public func wrappingNeg(): IntNative + public func wrappingShl(y: IntNative): IntNative + public func wrappingShr(y: IntNative): IntNative + public func wrappingSub(y: IntNative): IntNative +} + +extend UInt16 <: WrappingOp { + public func wrappingAdd(y: UInt16): UInt16 + public func wrappingDec(): UInt16 + public func wrappingDiv(y: UInt16): UInt16 + public func wrappingInc(): UInt16 + public func wrappingMod(y: UInt16): UInt16 + public func wrappingMul(y: UInt16): UInt16 + public func wrappingNeg(): UInt16 + public func wrappingShl(y: UInt16): UInt16 + public func wrappingShr(y: UInt16): UInt16 + public func wrappingSub(y: UInt16): UInt16 +} + +extend UInt32 <: WrappingOp { + public func wrappingAdd(y: UInt32): UInt32 + public func wrappingDec(): UInt32 + public func wrappingDiv(y: UInt32): UInt32 + public func wrappingInc(): UInt32 + public func wrappingMod(y: UInt32): UInt32 + public func wrappingMul(y: UInt32): UInt32 + public func wrappingNeg(): UInt32 + public func wrappingShl(y: UInt32): UInt32 + public func wrappingShr(y: UInt32): UInt32 + public func wrappingSub(y: UInt32): UInt32 +} + +extend UInt64 <: WrappingOp { + public func wrappingAdd(y: UInt64): UInt64 + public func wrappingDec(): UInt64 + public func wrappingDiv(y: UInt64): UInt64 + public func wrappingInc(): UInt64 + public func wrappingMod(y: UInt64): UInt64 + public func wrappingMul(y: UInt64): UInt64 + public func wrappingNeg(): UInt64 + public func wrappingShl(y: UInt64): UInt64 + public func wrappingShr(y: UInt64): UInt64 + public func wrappingSub(y: UInt64): UInt64 +} + +extend UInt8 <: WrappingOp { + public func wrappingAdd(y: UInt8): UInt8 + public func wrappingDec(): UInt8 + public func wrappingDiv(y: UInt8): UInt8 + public func wrappingInc(): UInt8 + public func wrappingMod(y: UInt8): UInt8 + public func wrappingMul(y: UInt8): UInt8 + public func wrappingNeg(): UInt8 + public func wrappingShl(y: UInt8): UInt8 + public func wrappingShr(y: UInt8): UInt8 + public func wrappingSub(y: UInt8): UInt8 +} + +extend UIntNative <: WrappingOp { + public func wrappingAdd(y: UIntNative): UIntNative + public func wrappingDec(): UIntNative + public func wrappingDiv(y: UIntNative): UIntNative + public func wrappingInc(): UIntNative + public func wrappingMod(y: UIntNative): UIntNative + public func wrappingMul(y: UIntNative): UIntNative + public func wrappingNeg(): UIntNative + public func wrappingShl(y: UIntNative): UIntNative + public func wrappingShr(y: UIntNative): UIntNative + public func wrappingSub(y: UIntNative): UIntNative +} + + diff --git a/cangjie_libs/std/random.cjd b/cangjie_libs/std/random.cjd new file mode 100644 index 0000000000000000000000000000000000000000..39b33ea3dfe3051ff9654ac0a3ea572bcab00d01 --- /dev/null +++ b/cangjie_libs/std/random.cjd @@ -0,0 +1,40 @@ +package std.random + +// --------------------------- +// -----classes +// --------------------------- +public open class Random { + public open mut prop seed: UInt64 + public init() + public init(seed: UInt64) + public open func next(bits: UInt64): UInt64 + public open func nextBool(): Bool + public open func nextFloat16(): Float16 + public open func nextFloat32(): Float32 + public open func nextFloat64(): Float64 + public func nextGaussianFloat16(mean!: Float16 = 0.0, sigma!: Float16 = 1.0): Float16 + protected open func nextGaussianFloat16Implement(mean: Float16, sigma: Float16): Float16 + public func nextGaussianFloat32(mean!: Float32 = 0.0, sigma!: Float32 = 1.0): Float32 + protected open func nextGaussianFloat32Implement(mean: Float32, sigma: Float32): Float32 + public func nextGaussianFloat64(mean!: Float64 = 0.0, sigma!: Float64 = 1.0): Float64 + protected open func nextGaussianFloat64Implement(mean: Float64, sigma: Float64): Float64 + public open func nextInt16(): Int16 + public open func nextInt16(upper: Int16): Int16 + public open func nextInt32(): Int32 + public open func nextInt32(upper: Int32): Int32 + public open func nextInt64(): Int64 + public open func nextInt64(upper: Int64): Int64 + public open func nextInt8(): Int8 + public open func nextInt8(upper: Int8): Int8 + public open func nextUInt16(): UInt16 + public open func nextUInt16(upper: UInt16): UInt16 + public open func nextUInt32(): UInt32 + public open func nextUInt32(upper: UInt32): UInt32 + public open func nextUInt64(): UInt64 + public open func nextUInt64(upper: UInt64): UInt64 + public open func nextUInt8(): UInt8 + public open func nextUInt8(upper: UInt8): UInt8 + public open func nextUInt8s(array: Array): Array +} + + diff --git a/cangjie_libs/std/reflect.cjd b/cangjie_libs/std/reflect.cjd new file mode 100644 index 0000000000000000000000000000000000000000..3e62095a47f6c3b324e04d2f0b1a9fe1c79d2c71 --- /dev/null +++ b/cangjie_libs/std/reflect.cjd @@ -0,0 +1,296 @@ +package std.reflect + +// --------------------------- +// -----classes +// --------------------------- +public class ClassTypeInfo <: TypeInfo { + public prop constructors: Collection + public prop instanceVariables: Collection + public prop sealedSubclasses: Collection + public prop staticVariables: Collection + public prop superClass: Option + public func construct(args: Array): Any + public func getConstructor(parameterTypes: Array): ConstructorInfo + public func getInstanceVariable(name: String): InstanceVariableInfo + public func getStaticVariable(name: String): StaticVariableInfo + public func isAbstract(): Bool + public func isOpen(): Bool + public func isSealed(): Bool +} + +public class ConstructorInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop parameters: InfoList + public func apply(args: Array): Any + public func findAnnotation(): Option where T <: Annotation + public func hashCode(): Int64 + public func toString(): String + public operator func !=(that: ConstructorInfo): Bool + public operator func ==(that: ConstructorInfo): Bool +} + +public class GlobalFunctionInfo <: Equatable & Hashable & ToString { + public prop name: String + public prop parameters: InfoList + public prop returnType: TypeInfo + public func apply(args: Array): Any + public func hashCode(): Int64 + public func toString(): String + public operator func ==(that: GlobalFunctionInfo): Bool + public operator func !=(that: GlobalFunctionInfo): Bool +} + +public class GlobalVariableInfo <: Equatable & Hashable & ToString { + public prop name: String + public prop typeInfo: TypeInfo + public func getValue(): Any + public func hashCode(): Int64 + public func isMutable(): Bool + public func setValue(newValue: Any): Unit + public func toString(): String + public operator func ==(that: GlobalVariableInfo): Bool + public operator func !=(that: GlobalVariableInfo): Bool +} + +public class InfoList <: Collection { + public prop size: Int64 + public func get(index: Int64): ?T + public func isEmpty(): Bool + public func iterator(): Iterator + public operator func [](index: Int64): T +} + +public class InstanceFunctionInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop parameters: InfoList + public prop returnType: TypeInfo + public func apply(instance: Any, args: Array): Any + public func findAnnotation(): Option where T <: Annotation + public func hashCode(): Int64 + public func isAbstract(): Bool + public func isOpen(): Bool + public func toString(): String + public operator func ==(that: InstanceFunctionInfo): Bool + public operator func !=(that: InstanceFunctionInfo): Bool +} + +public class InstancePropertyInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop typeInfo: TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func getValue(instance: Any): Any + public func hashCode(): Int64 + public func isMutable(): Bool + public func setValue(instance: Any, newValue: Any): Unit + public func toString(): String + public operator func !=(that: InstancePropertyInfo): Bool + public operator func ==(that: InstancePropertyInfo): Bool +} + +public class InstanceVariableInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop typeInfo: TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func getValue(instance: Any): Any + public func hashCode(): Int64 + public func isMutable(): Bool + public func setValue(instance: Any, newValue: Any): Unit + public func toString(): String + public operator func ==(that: InstanceVariableInfo): Bool + public operator func !=(that: InstanceVariableInfo): Bool +} + +public class InterfaceTypeInfo <: TypeInfo { + public prop sealedSubtypes: Collection + public func isSealed(): Bool +} + +public class ModuleInfo <: Equatable & Hashable & ToString { + public prop name: String + public prop packages: Collection + public prop version: String + public static func find(moduleName: String): Option + public static func load(path: String): ModuleInfo + public func getPackageInfo(packageName: String): PackageInfo + public func hashCode(): Int64 + public func toString(): String + public operator func !=(that: ModuleInfo): Bool + public operator func ==(that: ModuleInfo): Bool +} + +public class PackageInfo <: Equatable & Hashable & ToString { + public prop functions: Collection + public prop name: String + public prop qualifiedName: String + public prop typeInfos: Collection + public prop variables: Collection + public func getFunction(name: String, parameterTypes: Array): GlobalFunctionInfo + public func getTypeInfo(qualifiedName: String): TypeInfo + public func getVariable(name: String): GlobalVariableInfo + public func hashCode(): Int64 + public func toString(): String + public operator func !=(that: PackageInfo): Bool + public operator func ==(that: PackageInfo): Bool +} + +public class ParameterInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop index: Int64 + public prop name: String + public prop typeInfo: TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func hashCode(): Int64 + public func toString(): String + public operator func !=(that: ParameterInfo): Bool + public operator func ==(that: ParameterInfo): Bool +} + +public class PrimitiveTypeInfo <: TypeInfo {} + +public class StaticFunctionInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop parameters: InfoList + public prop returnType: TypeInfo + public func apply(args: Array): Any + public func findAnnotation(): Option where T <: Annotation + public func hashCode(): Int64 + public func toString(): String + public operator func !=(that: StaticFunctionInfo): Bool + public operator func ==(that: StaticFunctionInfo): Bool +} + +public class StaticPropertyInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop typeInfo: TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func getValue(): Any + public func hashCode(): Int64 + public func isMutable(): Bool + public func setValue(newValue: Any): Unit + public func toString(): String + public operator func !=(that: StaticPropertyInfo): Bool + public operator func ==(that: StaticPropertyInfo): Bool +} + +public class StaticVariableInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop modifiers: Collection + public prop name: String + public prop typeInfo: TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func getValue(): Any + public func hashCode(): Int64 + public func isMutable(): Bool + public func setValue(newValue: Any): Unit + public func toString(): String + public operator func !=(that: StaticVariableInfo): Bool + public operator func ==(that: StaticVariableInfo): Bool +} + +public class StructTypeInfo <: TypeInfo { + public prop constructors: Collection + public prop instanceVariables: Collection + public prop staticVariables: Collection + public func construct(args: Array): Any + public func getConstructor(parameterTypes: Array): ConstructorInfo + public func getInstanceVariable(name: String): InstanceVariableInfo + public func getStaticVariable(name: String): StaticVariableInfo +} + +sealed abstract class TypeInfo <: Equatable & Hashable & ToString { + public prop annotations: Collection + public prop instanceFunctions: Collection + public prop instanceProperties: Collection + public prop modifiers: Collection + public prop name: String + public prop qualifiedName: String + public prop staticFunctions: Collection + public prop staticProperties: Collection + public prop superInterfaces: Collection + public static func get(qualifiedName: String): TypeInfo + public static func of(a: Any): TypeInfo + public static func of(a: Object): ClassTypeInfo + public static func of(): TypeInfo + public func findAnnotation(): Option where T <: Annotation + public func getInstanceFunction(name: String, parameterTypes: Array): InstanceFunctionInfo + public func getInstanceProperty(name: String): InstancePropertyInfo + public func getStaticFunction(name: String, parameterTypes: Array): StaticFunctionInfo + public func getStaticProperty(name: String): StaticPropertyInfo + public func hashCode(): Int64 + public func isSubtypeOf(supertype: TypeInfo): Bool + public func toString(): String + public operator func !=(that: TypeInfo): Bool + public operator func ==(that: TypeInfo): Bool +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum ModifierInfo <: Equatable & Hashable & ToString { + Abstract + Mut + Open + Override + Redef + Sealed + Static + public func hashCode(): Int64 + public func toString(): String + public operator func ==(that: ModifierInfo): Bool + public operator func !=(that: ModifierInfo): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class IllegalSetException <: ReflectException { + public init() + public init(message: String) +} + +public class IllegalTypeException <: ReflectException { + public init() + public init(message: String) +} + +public class InfoNotFoundException <: ReflectException { + public init() + public init(message: String) +} + +public class InvocationTargetException <: ReflectException { + public init() + public init(message: String) +} + +public class MisMatchException <: ReflectException { + public init() + public init(message: String) +} + +public open class ReflectException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func parseParameterTypes(parameterTypes: String): Array { + import m1.p1.T1func f(a: Int64, b: T1, c!: Int64 = 0, d!: Int64 = 0): Int64 { ... } +} + + diff --git a/cangjie_libs/std/regex.cjd b/cangjie_libs/std/regex.cjd new file mode 100644 index 0000000000000000000000000000000000000000..058b27ee4ec62d747e6dc6ab9c338f359b32abc9 --- /dev/null +++ b/cangjie_libs/std/regex.cjd @@ -0,0 +1,68 @@ +package std.regex + +// --------------------------- +// -----classes +// --------------------------- +public class MatchData { + public func groupNumber(): Int64 + public func matchPosition(): Position + public func matchPosition(group: Int64): Position + public func matchStr(): String + public func matchStr(group: Int64): String +} + +public class Matcher { + public init(re: Regex, input: String) + public func allCount(): Int64 + public func find(): Option + public func find(index: Int64): Option + public func findAll(): Option> + public func fullMatch(): Option + public func getString(): String + public func matchStart(): Option + public func region(): Position + public func replace(replacement: String): String + public func replace(replacement: String, index: Int64): String + public func replaceAll(replacement: String): String + public func replaceAll(replacement: String, limit: Int64): String + public func resetRegion(): Matcher + public func resetString(input: String): Matcher + public func setRegion(beginIndex: Int64, endIndex: Int64): Matcher + public func split(): Array + public func split(limit: Int64): Array +} + +public class Regex { + public init(s: String) + public init(s: String, option: RegexOption) + public func matcher(input: String): Matcher + public func matches(input: String): Option + public func string(): String +} + +public class RegexOption <: ToString { + public init() + public func ignoreCase(): RegexOption + public func multiLine(): RegexOption + public func toString(): String +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class RegexException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct Position { + public prop end: Int64 + public prop start: Int64 +} + + diff --git a/cangjie_libs/std/runtime.cjd b/cangjie_libs/std/runtime.cjd new file mode 100644 index 0000000000000000000000000000000000000000..0e3d649eec7b96334e0c687295823ef17cdb7c2a --- /dev/null +++ b/cangjie_libs/std/runtime.cjd @@ -0,0 +1,24 @@ +package std.runtime + +// --------------------------- +// -----funcs +// --------------------------- +public func GC(heavy!: Bool = false): Unit +public func SetGCThreshold(value: UInt64): Unit + +// --------------------------- +// -----structs +// --------------------------- +public struct MemoryInfo { + public static prop allocatedHeapSize: Int64 + public static prop heapPhysicalMemory: Int64 + public static prop maxHeapSize: Int64 +} + +public struct ThreadInfo { + public static prop blockingThreadCount: Int64 + public static prop nativeThreadCount: Int64 + public static prop threadCount: Int64 +} + + diff --git a/cangjie_libs/std/sort.cjd b/cangjie_libs/std/sort.cjd new file mode 100644 index 0000000000000000000000000000000000000000..3006cd97e33da928e235f990caf45c6afeb82b46 --- /dev/null +++ b/cangjie_libs/std/sort.cjd @@ -0,0 +1,27 @@ +package std.sort + +// --------------------------- +// -----funcs +// --------------------------- +public func stableSort(data: Array): Unit where T <: Comparable +public func stableSort(data: Array, comparator: (T, T) -> Ordering): Unit +public func unstableSort(data: Array): Unit where T <: Comparable +public func unstableSort(data: Array, comparator: (T, T) -> Ordering): Unit + +// --------------------------- +// -----interfaces +// --------------------------- +public interface SortByExtension {} + +extend Array <: SortByExtension { + public func sortBy(stable!: Bool = false, comparator!: (T, T) -> Ordering): Unit +} + +public interface SortExtension {} + +extend Array <: SortExtension where T <: Comparable { + public func sort(stable!: Bool = false): Unit + public func sortDescending(stable!: Bool = false): Unit +} + + diff --git a/cangjie_libs/std/sync.cjd b/cangjie_libs/std/sync.cjd new file mode 100644 index 0000000000000000000000000000000000000000..a85998a928274a5b984071221a140240c4888864 --- /dev/null +++ b/cangjie_libs/std/sync.cjd @@ -0,0 +1,346 @@ +package std.sync + +// --------------------------- +// -----classes +// --------------------------- +public class AtomicBool { + public init(val: Bool) + public func compareAndSwap(old: Bool, new: Bool): Bool + public func compareAndSwap(old: Bool, new: Bool, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func load(): Bool + public func load(memoryOrder!: MemoryOrder): Bool + public func store(val: Bool): Unit + public func store(val: Bool, memoryOrder!: MemoryOrder): Unit + public func swap(val: Bool): Bool + public func swap(val: Bool, memoryOrder!: MemoryOrder): Bool +} + +public class AtomicInt16 { + public init(val: Int16) + public func compareAndSwap(old: Int16, new: Int16): Bool + public func compareAndSwap(old: Int16, new: Int16, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: Int16): Int16 + public func fetchAdd(val: Int16, memoryOrder!: MemoryOrder): Int16 + public func fetchAnd(val: Int16): Int16 + public func fetchAnd(val: Int16, memoryOrder!: MemoryOrder): Int16 + public func fetchOr(val: Int16): Int16 + public func fetchOr(val: Int16, memoryOrder!: MemoryOrder): Int16 + public func fetchSub(val: Int16): Int16 + public func fetchSub(val: Int16, memoryOrder!: MemoryOrder): Int16 + public func fetchXor(val: Int16): Int16 + public func fetchXor(val: Int16, memoryOrder!: MemoryOrder): Int16 + public func load(): Int16 + public func load(memoryOrder!: MemoryOrder): Int16 + public func store(val: Int16): Unit + public func store(val: Int16, memoryOrder!: MemoryOrder): Unit + public func swap(val: Int16): Int16 + public func swap(val: Int16, memoryOrder!: MemoryOrder): Int16 +} + +public class AtomicInt32 { + public init(val: Int32) + public func compareAndSwap(old: Int32, new: Int32): Bool + public func compareAndSwap(old: Int32, new: Int32, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: Int32): Int32 + public func fetchAdd(val: Int32, memoryOrder!: MemoryOrder): Int32 + public func fetchAnd(val: Int32): Int32 + public func fetchAnd(val: Int32, memoryOrder!: MemoryOrder): Int32 + public func fetchOr(val: Int32): Int32 + public func fetchOr(val: Int32, memoryOrder!: MemoryOrder): Int32 + public func fetchSub(val: Int32): Int32 + public func fetchSub(val: Int32, memoryOrder!: MemoryOrder): Int32 + public func fetchXor(val: Int32): Int32 + public func fetchXor(val: Int32, memoryOrder!: MemoryOrder): Int32 + public func load(): Int32 + public func load(memoryOrder!: MemoryOrder): Int32 + public func store(val: Int32): Unit + public func store(val: Int32, memoryOrder!: MemoryOrder): Unit + public func swap(val: Int32): Int32 + public func swap(val: Int32, memoryOrder!: MemoryOrder): Int32 +} + +public class AtomicInt64 { + public init(val: Int64) + public func compareAndSwap(old: Int64, new: Int64): Bool + public func compareAndSwap(old: Int64, new: Int64, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: Int64): Int64 + public func fetchAdd(val: Int64, memoryOrder!: MemoryOrder): Int64 + public func fetchAnd(val: Int64): Int64 + public func fetchAnd(val: Int64, memoryOrder!: MemoryOrder): Int64 + public func fetchOr(val: Int64): Int64 + public func fetchOr(val: Int64, memoryOrder!: MemoryOrder): Int64 + public func fetchSub(val: Int64): Int64 + public func fetchSub(val: Int64, memoryOrder!: MemoryOrder): Int64 + public func fetchXor(val: Int64): Int64 + public func fetchXor(val: Int64, memoryOrder!: MemoryOrder): Int64 + public func load(): Int64 + public func load(memoryOrder!: MemoryOrder): Int64 + public func store(val: Int64): Unit + public func store(val: Int64, memoryOrder!: MemoryOrder): Unit + public func swap(val: Int64): Int64 + public func swap(val: Int64, memoryOrder!: MemoryOrder): Int64 +} + +public class AtomicInt8 { + public init(val: Int8) + public func compareAndSwap(old: Int8, new: Int8): Bool + public func compareAndSwap(old: Int8, new: Int8, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: Int8): Int8 + public func fetchAdd(val: Int8, memoryOrder!: MemoryOrder): Int8 + public func fetchAnd(val: Int8): Int8 + public func fetchAnd(val: Int8, memoryOrder!: MemoryOrder): Int8 + public func fetchOr(val: Int8): Int8 + public func fetchOr(val: Int8, memoryOrder!: MemoryOrder): Int8 + public func fetchSub(val: Int8): Int8 + public func fetchSub(val: Int8, memoryOrder!: MemoryOrder): Int8 + public func fetchXor(val: Int8): Int8 + public func fetchXor(val: Int8, memoryOrder!: MemoryOrder): Int8 + public func load(): Int8 + public func load(memoryOrder!: MemoryOrder): Int8 + public func store(val: Int8): Unit + public func store(val: Int8, memoryOrder!: MemoryOrder): Unit + public func swap(val: Int8): Int8 + public func swap(val: Int8, memoryOrder!: MemoryOrder): Int8 +} + +public class AtomicOptionReference where T <: Object { + public init() + public init(val: Option) + public func compareAndSwap(old: Option, new: Option): Bool + public func compareAndSwap(old: Option, new: Option, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func load(): Option + public func load(memoryOrder!: MemoryOrder): Option + public func store(val: Option): Unit + public func store(val: Option, memoryOrder!: MemoryOrder): Unit + public func swap(val: Option): Option + public func swap(val: Option, memoryOrder!: MemoryOrder): Option +} + +public class AtomicReference where T <: Object { + public init(val: T) + public func compareAndSwap(old: T, new: T): Bool + public func compareAndSwap(old: T, new: T, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func load(): T + public func load(memoryOrder!: MemoryOrder): T + public func store(val: T): Unit + public func store(val: T, memoryOrder!: MemoryOrder): Unit + public func swap(val: T): T + public func swap(val: T, memoryOrder!: MemoryOrder): T +} + +public class AtomicUInt16 { + public init(val: UInt16) + public func compareAndSwap(old: UInt16, new: UInt16): Bool + public func compareAndSwap(old: UInt16, new: UInt16, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: UInt16): UInt16 + public func fetchAdd(val: UInt16, memoryOrder!: MemoryOrder): UInt16 + public func fetchAnd(val: UInt16): UInt16 + public func fetchAnd(val: UInt16, memoryOrder!: MemoryOrder): UInt16 + public func fetchOr(val: UInt16): UInt16 + public func fetchOr(val: UInt16, memoryOrder!: MemoryOrder): UInt16 + public func fetchSub(val: UInt16): UInt16 + public func fetchSub(val: UInt16, memoryOrder!: MemoryOrder): UInt16 + public func fetchXor(val: UInt16): UInt16 + public func fetchXor(val: UInt16, memoryOrder!: MemoryOrder): UInt16 + public func load(): UInt16 + public func load(memoryOrder!: MemoryOrder): UInt16 + public func store(val: UInt16): Unit + public func store(val: UInt16, memoryOrder!: MemoryOrder): Unit + public func swap(val: UInt16): UInt16 + public func swap(val: UInt16, memoryOrder!: MemoryOrder): UInt16 +} + +public class AtomicUInt32 { + public init(val: UInt32) + public func compareAndSwap(old: UInt32, new: UInt32): Bool + public func compareAndSwap(old: UInt32, new: UInt32, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: UInt32): UInt32 + public func fetchAdd(val: UInt32, memoryOrder!: MemoryOrder): UInt32 + public func fetchAnd(val: UInt32): UInt32 + public func fetchAnd(val: UInt32, memoryOrder!: MemoryOrder): UInt32 + public func fetchOr(val: UInt32): UInt32 + public func fetchOr(val: UInt32, memoryOrder!: MemoryOrder): UInt32 + public func fetchSub(val: UInt32): UInt32 + public func fetchSub(val: UInt32, memoryOrder!: MemoryOrder): UInt32 + public func fetchXor(val: UInt32): UInt32 + public func fetchXor(val: UInt32, memoryOrder!: MemoryOrder): UInt32 + public func load(): UInt32 + public func load(memoryOrder!: MemoryOrder): UInt32 + public func store(val: UInt32): Unit + public func store(val: UInt32, memoryOrder!: MemoryOrder): Unit + public func swap(val: UInt32): UInt32 + public func swap(val: UInt32, memoryOrder!: MemoryOrder): UInt32 +} + +public class AtomicUInt64 { + public init(val: UInt64) + public func compareAndSwap(old: UInt64, new: UInt64): Bool + public func compareAndSwap(old: UInt64, new: UInt64, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: UInt64): UInt64 + public func fetchAdd(val: UInt64, memoryOrder!: MemoryOrder): UInt64 + public func fetchAnd(val: UInt64): UInt64 + public func fetchAnd(val: UInt64, memoryOrder!: MemoryOrder): UInt64 + public func fetchOr(val: UInt64): UInt64 + public func fetchOr(val: UInt64, memoryOrder!: MemoryOrder): UInt64 + public func fetchSub(val: UInt64): UInt64 + public func fetchSub(val: UInt64, memoryOrder!: MemoryOrder): UInt64 + public func fetchXor(val: UInt64): UInt64 + public func fetchXor(val: UInt64, memoryOrder!: MemoryOrder): UInt64 + public func load(): UInt64 + public func load(memoryOrder!: MemoryOrder): UInt64 + public func store(val: UInt64): Unit + public func store(val: UInt64, memoryOrder!: MemoryOrder): Unit + public func swap(val: UInt64): UInt64 + public func swap(val: UInt64, memoryOrder!: MemoryOrder): UInt64 +} + +public class AtomicUInt8 { + public init(val: UInt8) + public func compareAndSwap(old: UInt8, new: UInt8): Bool + public func compareAndSwap(old: UInt8, new: UInt8, successOrder!: MemoryOrder, failureOrder!: MemoryOrder): Bool + public func fetchAdd(val: UInt8): UInt8 + public func fetchAdd(val: UInt8, memoryOrder!: MemoryOrder): UInt8 + public func fetchAnd(val: UInt8): UInt8 + public func fetchAnd(val: UInt8, memoryOrder!: MemoryOrder): UInt8 + public func fetchOr(val: UInt8): UInt8 + public func fetchOr(val: UInt8, memoryOrder!: MemoryOrder): UInt8 + public func fetchSub(val: UInt8): UInt8 + public func fetchSub(val: UInt8, memoryOrder!: MemoryOrder): UInt8 + public func fetchXor(val: UInt8): UInt8 + public func fetchXor(val: UInt8, memoryOrder!: MemoryOrder): UInt8 + public func load(): UInt8 + public func load(memoryOrder!: MemoryOrder): UInt8 + public func store(val: UInt8): Unit + public func store(val: UInt8, memoryOrder!: MemoryOrder): Unit + public func swap(val: UInt8): UInt8 + public func swap(val: UInt8, memoryOrder!: MemoryOrder): UInt8 +} + +public class Barrier { + public init(count: Int64) + public func wait(timeout!: Duration = Duration.Max): Unit +} + +public class Monitor <: ReentrantMutex { + public init() + public func notify(): Unit + public func notifyAll(): Unit + public func wait(timeout!: Duration = Duration.Max): Bool +} + +public class MultiConditionMonitor <: ReentrantMutex { + public init() + public func newCondition(): ConditionID + public func notify(condID: ConditionID): Unit + public func notifyAll(condID: ConditionID): Unit + public func wait(condID: ConditionID, timeout!: Duration = Duration.Max): Bool +} + +public open class ReentrantMutex <: IReentrantMutex { + public init() + public open func lock(): Unit + public open func tryLock(): Bool + public open func unlock(): Unit +} + +public class ReentrantReadMutex <: ReentrantMutex { + public func lock(): Unit + public func tryLock(): Bool + public func unlock(): Unit +} + +public class ReentrantReadWriteMutex { + public prop readMutex: ReentrantReadMutex + public prop writeMutex: ReentrantWriteMutex + public init(mode!: ReadWriteMutexMode = ReadWriteMutexMode.Unfair) +} + +public class ReentrantWriteMutex <: ReentrantMutex { + public func lock(): Unit + public func tryLock(): Bool + public func unlock(): Unit +} + +public class Semaphore { + public prop count: Int64 + public init(count: Int64) + public func acquire(amount!: Int64 = 1): Unit + public func release(amount!: Int64 = 1): Unit + public func tryAcquire(amount!: Int64 = 1): Bool +} + +public class SyncCounter { + public prop count: Int64 + public init(count: Int64) + public func dec(): Unit + public func waitUntilZero(timeout!: Duration = Duration.Max): Unit +} + +public class Timer <: Equatable & Hashable { + public static func after(delay: Duration, task: () -> Option): Timer + public static func once(delay: Duration, task: ()->Unit): Timer + public static func repeat(delay: Duration, interval: Duration, task: ()->Unit, style!: CatchupStyle = Burst): Timer + public static func repeatDuring(period: Duration, delay: Duration, interval: Duration, task: () -> Unit, style!: CatchupStyle = Burst): Timer + public static func repeatTimes(count: Int64, delay: Duration, interval: Duration, task: () -> Unit, style!: CatchupStyle = Burst): Timer + public func cancel(): Unit + public func hashCode(): Int64 + public operator func !=(rhs: Timer): Bool + public operator func ==(rhs: Timer): Bool +} + + +// --------------------------- +// -----vars +// --------------------------- +public let DefaultMemoryOrder: MemoryOrder = MemoryOrder.SeqCst {} + + +// --------------------------- +// -----enums +// --------------------------- +public enum CatchupStyle { + Burst + Delay + Skip +} + +public enum MemoryOrder { + SeqCst +} + +public enum ReadWriteMutexMode { + Fair + Unfair +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class IllegalSynchronizationStateException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----funcs +// --------------------------- +public func sleep(dur: Duration): Unit + +// --------------------------- +// -----interfaces +// --------------------------- +public interface IReentrantMutex { + func lock(): Unit + func tryLock(): Bool + func unlock(): Unit +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct ConditionID {} + + diff --git a/cangjie_libs/std/time.cjd b/cangjie_libs/std/time.cjd new file mode 100644 index 0000000000000000000000000000000000000000..f087a0a3ebbb8adb4c444237aa65195619dd4bfc --- /dev/null +++ b/cangjie_libs/std/time.cjd @@ -0,0 +1,210 @@ +package std.time + +// --------------------------- +// -----classes +// --------------------------- +public class DateTimeFormat { + public static prop RFC1123: DateTimeFormat + public static prop RFC3339: DateTimeFormat + public prop format: String + public static func of(format: String): DateTimeFormat +} + +public class TimeZone <: ToString & Equatable { + public static let Local: TimeZone + public static let UTC: TimeZone + public prop id: String + public init(id: String, offset: Duration) + public static func load(id: String): TimeZone + public static func loadFromPaths(id: String, tzpaths: Array): TimeZone + public static func loadFromTZData(id: String, data: Array): TimeZone + public func toString(): String + public operator func !=(r: TimeZone): Bool + public operator func ==(r: TimeZone): Bool +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum DayOfWeek <: ToString { + Friday + Monday + Saturday + Sunday + Thursday + Tuesday + Wednesday + public static func of(dayOfWeek: Int64): DayOfWeek + public func toString(): String + public func value(): Int64 + public operator func !=(r: DayOfWeek): Bool + public operator func ==(r: DayOfWeek): Bool +} + +public enum Month <: ToString { + April + August + December + February + January + July + June + March + May + November + October + September + public static func of(mon: Int64): Month + public func toString(): String + public func value(): Int64 + public operator func !=(r: Month): Bool + public operator func +(n: Int64): Month + public operator func -(n: Int64): Month + public operator func ==(r: Month): Bool +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class InvalidDataException <: Exception { + public init() + public init(message: String) +} + +public class TimeParseException <: Exception { + public init() + public init(message: String) +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface DurationExtension { + operator func *(r: Duration): Duration +} + +extend Float64 <: DurationExtension { + public operator func *(r: Duration): Duration +} + +extend Int64 <: DurationExtension { + public operator func *(r: Duration): Duration +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct DateTime <: ToString & Hashable & Comparable { + public static prop UnixEpoch: DateTime + public prop dayOfMonth: Int64 + public prop dayOfWeek: DayOfWeek + public prop dayOfYear: Int64 + public prop hour: Int64 + public prop isoWeek: (Int64, Int64) + public prop minute: Int64 + public prop month: Month + public prop monthValue: Int64 + public prop nanosecond: Int64 + public prop second: Int64 + public prop year: Int64 + public prop zone: TimeZone + public prop zoneId: String + public prop zoneOffset: Duration + public static func fromUnixTimeStamp(d: Duration): DateTime + public static func now(timeZone!: TimeZone = TimeZone.Local): DateTime + public static func nowUTC(): DateTime + public static func of( year!: Int64, month!: Int64, dayOfMonth!: Int64, hour!: Int64 = 0, minute!: Int64 = 0, second!: Int64 = 0, nanosecond!: Int64 = 0, timeZone!: TimeZone = TimeZone.Local): DateTime + public static func of( year!: Int64, month!: Month, dayOfMonth!: Int64, hour!: Int64 = 0, minute!: Int64 = 0, second!: Int64 = 0, nanosecond!: Int64 = 0, timeZone!: TimeZone = TimeZone.Local): DateTime + public static func ofEpoch(second!: Int64, nanosecond!: Int64): DateTime + public static func ofUTC( year!: Int64, month!: Int64, dayOfMonth!: Int64, hour!: Int64 = 0, minute!: Int64 = 0, second!: Int64 = 0, nanosecond!: Int64 = 0): DateTime + public static func ofUTC( year!: Int64, month!: Month, dayOfMonth!: Int64, hour!: Int64 = 0, minute!: Int64 = 0, second!: Int64 = 0, nanosecond!: Int64 = 0): DateTime + public static func parse(str: String): DateTime + public static func parse(str: String, format: String): DateTime + public static func parse(str: String, format: DateTimeFormat): DateTime + public func addDays(n: Int64): DateTime + public func addHours(n: Int64): DateTime + public func addMinutes(n: Int64): DateTime + public func addMonths(n: Int64): DateTime + public func addNanoseconds(n: Int64): DateTime + public func addSeconds(n: Int64): DateTime + public func addWeeks(n: Int64): DateTime + public func addYears(n: Int64): DateTime + public func compare(rhs: DateTime): Ordering + public func hashCode(): Int64 + public func inLocal(): DateTime + public func inTimeZone(timeZone: TimeZone): DateTime + public func inUTC(): DateTime + public func toString(): String + public func toString(format: String): String + public func toString(format: DateTimeFormat): String + public func toUnixTimeStamp(): Duration + public operator func !=(r: DateTime): Bool + public operator func +(r: Duration): DateTime + public operator func -(r: DateTime): Duration + public operator func -(r: Duration): DateTime + public operator func <(r: DateTime): Bool + public operator func <=(r: DateTime): Bool + public operator func ==(r: DateTime): Bool + public operator func >(r: DateTime): Bool + public operator func >=(r: DateTime): Bool +} + +public struct Duration <: ToString & Hashable & Comparable { + public static prop Max: Duration + public static prop Min: Duration + public static prop Zero: Duration + public static prop day: Duration + public static prop hour: Duration + public static prop microsecond: Duration + public static prop millisecond: Duration + public static prop minute: Duration + public static prop nanosecond: Duration + public static prop second: Duration + public static func since(t: DateTime): Duration + public static func until(t: DateTime): Duration + public func abs(): Duration + public func compare(rhs: Duration): Ordering + public func hashCode(): Int64 + public func toDays(): Int64 + public func toHours(): Int64 + public func toMicroseconds(): Int64 + public func toMilliseconds(): Int64 + public func toMinutes(): Int64 + public func toNanoseconds(): Int64 + public func toSeconds(): Int64 + public func toString(): String + public operator func !=(r: Duration): Bool + public operator func *(r: Float64): Duration + public operator func *(r: Int64): Duration + public operator func +(r: Duration): Duration + public operator func -(r: Duration): Duration + public operator func /(r: Duration): Float64 + public operator func /(r: Float64): Duration + public operator func /(r: Int64): Duration + public operator func <(r: Duration): Bool + public operator func <=(r: Duration): Bool + public operator func ==(r: Duration): Bool + public operator func >(r: Duration): Bool + public operator func >=(r: Duration): Bool +} + +public struct MonoTime <: Hashable & Comparable { + public static func now(): MonoTime + public func compare(rhs: MonoTime): Ordering + public func hashCode(): Int64 + public operator func !=(r: MonoTime): Bool + public operator func +(r: Duration): MonoTime + public operator func -(r: Duration): MonoTime + public operator func -(r: MonoTime): Duration + public operator func <(r: MonoTime): Bool + public operator func <=(r: MonoTime): Bool + public operator func ==(r: MonoTime): Bool + public operator func >(r: MonoTime): Bool + public operator func >=(r: MonoTime): Bool +} + + diff --git a/cangjie_libs/std/unicode.cjd b/cangjie_libs/std/unicode.cjd new file mode 100644 index 0000000000000000000000000000000000000000..36fbe36731dfb1b808f55de3a5e60b66bc4b52bf --- /dev/null +++ b/cangjie_libs/std/unicode.cjd @@ -0,0 +1,46 @@ +package std.unicode + +// --------------------------- +// -----interfaces +// --------------------------- +public interface UnicodeExtension {} + +extend Rune <: UnicodeExtension { + public func isLetter(): Bool + import std.unicode.*main(): Unit { println('a'.isLetter()) println('1'.isLetter())} + public func isLowerCase(): Bool + import std.unicode.*main(): Unit { println('a'.isLowerCase()) println('A'.isLowerCase())} + public func isNumber(): Bool + import std.unicode.*main(): Unit { println('a'.isNumber()) println('1'.isNumber())} + public func isTitleCase(): Bool + import std.unicode.*main(): Unit { println('Dž'.isTitleCase())} + public func isUpperCase(): Bool + import std.unicode.*main(): Unit { println('a'.isUpperCase()) println('A'.isUpperCase())} + public func isWhiteSpace(): Bool + import std.unicode.*main(): Unit { println(' '.isWhiteSpace())} + public func toLowerCase(): Rune + import std.unicode.*main(): Unit { println('A'.toLowerCase())} + public func toTitleCase(): Rune + import std.unicode.*main(): Unit { println('a'.toTitleCase())} + public func toUpperCase(): Rune + import std.unicode.*main(): Unit { println('a'.toUpperCase())} +} + +extend String <: UnicodeExtension { + public func isBlank(): Bool + import std.unicode.*main(): Unit { println(" \t\n\r".isBlank())} + public func toLower(): String + import std.unicode.*main(): Unit { println("AbcDEF".toLower())} + public func toTitle(): String + import std.unicode.*main(): Unit { println("AbcDEF".toTitle())} + public func toUpper(): String + import std.unicode.*main(): Unit { println("AbcDEF".toUpper())} + public func trim(): String + import std.unicode.*main(): Unit { println("\nx \t ".trim())} + public func trimLeft(): String + import std.unicode.*main(): Unit { println(" x ".trimLeft())} + public func trimRight(): String + import std.unicode.*main(): Unit { println(" x ".trimRight())} +} + + diff --git a/cangjie_libs/std/unittest.cjd b/cangjie_libs/std/unittest.cjd new file mode 100644 index 0000000000000000000000000000000000000000..926117f573e1f9623256bdf458595713c10ab0e1 --- /dev/null +++ b/cangjie_libs/std/unittest.cjd @@ -0,0 +1,348 @@ +package std.unittest + +// --------------------------- +// -----classes +// --------------------------- +public class Benchmark { + public func run(): BenchReport + public static func create(name: String, configuration!: Configuration = Configuration(), body!: () -> Unit): Benchmark + public static func createParameterized(name: String, strategy: DataStrategy, configuration!: Configuration = Configuration(), body!: (T) -> Unit): Benchmark + public static func createParameterized(name: String, strategy: DataStrategyProcessor, configuration!: Configuration = Configuration(), body!: (T) -> Unit): Benchmark + public prop name: String +} + +public class BenchReport <: Report { + public func reportTo(reporter: Reporter): T +} + +public class CartesianProductProcessor <: DataStrategyProcessor<(T0,T1)> { + public CartesianProductProcessor(let left: DataStrategyProcessor, let right: DataStrategyProcessor) +} + +public class ConsoleReporter <: Reporter & Reporter { + public ConsoleReporter(let colored!: Bool = true) +} + +public class TextReporter <: Reporter & Reporter + where PP <: PrettyPrinter { + public TextReporter(let into!: PP) +} + +public class CsvReporter <: Reporter { + public CsvReporter(let directory: Directory) +} + +public class CsvRawReporter <: Reporter { + public CsvRawReporter(let directory: Directory) +} + +public class CsvStrategy <: DataStrategy where T <: Serializable { + public override func provider(configuration: Configuration): SerializableProvider +} + +abstract sealed class DataStrategyProcessor { + protected prop isInfinite: Bool + public func intoBenchmark( caseName!: String, configuration!: Configuration, doRun!: (T, Int64, Int64) -> Float64): Benchmark + public func intoUnitTestCase( caseName!: String, configuration!: Configuration, doRun!: (T) -> Unit): UnitTestCase + protected func lastItemInfo(): Array + protected func lastItem(configuration: Configuration): T + protected func provide(configuration: Configuration): Iterable + protected func shrinkLastItem(configuration: Configuration, engine: LazyCyclicNode): Iterable + public static func start(s: DataStrategy, name: String): SimpleProcessor + public static func start(f: () -> DataStrategy, name: String): DataStrategyProcessor where U <: BenchInputProvider < T > + public static func start(f: () -> DataStrategy, name: String, x!: Int64 = 0): SimpleProcessor + public static func start(f: () -> DataStrategyProcessor, name: String): DataStrategyProcessor + public static func start(f: () -> DataStrategyProcessor, name: String, x!: Int64 = 0): DataStrategyProcessor where U <: BenchInputProvider +} + +extend DataStrategyProcessor { + public func map(f: (T) -> R): MapProcessor + public func mapWithConfig(f: (T, Configuration) -> R): MapProcessor + public func flatMap(f: (T) -> DataProvider): FlatMapProcessor + public func flatMapStrategy(f: (T) -> DataStrategy): FlatMapStrategyProcessor + public func product(p: DataStrategyProcessor): CartesianProductProcessor +} + +public class FlatMapProcessor <: DataStrategyProcessor {} + +public class FlatMapStrategyProcessor <: DataStrategyProcessor {} + +public class InputParameter {} + +public class JsonStrategy <: DataStrategy where T <: Serializable { + public override func provider(configuration: Configuration): SerializableProvider +} + +public open class LazyCyclicNode { + protected open func advance(): ?Unit + protected open func recover(): Unit +} + +public class MapProcessor <: DataStrategyProcessor {} + +public class PowerAssertDiagramBuilder { + public init(expression: String, initialPosition: Int64) + public func r(value: T, exprAsText: String, position: Int64): T + public func r(value: String, exprAsText: String, position: Int64): String + public func h(exception: Exception, exprAsText: String, position: Int64): Nothing + public func w(passed: Bool): Unit +} + +public class RandomDataProvider <: DataProvider where T <: Arbitrary { + public override prop isInfinite: Bool + public RandomDataProvider(private let configuration: Configuration) + public override func provide(): Iterable +} + +public class RandomDataShrinker <: DataShrinker { + public override func shrink(value: T): Iterable +} + +public class RandomDataStrategy <: DataStrategy where T <: Arbitrary { + public override func provider(configuration: Configuration): RandomDataProvider + public override func shrinker(_: Configuration): RandomDataShrinker +} + +sealed abstract class Report { + public prop errorCount: Int64 + public prop caseCount: Int64 + public prop passedCount: Int64 + public prop failedCount: Int64 + public prop skippedCount: Int64 +} + +public class RawStatsReporter <: Reporter> { + public RawStatsReporter() +} + +public class SerializableProvider <: DataProvider where T <: Serializable { + public override func provide(): Iterable + public prop isInfinite: Bool +} + +public class SimpleProcessor <: DataStrategyProcessor { + public SimpleProcessor(let buildDelegate:() -> DataStrategy, let name: String) +} + +public class TestGroup { + public func runBenchmarks(): BenchReport + public func runBenchmarks(Configuration): BenchReport + public func runTests(): TestReport + public func runTests(configuration: Configuration): TestReport + public static func builder(name: String): TestGroupBuilder + public static func builder(group: TestGroup): TestGroupBuilder + public prop name: String +} + +public class TestGroupBuilder { + public func add(benchmark: Benchmark): TestGroupBuilder + public func add(suite: TestSuite): TestGroupBuilder + public func add(test: UnitTestCase): TestGroupBuilder + public func build(): TestGroup + public func configure(configuration: Configuration): TestGroupBuilder + public func setName(name: String): TestGroupBuilder +} + +public class TestPackage { + public TestPackage(let name: String) + public func registerCase(testCase: () -> UnitTestCase): Unit + public func registerSuite(suite: () -> TestSuite): Unit + public func registerBench(bench: () -> Benchmark): Unit +} + +public class TestReport <: Report { + public func reportTo(reporter: Reporter): T +} + +public class TestSuite { + public func runBenchmarks(): BenchReport + public func runBenchmarks(configuration: Configuration): BenchReport + public func runTests(): TestReport + public func runTests(configuration: Configuration): TestReport + public static func builder(name: String): TestSuiteBuilder + public static func builder(suite: TestSuite): TestSuiteBuilder + public prop name: String +} + +public class TestSuiteBuilder { + public func add(benchmark: Benchmark): TestSuiteBuilder + public func add(test: UnitTestCase): TestSuiteBuilder + public func afterAll(body: () -> Unit): TestSuiteBuilder + public func afterEach(body: () -> Unit): TestSuiteBuilder + public func afterEach(body: (String) -> Unit): TestSuiteBuilder + public func beforeAll(body: () -> Unit): TestSuiteBuilder + public func beforeEach(body: () -> Unit): TestSuiteBuilder + public func beforeEach(body: (String) -> Unit): TestSuiteBuilder + public func build(): TestSuite + public func configure(configuration: Configuration): TestSuiteBuilder + public func setName(name: String): TestSuiteBuilder +} + +public class UnitTestCase { + public func run(): TestReport + public static func create(name: String, configuration!: Configuration = Configuration(), body!: () -> Unit): UnitTestCase + public static func createParameterized(name: String, strategy: DataStrategy, configuration!: Configuration = Configuration(), body!: (T) -> Unit): UnitTestCase + public static func createParameterized(name: String, strategy: DataStrategyProcessor, configuration!: Configuration = Configuration(), body!: (T) -> Unit): UnitTestCase + public prop name: String +} + +public class XmlReporter <: Reporter { + public XmlReporter(let directory: Directory) +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum ExplicitGcType <: ToString { + Disabled + Heavy + Light + public override func toString(): String +} + +public enum TimeUnit { + Micros + Millis + Nanos + Seconds +} + + +// --------------------------- +// -----exceptions +// --------------------------- +public class AssertException <: Exception { + public init(message: String) + public init(message: String) +} + +public class AssertIntermediateException <: Exception { + public let expression: String + public let originalException: Exception + public let position: Int64 + public func getOriginalStackTrace(): String +} + +public class UnittestCliOptionsFormatException <: UnittestException {} + +public open class UnittestException <: Exception {} + + +// --------------------------- +// -----functions +// --------------------------- +public func assertCaughtUnexpectedE( + message: String, + expectedExceptions: String, + caughtException: String +): Nothing +public func assertEqual(leftStr: String, rightStr: String, expected: T, actual: T): Unit where T <: Equatable +public func csv( + fileName: String, + delimiter!: Rune = ',', +    quoteChar!: Rune = '"', +    escapeChar!: Rune = '"', +    commentChar!: Option = None, +    header!: Option> = None, +    skipRows!: Array = [], +    skipColumns!: Array = [], +    skipEmptyLines!: Bool = false +): CsvStrategy where T <: Serializable +public func defaultConfiguration(): Configuration +public func entryMain(testPackage: TestPackage): Int64 +public func expectCaughtUnexpectedE( + message: String, + expectedExceptions: String, + caughtException: String +): Unit +public func expectEqual(leftStr: String, rightStr: String, expected: T, actual: T): Unit where T <: Equatable +public func fail(message: String): Nothing +public func failExpect(message: String): Unit +public func json(fileName: String): JsonStrategy where T <: Serializable { + @Test[user in json("users.json")]func test_user_age(user: User): Unit { @Expect(user.age, 100)} + class User <: Serializable { User(let age: Int64) {} public func serialize(): DataModel { DataModelStruct() .add(Field("age", DataModelInt(age))) } public static func deserialize(dm: DataModel): User { if (let Some(dms) <- dm as DataModelStruct) { if (let Some(age) <- dms.get("age") as DataModelInt) { return User(age.getValue()) } } throw Exception("Can't deserialize user.") }} + @Test[user in json("numbers.json")]func test(value: Int64) + @Test[user in json("names.json")]func test(name: String) +} + +public func tsv( + fileName: String, +    quoteChar!: Rune = '"', +    escapeChar!: Rune = '"', +    commentChar!: Option = None, +    header!: Option> = None, +    skipRows!: Array = [], +    skipColumns!: Array = [], +    skipEmptyLines!: Bool = false +): CsvStrategy where T <: Serializable { + import serialization.serialization.* import std.convert.* import std.unittest.* import std.unittest.testmacro.* public class User <: Serializable { public User(let name: String, let age: UInt32) {} public func serialize(): DataModel { let dms = DataModelStruct() dms.add(Field("username", DataModelString(name))) dms.add(Field("age", DataModelString(age.toString()))) return dms } static public func deserialize(dm: DataModel): User { var data: DataModelStruct = match (dm) { case dms: DataModelStruct => dms case _ => throw DataModelException("this data is not DataModelStruct") } let name = String.deserialize(data.get("username")) let age = String.deserialize(data.get("age")) return User(name, UInt32.parse(age)) } } @Test[user in csv("testdata.csv")] func testUser(user: User) { @Assert(user.name == "Alex Great" || user.name == "Donald Sweet") @Assert(user.age == 21 || user.age == 28) } +} + + +// --------------------------- +// -----interfaces +// --------------------------- +public interface BenchInputProvider <: BenchmarkInputMarker { + mut func get(idx: Int64): T + mut func reset(max: Int64) +} + +public interface BenchmarkConfig {} + +public interface BenchmarkInputMarker {} + +public interface Generator { + func next(): T +} + +public interface Measurement { + func measure(f: () -> Unit): Float64 + func measureIntermediate(): Float64 + func toString(f: Float64): String +} + +sealed interface Reporter {} + +public interface TestClass { + func asTestSuite(): TestSuite +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct BatchInputProvider <: BenchInputProvider { + public BatchInputProvider(let builder: () -> T) + public mut func get(idx: Int64): T + public mut func reset(max: Int64) +} + +public struct BatchSizeOneInputProvider <: BenchInputProvider { + public BatchSizeOneInputProvider(let builder: () -> T) + public mut func get(idx: Int64): T + public mut func reset(max: Int64) +} + +public struct GenerateEachInputProvider <: BenchInputProvider { + public GenerateEachInputProvider(let builder: () -> T) + public mut func get(idx: Int64): T + public mut func reset(max: Int64) +} + +public struct ImmutableInputProvider <: BenchInputProvider { + public ImmutableInputProvider(let data: T) + public mut func get(idx: Int64): T + public static func createOrExisting(arg: T, x!:Int64=0): ImmutableInputProvider + public static func createOrExisting(arg: U): U where U <: BenchInputProvider +} + +public struct TimeNow <: Measurement { + public init() + public init(unit: ?TimeUnit) + public func measure(f: () -> Unit): Float64 + public func measureIntermediate(): Float64 + public func toString(duration: Float64): String +} + + diff --git a/cangjie_libs/std/unittest.common.cjd b/cangjie_libs/std/unittest.common.cjd new file mode 100644 index 0000000000000000000000000000000000000000..da618d025c25e82d2bc47279ebf0f85815b339a4 --- /dev/null +++ b/cangjie_libs/std/unittest.common.cjd @@ -0,0 +1,136 @@ +package std.unittest.common + +// --------------------------- +// -----classes +// --------------------------- +public class Configuration <: ToString { + public init() + public func clone(): Configuration + public func get(key: String): ?T + public func remove(key: String): ?T + public func set(key: String, value: T) + public func toString(): String + public static func merge(parent: Configuration, child: Configuration): Configuration +} + +extend Configuration <: BenchmarkConfig { + public func batchSize(b: Int64) + public func batchSize(x: Range) + public func explicitGC(x: ExplicitGcType) + public func minBatches(x: Int64) + public func minDuration(x: Duration) + public func warmup(x: Int64) + public func warmup(x: Duration) +} + +abstract sealed class ConfigurationKey <: Equatable & Hashable { + protected func equals(that: ConfigurationKey): Bool + public override func hashCode(): Int64 + public override operator func ==(that: ConfigurationKey) + public override operator func !=(that: ConfigurationKey) +} + +public abstract class PrettyPrinter { + public PrettyPrinter(let indentationSize!: UInt64 = 4, let startingIndent!: UInt64 = 0) + public func append(text: String): PrettyPrinter + public func append(value: PP): PrettyPrinter where PP <: PrettyPrintable + public func appendCentered(text: String, space: UInt64): PrettyPrinter + public func appendLeftAligned(text: String, space: UInt64): PrettyPrinter + public func appendLine(text: String): PrettyPrinter + public func appendLine(value: PP): PrettyPrinter where PP <: PrettyPrintable + public func appendRightAligned(text: String, space: UInt64): PrettyPrinter + public func colored(color: Color, body: () -> Unit): PrettyPrinter + pp.colored(RED) { pp.appendLine("1") pp.appendLine("2") pp.appendLine("3")} + public func colored(color: Color, text: String): PrettyPrinter + public func customOffset(symbols: UInt64, body: () -> Unit): PrettyPrinter + pp.customOffset(5) { pp.appendLine("1") pp.appendLine("2") pp.appendLine("3")} + public func indent(body: () -> Unit): PrettyPrinter + pp.indent { pp.appendLine("1") pp.appendLine("2") pp.appendLine("3")} + public func indent(indents: UInt64, body: () -> Unit): PrettyPrinter + pp.indent(2) { pp.appendLine("1") pp.appendLine("2") pp.appendLine("3")} + public func newLine(): PrettyPrinter + protected func put(s: String): Unit + protected open func putNewLine(): Unit + protected func setColor(color: Color): Unit + public prop isTopLevel: Bool +} + +public class PrettyText <: PrettyPrinter & PrettyPrintable & ToString { + public init() + public init(string: String) + public func isEmpty(): Bool + public func pprint(to: PrettyPrinter): PrettyPrinter + public func toString(): String + public static func of(pp: PP) where PP <: PrettyPrintable +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum Color <: Equatable { + RED + GREEN + YELLOW + BLUE + CYAN + MAGENTA + GRAY + DEFAULT_COLOR + public operator func ==(that: Color): Bool + public operator func !=(that: Color): Bool +} + + +// --------------------------- +// -----functions +// --------------------------- +public func toStringOrPlaceholder(value: T) + +// --------------------------- +// -----interfaces +// --------------------------- +public interface DataProvider { + prop isInfinite: Bool + func provide(): Iterable + func positions(): Array +} + +extend Array <: DataProvider { + @Test[x in [1,2,3]]func test(x: Int64) {} +} + +extend Range <: DataProvider { + @Test[x in (0..5)]func test(x: Int64) {} +} + +public interface DataShrinker { + func shrink(value: T): Iterable +} + +public interface DataStrategy { + func provider(configuration: Configuration): DataProvider + open func shrinker(configuration: Configuration): DataShrinker +} + +extend Array <: DataStrategy { + @Test[x in [1,2,3]]func test(x: Int64) {} +} + +extend Range <: DataStrategy { + @Test[x in (0..5)]func test(x: Int64) {} +} + +public interface PrettyPrintable { + func pprint(to: PrettyPrinter): PrettyPrinter +} + +extend Array <: PrettyPrintable where T <: PrettyPrintable { + public func pprint(to: PrettyPrinter): PrettyPrinter +} + +extend ArrayList <: PrettyPrintable where T <: PrettyPrintable { + public func pprint(to: PrettyPrinter): PrettyPrinter +} + + diff --git a/cangjie_libs/std/unittest.diff.cjd b/cangjie_libs/std/unittest.diff.cjd new file mode 100644 index 0000000000000000000000000000000000000000..9eb53b87d834524edc586dcc5089983dd249a8f9 --- /dev/null +++ b/cangjie_libs/std/unittest.diff.cjd @@ -0,0 +1,11 @@ +package std.unittest.diff + +// --------------------------- +// -----interfaces +// --------------------------- +public interface AssertPrintable { + func pprintForAssertion( pp: PrettyPrinter, that: T, thisPrefix: String, thatPrefix: String, level: Int64): PrettyPrinter + prop hasNestedDiff: Bool +} + + diff --git a/cangjie_libs/std/unittest.mock.cjd b/cangjie_libs/std/unittest.mock.cjd new file mode 100644 index 0000000000000000000000000000000000000000..d1d077c7be96477d909a44124c0857c72d5b8bd5 --- /dev/null +++ b/cangjie_libs/std/unittest.mock.cjd @@ -0,0 +1,206 @@ +package std.unittest.mock + +// --------------------------- +// -----classes +// --------------------------- +public sealed abstract class ActionSelector { + func fails(): Unit +} + +public class AnyMatcher <: ArgumentMatcher { + public func matchesAny(_: Any) +} + +extend AnyMatcher { + public func value(): T +} + +public abstract class ArgumentMatcher { + public func withDescription(description: String): ArgumentMatcher + public func forParameter(name: String): ArgumentMatcher + public func matchesAny(arg: Any) +} + +public class CardinalitySelector where A <: ActionSelector { + func anyTimes(): Unit + func atLeastOnce(): Unit + func atLeastTimes(minTimesExpected: Int64): Unit + func once(): Continuation + func times(expectedTimes: Int64): Continuation + func times(min!: Int64, max!: Int64): Unit +} + +public class ConfigureMock { + public static func stubGetter( stubCall: () -> TRet, objectReference: TObj, objectName: String, fieldOrPropertyName: String, callDescription: String, lineNumber: Int64): GetterActionSelector + public static func stubMethod( stubCall: () -> TRet, matchers: Array, objectReference: TObj, objectName: String, methodName: String, callDescription: String, lineNumber: Int64): MethodActionSelector + public static func stubSetter( stubCall: () -> Unit, _: () -> TArg, matcher: ArgumentMatcher, objectReference: TObj, objectName: String, fieldOrPropertyName: String, callDescription: String, lineNumber: Int64): SetterActionSelector +} + +public class Continuation where A <: ActionSelector { + func then(): A +} + +public class GetterActionSelector <: ActionSelector { + public func getsField(field: SyntheticField): CardinalitySelector> + public func getsOriginal(): CardinalitySelector> + public func returns(value: TRet): CardinalitySelector> + public func returns(valueFactory: () -> TRet): CardinalitySelector> + public func returnsConsecutively(values: Array) + public func returnsConsecutively(values: ArrayList) + public func throws(exception: Exception): CardinalitySelector> + public func throws(exceptionFactory: () -> Exception): CardinalitySelector> +} + +extend MethodActionSelector where TRet <: Unit { + public func returns(): CardinalitySelector> +} + +public class Matchers { + public static func any(): AnyMatcher + public static func argThat(listener: ValueListener, predicate: (T) -> Bool): TypedMatcher + public static func argThat(predicate: (T) -> Bool): TypedMatcher + public static func argThatNot(predicate: (T) -> Bool): TypedMatcher + public static func capture(listener: ValueListener): TypedMatcher + public static func default(target: T): TypedMatcher + public static func eq(target: T): TypedMatcher where T <: Equatable + public static func ofType(): TypedMatcher + public static func same(target: T): TypedMatcher where T <: Object +} + +extend Matchers { + public static func none(): NoneMatcher +} + +public class MethodActionSelector <: ActionSelector { + func callsOriginal(): CardinalitySelector + func returns(valueFactory: () -> R): CardinalitySelector + func returns(value: R): CardinalitySelector + func returnsConsecutively(values: Array): Continuation + func returnsConsecutively(values: ArrayList): Continuation + func throws(exceptionFactory: () -> Exception): CardinalitySelector + func throws(exception: Exception): CardinalitySelector +} + +public class MockFramework { + public static func openSession(name: String, sessionKind: MockSessionKind): Unit + public static func closeSession(): Unit +} + +public class NoneMatcher <: ArgumentMatcher { + public override func matchesAny(arg: Any): Bool +} + +extend NoneMatcher { + public func value(): Option +} + +public class OrderedVerifier { + public func checkThat(statement: VerifyStatement): OrderedVerifier +} + +public class SetterActionSelector <: ActionSelector { + public func doesNothing(): CardinalitySelector> + public func setsOriginal(): CardinalitySelector> + public func setsField(field: SyntheticField): CardinalitySelector> + public func throws(exception: Exception): CardinalitySelector> + public func throws(exceptionFactory: () -> Exception): CardinalitySelector> +} + +public class SyntheticField { + public static func create(initialValue!: T): SyntheticField +} + +public abstract class TypedMatcher <: ArgumentMatcher { + public func matches(arg: T): Bool + public func matchesAny(arg: Any): Bool +} + +extend TypedMatcher { + public func value(): T +} + +public class UnorderedVerifier { + public func checkThat(statement: VerifyStatement):UnorderedVerifier +} + +public class Verify { + let foo = mock()// 定义“桩签名”的“桩行为”@On(foo.bar().returns(1))// 实际“桩签名”在用例中的执行情况foo.bar()// 验证“桩签名”的执行情况:foo.bar() 至少执行了一次Verify.that(@Called(foo.bar())) + public static func clearInvocationLog(): Unit + public static func noInteractions(mocks: Array): Unit + public static func ordered( collectStatements: (OrderedVerifier) -> Unit): Unit + public static func ordered(statements: Array): Unit + for (i in 0..4) { foo.bar(i % 2)}Verify.ordered( @Called(foo.bar(0)), @Called(foo.bar(1)), @Called(foo.bar(0)), @Called(foo.bar(1)),)// 将抛出异常,验证范围内有 4 次 foo.bar() 表达式的执行动作,此处只验证了2次执行。Verify.ordered( @Called(foo.bar(0)), @Called(foo.bar(_)),) + public static func that(statement: VerifyStatement): Unit + public static func unordered(collectStatements: (UnorderedVerifier) -> Unit): Unit + let totalTimes = getTimes()for (i in 0..totalTimes) { foo.bar(i % 2)}// 通过闭包使得“验证语句”可以通过 totalTimes 的值确定内容Verify.unordered { v => for (j in 0..totalTimes) { v.checkThat(@Called(foo.bar(eq(j % 2)))) }} + public static func unordered(statements: Array): Unit + let foo = mock()for (i in 0..4) { foo.bar(i % 2)}// 验证 bar() 在传入参数为 0 或 1 的情况下均至少执行一次Verify.unordered( @Called(foo.bar(0)), @Called(foo.bar(1)))// 此处的验证动作将抛出异常,因为 `foo.bar(_)` 包含了 `foo.bar(1)`Verify.unordered( @Called(foo.bar(_)).times(2), @Called(foo.bar(1)).times(2))// 可以通过如下方式进行验证// 验证入参为 1 的调用表达式执行了2次Verify.that(@Called(foo.bar(1)).times(2))// 验证任意入参的调用表达式执行了2次Verify.that(@Called(foo.bar(_)).times(2)) // called four times in total + public static func unordered(exhaustive: Exhaustiveness, collectStatements: (UnorderedVerifier) -> Unit): Unit + public static func unordered(exhaustive: Exhaustiveness, statements: Array): Unit +} + +public class VerifyStatement { + public func atLeastOnce(): VerifyStatement + public func atLeastTimes(minTimesExpected: Int64): VerifyStatement + public func once(): VerifyStatement + public func times(expectedTimes: Int64): VerifyStatement + public func times(min!: Int64, max!: Int64): VerifyStatement +} + + +// --------------------------- +// -----enums +// --------------------------- +public enum Exhaustiveness { + for (i in 0..6) { foo.bar(i % 3)}// 此处验证动作将抛出异常,因为 foo.bar()在验证范围内一共执行了 6 次,而此处的验证动作仅指定了 4 次执行行为。Verify.unordered( @Called(foo.bar(1)).times(2), @Called(foo.bar(2)).times(2))// 此处验证动作可以成功,指定了 Partial 模式后,2 次未在验证动作中定义的执行行为将被忽略。Verify.unordered(Partial, @Called(foo.bar(1)).times(2), @Called(foo.bar(2)).times(2)) + Exhaustive + Partial +} + +public enum MockSessionKind {} + +public enum StubMode {} + + +// --------------------------- +// -----exceptions +// --------------------------- +public open class ExpectationFailedException <: PrettyException {} + +public class MockFrameworkException <: PrettyException {} + +public class MockFrameworkInternalError <: PrettyException {} + +public abstract class PrettyException <: Exception & PrettyPrintable { + public func pprint(to: PrettyPrinter): PrettyPrinter +} + +public class UnhandledCallException <: PrettyException {} + +public class UnnecessaryStubbingException <: PrettyException {} + +public class UnstubbedInvocationException <: PrettyException {} + +public class VerificationFailedException <: PrettyException {} + + +// --------------------------- +// -----functions +// --------------------------- +public func mock(): T +public func mock(modes: Array): T +public func spy(objectToSpyOn: T): T + +// --------------------------- +// -----interfaces +// --------------------------- +public interface ValueListener { + struct Animal { Animal( let name: String, let info: String ) {}}abstract class AnimalUi { func showAnimal(animal: Animal): Unit}let animals = [Animal("Smokey", "Cat, age: 5"), Animal("Daisy", "Dog, age: 9")]@Test func testAnimal(): Unit { let ui = mock() // 定义了一个值监听器:检查每个值,当值不满足条件时抛出异常 let listener = ValueListener.onEach { animal => if (animal.name == "Smokey") { @Assert(animal.info.contains("Cat")) } } // 定义一个桩签名的“桩行为”,参数匹配器为可执行上述值监听器的参数捕获器 @On(ui.showAnimal(capture(listener))).returns(()) for (animal in animals) { // 此处将捕获传入的 animal 对象,并对其执行值监听器中的检查行为。 ui.showAnimal(animal) }} + func addCallback(callback: (T) -> Unit): Unit + func allValues(): Array + func lastValue(): Option + static func new(): ValueListener + static func onEach(callback: (T) -> Unit): ValueListener +} + + diff --git a/cangjie_libs/std/unittest.mockmacro.cjd b/cangjie_libs/std/unittest.mockmacro.cjd new file mode 100644 index 0000000000000000000000000000000000000000..85de15e395a424d1018db3c76cf17d2ac6188472 --- /dev/null +++ b/cangjie_libs/std/unittest.mockmacro.cjd @@ -0,0 +1,6 @@ +package std.unittest.mockmacro + +// --------------------------- +// -----macros +// --------------------------- + diff --git a/cangjie_libs/std/unittest.prop_test.cjd b/cangjie_libs/std/unittest.prop_test.cjd new file mode 100644 index 0000000000000000000000000000000000000000..ef9f3b5f24035f92de8f0e766f50172957a245b6 --- /dev/null +++ b/cangjie_libs/std/unittest.prop_test.cjd @@ -0,0 +1,323 @@ +package std.unittest.prop_test + +// --------------------------- +// -----classes +// --------------------------- +public class Generators { + public static func generate(body: () -> T): Generator + public static func iterable(random: RandomSource, collection: Array): Generator + public static func lookup(random: RandomSource): Generator where T <: Arbitrary + public static func mapped(random: RandomSource, body: (T) -> R): Generator where T <: Arbitrary + public static func mapped(random: RandomSource, body: (T1, T2) -> R): Generator where T1 <: Arbitrary, T2 <: Arbitrary + public static func mapped(random: RandomSource, body: (T1, T2, T3) -> R): Generator where T1 <: Arbitrary, T2 <: Arbitrary, T3 <: Arbitrary + public static func mapped(random: RandomSource, body: (T1, T2, T3, T4) -> R): Generator where T1 <: Arbitrary, T2 <: Arbitrary, T3 <: Arbitrary, T4 <: Arbitrary + public static func pick(random: RandomSource, variants: Array>): Generator ``` 通过从生成器数组中随机选取来生成值的生成器。功能:通过从生成器数组中随机选取来生成值的生成器。参数:- random: [RandomSource](./unittest_prop_test_package_interfaces.md#interface-randomsource) - 随机数。- variants: [Array](../../core/core_package_api/core_package_structs.md#struct-arrayt)> - 生成器数组。返回值:- [Generator](#class-generators)\ - 生成器。### static func single(T)```cangjiepublic static func single(value: T): Generator + public static func weighted(random: RandomSource, variants: Array<(UInt64, Generator)>): Generator +} + +public class LazySeq <: Iterable { + public init() + public init(element: T) + public func append(element: T): LazySeq + public func concat(other: LazySeq): LazySeq + public func iterator(): Iterator + public func map(body: (T) -> U): [LazySeq](#class-lazyseq) + public func mixWith(other: LazySeq): LazySeq + public func prepend(element: T): LazySeq + public static func mix(l1: LazySeq, l2: LazySeq) + public static func mix(l1: LazySeq, l2: LazySeq, l3: LazySeq) + public static func mix(l1: LazySeq, l2: LazySeq, l3: LazySeq, l4: LazySeq) + public static func mix(l1: LazySeq, l2: LazySeq, l3: LazySeq, l4: LazySeq, l5: LazySeq) + public static func of(iterable: Iterable) + public static func of(array: Array) +} + +public class ShrinkHelpers { + public static func shrinkTuple( tuple: (T0, T1), t0: Iterable, t1: Iterable): Iterable<(T0, T1)> + public static func shrinkTuple( tuple: (T0, T1, T2), t0: Iterable, t1: Iterable, t2: Iterable): Iterable<(T0, T1, T2)> + public static func shrinkTuple( tuple: (T0, T1, T2, T3), t0: Iterable, t1: Iterable, t2: Iterable, t3: Iterable): Iterable<(T0, T1, T2, T3)> + public static func shrinkTuple( tuple: (T0, T1, T2, T3, T4), t0: Iterable, t1: Iterable, t2: Iterable, t3: Iterable, t4: Iterable): Iterable<(T0, T1, T2, T3, T4)> +} + + +// --------------------------- +// -----functions +// --------------------------- +public func emptyIterable(): Iterable +public func random(): RandomDataStrategy where T <: Arbitrary + +// --------------------------- +// -----interfaces +// --------------------------- +public interface Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Bool <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Float16 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Float32 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Float64 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Int16 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Int32 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Int64 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Int8 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend IntNative <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Ordering <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Rune <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend String <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend UInt16 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend UInt32 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend UInt64 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend UInt8 <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend UIntNative <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Unit <: Arbitrary { + static func arbitrary(random: RandomSource): Generator +} + +extend Array <: Arbitrary> where T <: Arbitrary { + static func arbitrary(random: RandomSource): Generator> +} + +extend option <: Arbitrary> where T <: Arbitrary { + static func arbitrary(random: RandomSource): Generator> +} + +extend ArrayList <: Arbitrary> where T <: Arbitrary { + static func arbitrary(random: RandomSource): Generator> +} + +extend HashSet <: Arbitrary> where T <: Arbitrary { + static func arbitrary(random: RandomSource): Generator> +} + +extend HashMap <: Arbitrary> where K <: Arbitrary, V <: Arbitrary { + static func arbitrary(random: RandomSource): Generator> +} + +public interface IndexAccess { + func getElementAsAny(index: Int64): ?Any +} + +public interface RandomSource {} + +public interface Shrink { + func shrink(): Iterable +} + +extend Bool <: Shrink { + func shrink(): Iterable +} + +extend Int16 <: Shrink { + func shrink(): Iterable +} + +extend Int32 <: Shrink { + func shrink(): Iterable +} + +extend Int64 <: Shrink { + func shrink(): Iterable +} + +extend Int8 <: Shrink { + func shrink(): Iterable +} + +extend IntNative <: Shrink { + func shrink(): Iterable +} + +extend Rune <: Shrink { + func shrink(): Iterable +} + +extend String <: Shrink { + func shrink(): Iterable +} + +extend UInt16 <: Shrink { + func shrink(): Iterable +} + +extend UInt32 <: Shrink { + func shrink(): Iterable +} + +extend UInt64 <: Shrink { + func shrink(): Iterable +} + +extend UInt8 <: Shrink { + func shrink(): Iterable +} + +extend UIntNative <: Shrink { + func shrink(): Iterable +} + +extend Unit <: Shrink { + func shrink(): Iterable +} + +extend Array <: Shrink> where T <: Shrink { + func shrink(): Iterable> +} + +extend Option <: Shrink> where T <: Shrink { + func shrink(): Iterable> +} + + +// --------------------------- +// -----structs +// --------------------------- +public struct Function0Wrapper { + public Function0Wrapper(public let function: () -> R) + public operator func () (): R +} + +extend Function0Wrapper <: Arbitrary> where R <: Arbitrary { + public static func arbitrary(random: RandomSource): Generator> +} + +public struct TupleWrapper2 { + public TupleWrapper2(public let tuple: (T0, T1)) + public func apply(f: (T0, T1) -> R): R +} + +extend TupleWrapper2 <: ToString { + public func toString() +} + +extend TupleWrapper2 <: Equatable> { + public operator func ==(other: TupleWrapper2) + public operator func !=(other: TupleWrapper2) +} + +extend TupleWrapper2 <: IndexAccess { + public func getElementAsAny(index: Int64): ?Any +} + +extend TupleWrapper2 <: Arbitrary> where T0 <: Arbitrary,T1 <: Arbitrary { + public static func arbitrary(random: RandomSource): Generator> +} + +public struct TupleWrapper3 { + public TupleWrapper3(public let tuple: (T0, T1,T2)) + public func apply(f: (T0, T1,T2) -> R): R +} + +extend TupleWrapper3 <: ToString { + public func toString() +} + +extend TupleWrapper3 <: Equatable> { + public operator func ==(other: TupleWrapper3) + public operator func !=(other: TupleWrapper3) +} + +extend TupleWrapper3 <: IndexAccess { + public func getElementAsAny(index: Int64): ?Any +} + +extend TupleWrapper3 <: Arbitrary> where T0 <: Arbitrary,T1 <: Arbitrary,T2 <: Arbitrary { + public static func arbitrary(random: RandomSource): Generator> +} + +public struct TupleWrapper4 { + public TupleWrapper4(public let tuple: (T0, T1, T2, T3)) + public func apply(f: (T0, T1, T2, T3) -> R): R +} + +extend TupleWrapper4 <: ToString { + public func toString() +} + +extend TupleWrapper3 <: Equatable> { + public operator func ==(other: TupleWrapper4) + public operator func !=(other: TupleWrapper4) +} + +extend TupleWrapper4 <: IndexAccess { + public func getElementAsAny(index: Int64): ?Any +} + +extend TupleWrapper4<: Arbitrary> where where T0 <: Arbitrary,T1 <: Arbitrary,T2 <: Arbitrary,T3 <: Arbitrary { + public static func arbitrary(random: RandomSource): Generator> +} + +public struct TupleWrapper5 { + public TupleWrapper5(public let tuple: (T0, T1, T2, T3, T4)) + public func apply(f: (T0, T1, T2, T3, T4) -> R): R +} + +extend TupleWrapper5 <: ToString { + public func toString() +} + +extend TupleWrapper3 <: Equatable> { + public operator func ==(other: TupleWrapper5) + public operator func !=(other: TupleWrapper2) +} + +extend TupleWrapper5 <: IndexAccess { + public func getElementAsAny(index: Int64): ?Any +} + +extend TupleWrapper5 <: Arbitrary> where T0 <: Arbitrary,T1 <: Arbitrary,T2 <: Arbitrary,T3 <: Arbitrary,T4 <: Arbitrary { + public static func arbitrary(random: RandomSource): Generator> +} + + diff --git a/cangjie_libs/std/unittest.testmacro.cjd b/cangjie_libs/std/unittest.testmacro.cjd new file mode 100644 index 0000000000000000000000000000000000000000..7b26b0c795366a94589b2c8b1b24a6f6adbb2136 --- /dev/null +++ b/cangjie_libs/std/unittest.testmacro.cjd @@ -0,0 +1,27 @@ +package std.unittest.testmacro + +// --------------------------- +// -----macros +// --------------------------- +public macro @AfterAll(input: Tokens): Tokens +public macro @AfterEach(input: Tokens): Tokens +public macro @Assert(input: Tokens): Tokens +public macro @AssertThrows(input: Tokens): Tokens +public macro @BeforeAll(input: Tokens): Tokens +public macro @BeforeEach(input: Tokens): Tokens +public macro @Bench(input: Tokens): Tokens +public macro @Configure(input: Tokens): Tokens +public macro @Expect(input: Tokens): Tokens +public macro @ExpectThrows(input: Tokens): Tokens +public macro @Fail(input: Tokens): Tokens +public macro @FailExpect(input: Tokens): Tokens +public macro @Parallel(input: Tokens): Tokens +public macro @PowerAssert(input: Tokens): Tokens +public macro @Skip(input: Tokens): Tokens +public macro @Strategy(input: Tokens): Tokens +public macro @Test(input: Tokens): Tokens +public macro @TestBuilder(input: Tokens): Tokens +public macro @TestCase(input: Tokens): Tokens +public macro @Timeout(input: Tokens): Tokens +public macro @Types(input: Tokens): Tokens + diff --git a/index.js b/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7e3b9f11e2538d5ad178b823079fa6b457e91805 --- /dev/null +++ b/index.js @@ -0,0 +1,136 @@ +// const axios = require("axios") +const fs = require('fs'); +const path = require('path'); +const cheerio = require('cheerio'); + +const docPath = "D:/intelliJ/CangjieProject/docs/cjnative" +const cjLibs = [ + { + name: "std", + pkgs: ["core", "argopt", "ast", "binary", "collection", "collection.concurrent", "console", + "convert", "crypto.digest", "crypto.cipher", "database.sql", "deriving", "ffi.python", + "format", "fs", "io", "log", "math", "math.numeric", "net", "objectpool", "os", + "os.posix", "os.process", "overflow", "random", "reflect", "regex", "runtime", "socket", + "sort", "sync", "time", "unicode", "unittest", "unittest.mock", "unittest.mockmacro", + "unittest.testmacro", "unittest.common", "unittest.diff", "unittest.prop_test" + ] + }, + { + name: "compress", + pkgs: ["zlib"] + }, + { + name: "crypto", + pkgs: ["crypto", "digest", "keys", "x509"] + }, + { + name: "encoding", + pkgs: ["base64", "hex", "json", "json.stream", "url", "xml"] + }, + { + name: "fuzz", + pkgs: ["fuzz"] + }, + { + name: "log", + pkgs: ["log"] + }, + { + name: "logger", + pkgs: ["logger"] + }, + { + name: "net", + pkgs: ["http", "tls"] + }, + { + name: "serialization", + pkgs: ["serialization"] + } +] + +function findDirsIncludes(dir, ...extensions) { + const files = fs.readdirSync(dir); + const matchingFiles = files.filter(file => { + const filePath = path.join(dir, file); + return fs.statSync(filePath).isDirectory() && extensions.every(ext => file.includes(ext)); + }); + return matchingFiles.map(file => path.join(dir, file)); +} + +if (!fs.existsSync("./docs")) { + fs.mkdirSync(path.join("./docs"), { recursive: true }); +} + +for (lib of cjLibs) { + for (pkg of lib.pkgs) { + let libPath; + let pkgName = pkg.replace(/\./g, "_"); + if (lib.name === "std") { + if (pkg.startsWith("crypto")) { + libPath = findDirsIncludes(path.join(docPath, "libs", lib.name, pkg.split(".")[0], pkg.split(".")[1]), "api")[0]; + } else if (pkg.includes("mockmacro")) { + libPath = findDirsIncludes(path.join(docPath, "libs", lib.name, "unittest_testmacro"), "api", "mockmacro")[0]; + } else if (pkg.includes("testmacro")) { + libPath = findDirsIncludes(path.join(docPath, "libs", lib.name, "unittest_testmacro"), "api", "testmacro")[0]; + } + } + if (!libPath) libPath = findDirsIncludes(path.join(docPath, "libs", lib.name, pkgName), "api")[0]; + + if (!libPath) { + console.log(`${lib.name}.${pkg} no api found.`) + continue + } + const files = fs.readdirSync(libPath); + let content = `package ${lib.name}.${pkg}\n\n` + + console.log(`${lib.name}.${pkg} processing...`) + for (let file of files) { + let type = file.match(/([0-9a-zA-Z]+)(?=\.html)/)[0] + content += `// ---------------------------\n// -----${type}\n// ---------------------------\n` + const $ = cheerio.load(fs.readFileSync(path.join(libPath, file), "utf8")); + const main = $("#content"); + if (type === "macros") { + // 搜索宏定义 + main.find("h2").each((i, elem) => { + let name = $(elem).find("code").text() + if (name) { + content += `public macro ${name}(input: Tokens): Tokens\n`; + } + }); + } else { + // 搜索文档中的代码片段 + main.find("h2, [id^='extend']").each((i, elem) => { + let nameNode = $(elem).next("pre") + let name = nameNode.find("code").text() + "{"; + name = name.substring(0, name.indexOf("{") ?? name.length).trim() + const decls = [] + + $(nameNode).nextUntil("h2, [id^='extend']").each((j, subElem) => { + if (subElem.tagName === "pre") { + const decl = $(subElem).find("code.language-cangjie").text().replace(/[\n\r\t]/g, "").replace(/\s+/g, " ").trim() + if (decl) decls.push(decl) + } + }); + + if (name) { + content += `${name}`; + if (decls.length > 0) + content += ` {\n\t${decls.join("\n\t")}\n}\n`; + else if (!name.includes("func") && !name.includes("func")) { + content += " {}\n"; + } + content += "\n"; + } + }); + } + content += "\n" + } + console.log(`${lib.name}.${pkg} done.`) + if (!fs.existsSync(`./docs/${lib.name}`)) { + fs.mkdirSync(path.join(`./docs/${lib.name}`), { recursive: true }); + } + fs.writeFileSync(path.join(`./docs/${lib.name}`, `${pkg}.cjd`), content, "utf8") + } +} +