diff --git a/Sources/FrontEnd/AST/AST.swift b/Sources/FrontEnd/AST/AST.swift index 1f9952440..57ee86d38 100644 --- a/Sources/FrontEnd/AST/AST.swift +++ b/Sources/FrontEnd/AST/AST.swift @@ -303,7 +303,6 @@ public struct AST { /// Returns the kind identifying synthesized declarations of `requirement`, or `nil` if /// `requirement` is not synthesizable. public func synthesizedKind(of requirement: T) -> SynthesizedFunctionDecl.Kind? { - // If the requirement is defined in `Deinitializable`, it must be the deinitialization method. switch requirement.rawValue { case core.deinitializable.deinitialize.rawValue: return .deinitialize @@ -313,6 +312,8 @@ public struct AST { return .moveAssignment case core.copyable.copy.rawValue: return .copy + case core.equatable.equal.rawValue: + return .equal default: return nil } diff --git a/Sources/FrontEnd/AST/Decl/SynthesizedFunctionDecl.swift b/Sources/FrontEnd/AST/Decl/SynthesizedFunctionDecl.swift index d0c785930..495aa313d 100644 --- a/Sources/FrontEnd/AST/Decl/SynthesizedFunctionDecl.swift +++ b/Sources/FrontEnd/AST/Decl/SynthesizedFunctionDecl.swift @@ -18,6 +18,9 @@ public struct SynthesizedFunctionDecl: Hashable { /// A copy method. case copy + /// An equality method. + case equal + /// A global initializer for a binding declaration. case globalInitialization(BindingDecl.ID) diff --git a/Sources/FrontEnd/Types/BuiltinType.swift b/Sources/FrontEnd/Types/BuiltinType.swift index b229da345..ac4404407 100644 --- a/Sources/FrontEnd/Types/BuiltinType.swift +++ b/Sources/FrontEnd/Types/BuiltinType.swift @@ -28,6 +28,9 @@ public enum BuiltinType: TypeProtocol { /// The type of the built-in module. case module + /// The type of a union discriminator. + public static let discriminator = word + /// `true` iff `self` is `.i` or `.word`. public var isInteger: Bool { switch self { diff --git a/Sources/IR/Emitter.swift b/Sources/IR/Emitter.swift index d4978bd2b..ff17742a3 100644 --- a/Sources/IR/Emitter.swift +++ b/Sources/IR/Emitter.swift @@ -645,15 +645,17 @@ struct Emitter { mutating func lower(synthetic d: SynthesizedFunctionDecl) { switch d.kind { case .deinitialize: - return withClearContext({ $0.lower(syntheticDeinit: d) }) + lower(syntheticDeinit: d) case .moveInitialization: - return withClearContext({ $0.lower(syntheticMoveInit: d) }) + lower(syntheticMoveInit: d) case .moveAssignment: - return withClearContext({ $0.lower(syntheticMoveAssign: d) }) + lower(syntheticMoveAssign: d) case .copy: - return withClearContext({ $0.lower(syntheticCopy: d) }) + lower(syntheticCopy: d) + case .equal: + lower(syntheticEqual: d) case .globalInitialization: - return withClearContext({ $0.lower(globalBindingInitializer: d) }) + lower(globalBindingInitializer: d) case .autoclosure: // nothing do to here; expansion is done at the caller side. break @@ -662,54 +664,34 @@ struct Emitter { /// Inserts the IR for `d`, which is a synthetic deinitializer. private mutating func lower(syntheticDeinit d: SynthesizedFunctionDecl) { - let f = module.demandDeclaration(lowering: d) - if !shouldEmitBody(of: d, loweredTo: f) { return } + withPrologue(of: d) { (me, site, entry) in + // The receiver is a sink parameter representing the object to deinitialize. + let receiver = Operand.parameter(entry, 0) + me.emitDeinitParts(of: receiver, at: site) - let site = ast[module.id].site - let entry = module.appendEntry(in: d.scope, to: f) - insertionPoint = .end(of: entry) - self.frames.push() - defer { - self.frames.pop() - assert(self.frames.isEmpty) + me.insert(me.module.makeMarkState(me.returnValue!, initialized: true, at: site)) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) } - - // The receiver is a sink parameter representing the object to deinitialize. - let receiver = Operand.parameter(entry, 0) - emitDeinitParts(of: receiver, at: site) - - insert(module.makeMarkState(returnValue!, initialized: true, at: site)) - emitDeallocTopFrame(at: site) - insert(module.makeReturn(at: site)) } /// Inserts the IR for `d`, which is a synthetic move initialization method. private mutating func lower(syntheticMoveInit d: SynthesizedFunctionDecl) { - let f = module.demandDeclaration(lowering: d) - if !shouldEmitBody(of: d, loweredTo: f) { return } - - let site = ast[module.id].site - let entry = module.appendEntry(in: d.scope, to: f) - insertionPoint = .end(of: entry) - self.frames.push() - defer { - self.frames.pop() - assert(self.frames.isEmpty) - } - - let receiver = Operand.parameter(entry, 0) - let argument = Operand.parameter(entry, 1) - let object = module.type(of: receiver).ast + withPrologue(of: d) { (me, site, entry) in + let receiver = Operand.parameter(entry, 0) + let argument = Operand.parameter(entry, 1) + let object = me.module.type(of: receiver).ast + + if object.hasRecordLayout { + me.emitMoveInitRecordParts(of: receiver, consuming: argument, at: site) + } else if object.base is UnionType { + me.emitMoveInitUnionPayload(of: receiver, consuming: argument, at: site) + } - if object.hasRecordLayout { - emitMoveInitRecordParts(of: receiver, consuming: argument, at: site) - } else if object.base is UnionType { - emitMoveInitUnionPayload(of: receiver, consuming: argument, at: site) + me.insert(me.module.makeMarkState(me.returnValue!, initialized: true, at: site)) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) } - - insert(module.makeMarkState(returnValue!, initialized: true, at: site)) - emitDeallocTopFrame(at: site) - insert(module.makeReturn(at: site)) } /// Inserts the IR for initializing the stored parts of `receiver`, which stores a record, @@ -799,57 +781,81 @@ struct Emitter { /// Inserts the IR for `d`, which is a synthetic move initialization method. private mutating func lower(syntheticMoveAssign d: SynthesizedFunctionDecl) { - let f = module.demandDeclaration(lowering: d) - if !shouldEmitBody(of: d, loweredTo: f) { return } - - let site = ast[module.id].site - let entry = module.appendEntry(in: d.scope, to: f) - insertionPoint = .end(of: entry) - self.frames.push() - defer { - self.frames.pop() - assert(self.frames.isEmpty) - } + withPrologue(of: d) { (me, site, entry) in + let receiver = Operand.parameter(entry, 0) + let argument = Operand.parameter(entry, 1) - let receiver = Operand.parameter(entry, 0) - let argument = Operand.parameter(entry, 1) - - // Deinitialize the receiver. - emitDeinit(receiver, at: site) + // Deinitialize the receiver. + me.emitDeinit(receiver, at: site) - // Apply the move-initializer. - emitMove([.set], argument, to: receiver, at: site) - insert(module.makeMarkState(returnValue!, initialized: true, at: site)) - emitDeallocTopFrame(at: site) - insert(module.makeReturn(at: site)) + // Apply the move-initializer. + me.emitMove([.set], argument, to: receiver, at: site) + me.insert(me.module.makeMarkState(me.returnValue!, initialized: true, at: site)) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) + } } /// Inserts the IR for `d`, which is a synthetic copy method. private mutating func lower(syntheticCopy d: SynthesizedFunctionDecl) { - let f = module.demandDeclaration(lowering: d) - if !shouldEmitBody(of: d, loweredTo: f) { return } + withPrologue(of: d) { (me, site, entry) in + let source = Operand.parameter(entry, 0) + let target = Operand.parameter(entry, 1) + let object = me.module.type(of: source).ast + + if object.hasRecordLayout { + me.emitCopyRecordParts(from: source, to: target, at: site) + } else if object.base is UnionType { + me.emitCopyUnionPayload(from: source, to: target, at: site) + } - let site = ast[module.id].site - let entry = module.appendEntry(in: d.scope, to: f) - insertionPoint = .end(of: entry) - self.frames.push() - defer { - self.frames.pop() - assert(self.frames.isEmpty) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) } + } + + /// Inserts the ID for `d`, which is an equality operator. + private mutating func lower(syntheticEqual d: SynthesizedFunctionDecl) { + withPrologue(of: d) { (me, site, entry) in + let lhs = Operand.parameter(entry, 0) + let rhs = Operand.parameter(entry, 1) + let t = me.module.type(of: lhs).ast - let source = Operand.parameter(entry, 0) - let target = Operand.parameter(entry, 1) - let object = module.type(of: source).ast + if t.hasRecordLayout { + me.emitStorePartsEquality(lhs, rhs, to: me.returnValue!, at: site) + } else if t.base is UnionType { + me.emitStoreUnionPayloadEquality(lhs, rhs, to: me.returnValue!, at: site) + } else { + UNIMPLEMENTED("synthetic equality for type '\(t)'") + } - if object.hasRecordLayout { - emitCopyRecordParts(from: source, to: target, at: site) - } else if object.base is UnionType { - emitCopyUnionPayload(from: source, to: target, at: site) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) } + } - emitDeallocTopFrame(at: site) - insert(module.makeReturn(at: site)) + /// Declares `d` in the current module and returns its corresponding identifier, calls `action` + /// to generate its implementation if it should be emitted the current module. + @discardableResult + private mutating func withPrologue( + of d: SynthesizedFunctionDecl, + _ action: (inout Self, _ site: SourceRange, _ entry: Block.ID) -> Void + ) -> Function.ID { + withClearContext { (me) in + let f = me.module.demandDeclaration(lowering: d) + if me.shouldEmitBody(of: d, loweredTo: f) { + let site = me.ast[me.module.id].site + let entry = me.module.appendEntry(in: d.scope, to: f) + me.insertionPoint = .end(of: entry) + me.frames.push() + + action(&me, site, entry) + + me.frames.pop() + assert(me.frames.isEmpty) + } + return f + } } /// Inserts the IR for copying the stored parts of `source`, which stores a record, to `target` @@ -927,31 +933,20 @@ struct Emitter { /// the lowered function. @discardableResult private mutating func lower(globalBindingInitializer d: SynthesizedFunctionDecl) -> Function.ID { - let f = module.demandDeclaration(lowering: d) - if !shouldEmitBody(of: d, loweredTo: f) { - return f - } + withPrologue(of: d) { (me, _, entry) in + let storage = Operand.parameter(entry, 0) + guard case .globalInitialization(let binding) = d.kind else { unreachable() } - let entry = module.appendEntry(in: d.scope, to: f) - insertionPoint = .end(of: entry) - self.frames.push() - defer { - self.frames.pop() - assert(self.frames.isEmpty) - } - - let storage = Operand.parameter(entry, 0) - guard case .globalInitialization(let binding) = d.kind else { unreachable() } - let initializer = program[binding].initializer! + let initializer = me.program[binding].initializer! + let site = me.program[initializer].site - emitInitStoredLocalBindings( - in: program[binding].pattern.subpattern, referringTo: [], relativeTo: storage, - consuming: initializer) - insert(module.makeMarkState(returnValue!, initialized: true, at: program[initializer].site)) - emitDeallocTopFrame(at: program[initializer].site) - insert(module.makeReturn(at: program[initializer].site)) - - return f + me.emitInitStoredLocalBindings( + in: me.program[binding].pattern.subpattern, referringTo: [], relativeTo: storage, + consuming: initializer) + me.insert(me.module.makeMarkState(me.returnValue!, initialized: true, at: site)) + me.emitDeallocTopFrame(at: site) + me.insert(me.module.makeReturn(at: site)) + } } private mutating func lower(syntheticAutoclosure d: SynthesizedFunctionDecl) -> Function.ID { @@ -1432,9 +1427,7 @@ struct Emitter { /// Inserts the IR for storing the value of `e` to `storage`. private mutating func emitStore(_ e: BooleanLiteralExpr.ID, to storage: Operand) { - let x0 = emitSubfieldView(storage, at: [0], at: ast[e].site) - let x1 = insert(module.makeAccess(.set, from: x0, at: ast[e].site))! - insert(module.makeStore(.i1(ast[e].value), at: x1, at: ast[e].site)) + emitStore(boolean: ast[e].value, to: storage, at: ast[e].site) } /// Inserts the IR for storing the value of `e` to `storage`. @@ -1581,17 +1574,9 @@ struct Emitter { usingExplicit: ast[e].arguments, synthesizingDefaultAt: .empty(at: ast[e].site.end)) let m = ast.isMarkedForMutation(ast[e].callee) let (callee, captures) = emitFunctionCallee(ast[e].callee, markedForMutation: m) - let inputs = captures + arguments // Call is evaluated last. - switch callee { - case .direct(let r): - emitApply(.constant(r), to: inputs, writingResultTo: storage, at: ast[e].site) - case .lambda(let r): - emitApply(r, to: inputs, writingResultTo: storage, at: ast[e].site) - case .bundle(let r): - emitApply(r, to: inputs, writingResultTo: storage, at: ast[e].site) - } + emitApply(callee, to: captures + arguments, writingResultTo: storage, at: ast[e].site) } /// Inserts the IR for storing the value of `e` to `storage`. @@ -1681,8 +1666,8 @@ struct Emitter { private mutating func emitStore(_ e: FoldedSequenceExpr, to storage: Operand) { switch e { case .infix(let callee, let lhs, let rhs): - let t = program[callee.expr].type - let calleeType = ArrowType(canonical(t))!.lifted + let t = canonical(program[callee.expr].type) + let calleeType = ArrowType(t)!.lifted // Emit the operands, starting with RHS. let r = emit(infixOperand: rhs, passed: ParameterType(calleeType.inputs[1].type)!.access) @@ -1693,13 +1678,13 @@ struct Emitter { unreachable() } - let o = FunctionReference(to: d, in: &module, specializedBy: a, in: insertionScope!) - let f = Operand.constant(o) - - // Emit the call. - let site = ast.site(of: e) - let result = insert(module.makeAccess(.set, from: storage, at: site))! - insert(module.makeCall(applying: f, to: [l, r], writingResultTo: result, at: site)) + let site = program[callee.expr].site + let lhsIsMarkedForMutation = program.ast.isMarkedForMutation(lhs) + let (callee, captures) = emitMemberFunctionCallee( + referringTo: d, memberOf: l, markedForMutation: lhsIsMarkedForMutation, + specializedBy: a, in: program[callee.expr].scope, + at: site) + emitApply(callee, to: captures + [r], writingResultTo: storage, at: site) case .leaf(let v): emitStore(value: v, to: storage) @@ -1833,6 +1818,16 @@ struct Emitter { insert(module.makeStore(x2, at: x1, at: syntax.site)) } + /// Writes an instance of `Hylo.Bool` with value `v` to `storage`. + /// + /// - Requires: `storage` is the address of uninitialized memory of type `Hylo.Int`. + private mutating func emitStore(boolean v: Bool, to storage: Operand, at site: SourceRange) { + let x0 = emitSubfieldView(storage, at: [0], at: site) + let x1 = insert(module.makeAccess(.set, from: x0, at: site))! + insert(module.makeStore(.i1(v), at: x1, at: site)) + insert(module.makeEndAccess(x1, at: site)) + } + /// Writes an instance of `Hylo.Int` with value `v` to `storage`. /// /// - Requires: `storage` is the address of uninitialized memory of type `Hylo.Int`. @@ -1872,6 +1867,21 @@ struct Emitter { frames.top.setMayHoldCaptures(s) } + /// Inserts the IR for calling `callee` on `arguments`, storing the result to `storage`. + private mutating func emitApply( + _ callee: Callee, to arguments: [Operand], + writingResultTo storage: Operand, at site: SourceRange + ) { + switch callee { + case .direct(let r): + emitApply(.constant(r), to: arguments, writingResultTo: storage, at: site) + case .lambda(let r): + emitApply(r, to: arguments, writingResultTo: storage, at: site) + case .bundle(let r): + emitApply(r, to: arguments, writingResultTo: storage, at: site) + } + } + /// Inserts the IR for calling `callee` on `arguments`, storing the result to `storage`. private mutating func emitApply( _ callee: Operand, to arguments: [Operand], @@ -2119,7 +2129,7 @@ struct Emitter { } } - /// Inserts the IR for given `callee`, which is marked for mutation if `isMutating` is `true`, + /// Inserts the IR for given `callee`, which is marked for mutation iff `isMutating` is `true`, /// and returns the callee's value along with its lifted arguments. /// /// Lifted arguments correspond to the captures of the `callee`, which are additional parameters @@ -2170,30 +2180,47 @@ struct Emitter { } } - /// Inserts the IR evaluating `callee`, which refers to a member function marked for mutation - /// iff `isMutating` is `true`, returning the callee's value along with the call receiver. + /// Inserts the IR evaluating `callee`, which refers to a member function, returning the callee's + /// value along with the call receiver. + /// + /// The callee is marked for mutation iff `isMutating` is `true`, in which case the receiver is + /// accessed with a `set` or `inout` capability. private mutating func emitMemberFunctionCallee( _ callee: NameExpr.ID, markedForMutation isMutating: Bool ) -> (callee: Callee, captures: [Operand]) { guard case .member(let d, let a, let s) = program[callee].referredDecl else { unreachable() } - let receiver = emitLValue(receiver: s, at: ast[callee].site) - let receiverType = module.type(of: receiver).ast + let r = emitLValue(receiver: s, at: ast[callee].site) + return emitMemberFunctionCallee( + referringTo: d, memberOf: r, markedForMutation: isMutating, + specializedBy: a, in:program[callee].scope, + at: program[callee].site) + } - let available = receiverCapabilities(program[callee].type) + /// Inserts the IR constructing the callee of a call referring to `d`, which is a member function + /// of `r`, returning the callee's value along with the call receiver. + /// + /// The callee is marked for mutation iff `isMutating` is `true`, in which case the receiver is + /// accessed with a `set` or `inout` capability. + private mutating func emitMemberFunctionCallee( + referringTo d: AnyDeclID, memberOf r: Operand, markedForMutation isMutating: Bool, + specializedBy a: GenericArguments, in scopeOfUse: AnyScopeID, + at site: SourceRange + ) -> (callee: Callee, captures: [Operand]) { + let available = receiverCapabilities(program[d].type) var requested = available.intersection(.forUseOfBundle(performingInPlaceMutation: isMutating)) // TODO: Should report an error when available is `let|sink` and requested is `inout/set` requested = requested.isEmpty ? available : requested let entityToCall = module.memberCallee( - referringTo: d, memberOf: receiverType, accessedWith: requested, - specializedBy: a, usedIn: program[callee].scope) + referringTo: d, memberOf: module.type(of: r).ast, accessedWith: requested, + specializedBy: a, usedIn: scopeOfUse) if case .bundle(let b) = entityToCall { - return emitMethodBundleCallee(referringTo: b, on: receiver, at: program[callee].site) + return emitMethodBundleCallee(referringTo: b, on: r, at: site) } else { - let c = insert(module.makeAccess(requested, from: receiver, at: program[callee].site))! + let c = insert(module.makeAccess(requested, from: r, at: site))! return (callee: entityToCall, captures: [c]) } } @@ -2639,6 +2666,8 @@ struct Emitter { /// Inserts the IR for lvalue `e`. private mutating func emitLValue(upcast e: CastExpr.ID) -> Operand { switch ast[e].left.kind { + case BooleanLiteralExpr.self: + return emitStore(value: ast[e].left) case FloatLiteralExpr.self: return emitStore(value: ast[e].left) case IntegerLiteralExpr.self: @@ -2972,7 +3001,7 @@ struct Emitter { } else if m.isBuiltinOrRawTuple { insert(module.makeMarkState(storage, initialized: false, at: site)) } else { - report(.error(module.type(of: storage).ast, doesNotConformTo: d, at: site)) + report(.error(m, doesNotConformTo: d, at: site)) } } @@ -3086,6 +3115,116 @@ struct Emitter { insert(module.makeCloseUnion(x0, at: site)) } + // MARK: Equality + + private mutating func emitStoreEquality( + _ lhs: Operand, _ rhs: Operand, to target: Operand, at site: SourceRange + ) { + let m = module.type(of: lhs).ast + let d = program.ast.core.equatable.type + + if let equatable = program.conformance(of: m, to: d, exposedTo: insertionScope!) { + let d = module.demandEqualDeclaration(definedBy: equatable) + let f = module.reference(to: d, implementedFor: equatable) + + let x0 = insert(module.makeAccess(.set, from: target, at: site))! + let x1 = insert(module.makeAccess(.let, from: lhs, at: site))! + let x2 = insert(module.makeAccess(.let, from: rhs, at: site))! + insert(module.makeCall(applying: .constant(f), to: [x1, x2], writingResultTo: x0, at: site)) + insert(module.makeEndAccess(x2, at: site)) + insert(module.makeEndAccess(x1, at: site)) + insert(module.makeEndAccess(x0, at: site)) + } else { + report(.error(m, doesNotConformTo: d, at: site)) + } + } + + /// Inserts the IR writing in `target` whether the parts of `lhs` and `rhs` are pairwise equal. + private mutating func emitStorePartsEquality( + _ lhs: Operand, _ rhs: Operand, + to target: Operand, at site: SourceRange + ) { + let layout = AbstractTypeLayout( + of: module.type(of: lhs).ast, definedIn: module.program) + + // If the object is empty, return true. + var parts = layout.properties[...] + if parts.isEmpty { + emitStore(boolean: true, to: target, at: site) + return + } + + // Otherwise, compare all parts pairwise. + let tail = appendBlock() + while !parts.isEmpty { + let x0 = emitSubfieldView(lhs, at: [parts.startIndex], at: site) + let x1 = emitSubfieldView(rhs, at: [parts.startIndex], at: site) + emitStoreEquality(x0, x1, to: target, at: site) + + parts = parts.dropFirst() + if parts.isEmpty { + insert(module.makeBranch(to: tail, at: site)) + insertionPoint = .end(of: tail) + } else { + let x2 = emitLoadBuiltinBool(target, at: site) + let next = appendBlock() + insert(module.makeCondBranch(if: x2, then: next, else: tail, at: site)) + insertionPoint = .end(of: next) + } + } + } + + /// Inserts the IR writing in `target` whether the payloads of `lhs` and `rhs` are equal. + private mutating func emitStoreUnionPayloadEquality( + _ lhs: Operand, _ rhs: Operand, + to target: Operand, at site: SourceRange + ) { + let union = UnionType(module.type(of: lhs).ast)! + + // If the union is empty, return true. + if union.elements.isEmpty { + emitStore(boolean: true, to: target, at: site) + return + } + + // Otherwise, compare their payloads. + let elements = program.discriminatorToElement(in: union) + + let same = appendBlock() + var successors: [Block.ID] = [] + for _ in elements { + successors.append(appendBlock()) + } + let fail = appendBlock() + let tail = appendBlock() + + // The success blocks compare discriminators and then payloads. + let dl = emitUnionDiscriminator(lhs, at: site) + let dr = emitUnionDiscriminator(rhs, at: site) + let x0 = insert(module.makeLLVM(applying: .icmp(.eq, .discriminator), to: [dl, dr], at: site))! + insert(module.makeCondBranch(if: x0, then: same, else: fail, at: site)) + + insertionPoint = .end(of: same) + insert(module.makeSwitch(on: dl, toOneOf: successors, at: site)) + for i in 0 ..< elements.count { + insertionPoint = .end(of: successors[i]) + let y0 = insert(module.makeOpenUnion(lhs, as: elements[i], at: site))! + let y1 = insert(module.makeOpenUnion(rhs, as: elements[i], at: site))! + emitStoreEquality(y0, y1, to: target, at: site) + insert(module.makeCloseUnion(y1, at: site)) + insert(module.makeCloseUnion(y0, at: site)) + insert(module.makeBranch(to: tail, at: site)) + } + + // The failure block writes `false` to the return storage. + insertionPoint = .end(of: fail) + emitStore(boolean: false, to: target, at: site) + insert(module.makeBranch(to: tail, at: site)) + + // The tail block represents the continuation. + insertionPoint = .end(of: tail) + } + // MARK: Helpers /// Returns the canonical form of `t` in the current insertion scope. diff --git a/Sources/IR/Mangling/Mangler.swift b/Sources/IR/Mangling/Mangler.swift index c9a895e6b..7e7e3ae2d 100644 --- a/Sources/IR/Mangling/Mangler.swift +++ b/Sources/IR/Mangling/Mangler.swift @@ -379,11 +379,13 @@ struct Mangler { write(base64Didit: 2, to: &output) case .copy: write(base64Didit: 3, to: &output) - case .globalInitialization(let d): + case .equal: write(base64Didit: 4, to: &output) + case .globalInitialization(let d): + write(base64Didit: 5, to: &output) write(entity: d, to: &output) case .autoclosure(let e): - write(base64Didit: 5, to: &output) + write(base64Didit: 6, to: &output) // To allow using multiple autoclosures in the same scope, also write the expression ID. write(integer: Int(e.rawValue.bits), to: &output) } diff --git a/Sources/IR/Module.swift b/Sources/IR/Module.swift index de45a4335..cfc98e648 100644 --- a/Sources/IR/Module.swift +++ b/Sources/IR/Module.swift @@ -518,6 +518,16 @@ public struct Module { return demandDeclaration(lowering: conformanceToCopyable.implementations[d]!) } + /// Returns the IR function implementing the operator defined in `conformanceToEquatable`. + /// + /// - Parameter conformanceToEquatable: A conformance to `Equatable`. + mutating func demandEqualDeclaration( + definedBy conformanceToEquatable: FrontEnd.Conformance + ) -> Function.ID { + let d = program.ast.core.equatable.equal + return demandDeclaration(lowering: conformanceToEquatable.implementations[d]!) + } + /// Returns a function reference to the implementation of the requirement `r` in `witness`. /// /// - Requires: `r` identifies a function or subscript requirement in the trait for which diff --git a/Sources/IR/Operands/Instruction/UnionDiscriminator.swift b/Sources/IR/Operands/Instruction/UnionDiscriminator.swift index 90b35e998..a2b30b66b 100644 --- a/Sources/IR/Operands/Instruction/UnionDiscriminator.swift +++ b/Sources/IR/Operands/Instruction/UnionDiscriminator.swift @@ -16,7 +16,7 @@ public struct UnionDiscriminator: Instruction { } public var result: IR.`Type`? { - .object(BuiltinType.word) + .object(BuiltinType.discriminator) } public var operands: [Operand] { diff --git a/Tests/EndToEndTests/TestCases/SyntheticEquality.hylo b/Tests/EndToEndTests/TestCases/SyntheticEquality.hylo new file mode 100644 index 000000000..78408699a --- /dev/null +++ b/Tests/EndToEndTests/TestCases/SyntheticEquality.hylo @@ -0,0 +1,28 @@ +//- compileAndRun expecting: .success + +type A: Regular { + public let x: Int + public let y: Int + public memberwise init +} + +type B: Regular { + public let a: A + public memberwise init +} + +typealias IntOrBool = Union + +conformance IntOrBool: Equatable {} + +public fun main() { + precondition(B(a: A(x: 1, y: 2)) == B(a: A(x: 1, y: 2))) + precondition(B(a: A(x: 1, y: 2)) != B(a: A(x: 2, y: 1))) + + let n: IntOrBool = 42 as _ + let m: IntOrBool = 1337 as _ + let b: IntOrBool = true as _ + precondition(n == n) + precondition(n != m) // inequal payloads + precondition(n != b) // inequal discriminators +}