Best Atoum code snippet using generator
CodeGenerators.swift
Source:CodeGenerators.swift
...11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//15// Code generators.16//17// These insert one or more instructions into a program.18//19public let CodeGenerators: [CodeGenerator] = [20// CodeGenerator("IntegerGenerator") { b in21// b.loadInt(b.genInt())22// },23//24// CodeGenerator("BigIntGenerator") { b in25// b.loadBigInt(b.genInt())26// },27//28// CodeGenerator("RegExpGenerator") { b in29// b.loadRegExp(b.genRegExp(), b.genRegExpFlags())30// },31//32// CodeGenerator("FloatGenerator") { b in33// b.loadFloat(b.genFloat())34// },35//36// CodeGenerator("StringGenerator") { b in37// b.loadString(b.genString())38// },39//40// CodeGenerator("BooleanGenerator") { b in41// b.loadBool(Bool.random())42// },43//44// CodeGenerator("UndefinedGenerator") { b in45// b.loadUndefined()46// },47//48// CodeGenerator("NullGenerator") { b in49// b.loadNull()50// },51//52// CodeGenerator("ThisGenerator") { b in53// b.loadThis()54// },55//56// CodeGenerator("ArgumentsGenerator", inContext: .function) { b in57// assert(b.context.contains(.function))58// b.loadArguments()59// },60//61// CodeGenerator("ObjectGenerator") { b in62// var initialProperties = [String: Variable]()63// for _ in 0..<Int.random(in: 0...10) {64// let propertyName = b.genPropertyNameForWrite()65// var type = b.type(ofProperty: propertyName)66// initialProperties[propertyName] = b.randVar(ofType: type) ?? b.generateVariable(ofType: type)67// }68// b.createObject(with: initialProperties)69// },70//71// CodeGenerator("ArrayGenerator") { b in72// var initialValues = [Variable]()73// for _ in 0..<Int.random(in: 0...10) {74// initialValues.append(b.randVar())75// }76// b.createArray(with: initialValues)77// },78//79// CodeGenerator("ObjectWithSpreadGenerator") { b in80// var initialProperties = [String: Variable]()81// var spreads = [Variable]()82// for _ in 0..<Int.random(in: 0...10) {83// withProbability(0.5, do: {84// let propertyName = b.genPropertyNameForWrite()85// var type = b.type(ofProperty: propertyName)86// initialProperties[propertyName] = b.randVar(ofType: type) ?? b.generateVariable(ofType: type)87// }, else: {88// spreads.append(b.randVar())89// })90// }91// b.createObject(with: initialProperties, andSpreading: spreads)92// },93//94// CodeGenerator("ArrayWithSpreadGenerator") { b in95// var initialValues = [Variable]()96// for _ in 0..<Int.random(in: 0...10) {97// initialValues.append(b.randVar())98// }99//100// // Pick some random inputs to spread.101// let spreads = initialValues.map({ el in102// probability(0.75) && b.type(of: el).Is(.iterable)103// })104//105// b.createArray(with: initialValues, spreading: spreads)106// },107//108// CodeGenerator("TemplateStringGenerator") { b in109// var interpolatedValues = [Variable]()110// for _ in 1..<Int.random(in: 1...5) {111// interpolatedValues.append(b.randVar())112// }113//114// var parts = [String]()115// for _ in 0...interpolatedValues.count {116// // For now we generate random strings117// parts.append(b.genString())118// }119// b.createTemplateString(from: parts, interpolating: interpolatedValues)120// },121//122// CodeGenerator("BuiltinGenerator") { b in123// b.loadBuiltin(b.genBuiltinName())124// },125//126// // For functions, we always generate one random instruction and one return instruction as function body.127// // This ensures that generating one random instruction does not accidentially generate multiple instructions128// // (which increases the likelyhood of runtime exceptions), but also generates somewhat useful functions.129//130// CodeGenerator("PlainFunctionGenerator") { b in131// b.definePlainFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in132// b.generateRecursive()133// b.doReturn(value: b.randVar())134// }135// },136//137// CodeGenerator("ArrowFunctionGenerator") { b in138// b.defineArrowFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in139// b.generateRecursive()140// b.doReturn(value: b.randVar())141// }142// },143//144// CodeGenerator("GeneratorFunctionGenerator") { b in145// b.defineGeneratorFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in146// b.generateRecursive()147// if probability(0.5) {148// b.yield(value: b.randVar())149// } else {150// b.yieldEach(value: b.randVar())151// }152// b.doReturn(value: b.randVar())153// }154// },155//156// CodeGenerator("AsyncFunctionGenerator") { b in157// b.defineAsyncFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in158// b.generateRecursive()159// b.await(value: b.randVar())160// b.doReturn(value: b.randVar())161// }162// },163//164// CodeGenerator("AsyncArrowFunctionGenerator") { b in165// b.defineAsyncArrowFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in166// b.generateRecursive()167// b.await(value: b.randVar())168// b.doReturn(value: b.randVar())169// }170// },171//172// CodeGenerator("AsyncGeneratorFunctionGenerator") { b in173// b.defineAsyncGeneratorFunction(withSignature: FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1)), isStrict: probability(0.1)) { _ in174// b.generateRecursive()175// b.await(value: b.randVar())176// if probability(0.5) {177// b.yield(value: b.randVar())178// } else {179// b.yieldEach(value: b.randVar())180// }181// b.doReturn(value: b.randVar())182// }183// },184//185// CodeGenerator("PropertyRetrievalGenerator", input: .object()) { b, obj in186// let propertyName = b.type(of: obj).randomProperty() ?? b.genPropertyNameForRead()187// b.loadProperty(propertyName, of: obj)188// },189//190// CodeGenerator("PropertyAssignmentGenerator", input: .object()) { b, obj in191// let propertyName: String192// // Either change an existing property or define a new one193// if probability(0.5) {194// propertyName = b.type(of: obj).randomProperty() ?? b.genPropertyNameForWrite()195// } else {196// propertyName = b.genPropertyNameForWrite()197// }198// var propertyType = b.type(ofProperty: propertyName)199// let value = b.randVar(ofType: propertyType) ?? b.generateVariable(ofType: propertyType)200// b.storeProperty(value, as: propertyName, on: obj)201// },202//203// CodeGenerator("StorePropertyWithBinopGenerator", input: .object()) { b, obj in204// let propertyName: String205// // Change an existing property206// propertyName = b.type(of: obj).randomProperty() ?? b.genPropertyNameForWrite()207//208// var propertyType = b.type(ofProperty: propertyName)209// let value = b.randVar(ofType: propertyType) ?? b.generateVariable(ofType: propertyType)210// b.storeProperty(value, as: propertyName, with: chooseUniform(from: allBinaryOperators), on: obj)211// },212//213// CodeGenerator("PropertyRemovalGenerator", input: .object()) { b, obj in214// let propertyName = b.type(of: obj).randomProperty() ?? b.genPropertyNameForWrite()215// b.deleteProperty(propertyName, of: obj)216// },217//218// CodeGenerator("ElementRetrievalGenerator", input: .object()) { b, obj in219// let index = b.genIndex()220// b.loadElement(index, of: obj)221// },222//223// CodeGenerator("ElementAssignmentGenerator", input: .object()) { b, obj in224// let index = b.genIndex()225// let value = b.randVar()226// b.storeElement(value, at: index, of: obj)227// },228//229// CodeGenerator("StoreElementWithBinopGenerator", input: .object()) { b, obj in230// let index = b.genIndex()231// let value = b.randVar()232// b.storeElement(value, at: index, with: chooseUniform(from: allBinaryOperators), of: obj)233// },234//235// CodeGenerator("ElementRemovalGenerator", input: .object()) { b, obj in236// let index = b.genIndex()237// b.deleteElement(index, of: obj)238// },239//240// CodeGenerator("ComputedPropertyRetrievalGenerator", input: .object()) { b, obj in241// let propertyName = b.randVar()242// b.loadComputedProperty(propertyName, of: obj)243// },244//245// CodeGenerator("ComputedPropertyAssignmentGenerator", input: .object()) { b, obj in246// let propertyName = b.randVar()247// let value = b.randVar()248// b.storeComputedProperty(value, as: propertyName, on: obj)249// },250//251// CodeGenerator("StoreComputedPropertyWithBinopGenerator", input: .object()) { b, obj in252// let propertyName = b.randVar()253// let value = b.randVar()254// b.storeComputedProperty(value, as: propertyName, with: chooseUniform(from: allBinaryOperators), on: obj)255// },256//257// CodeGenerator("ComputedPropertyRemovalGenerator", input: .object()) { b, obj in258// let propertyName = b.randVar()259// b.deleteComputedProperty(propertyName, of: obj)260// },261//262// CodeGenerator("TypeTestGenerator", input: .anything) { b, val in263// let type = b.doTypeof(val)264// // Also generate a comparison here, since that's probably the only interesting thing you can do with the result.265// let rhs = b.loadString(chooseUniform(from: JavaScriptEnvironment.jsTypeNames))266// b.compare(type, rhs, with: .strictEqual)267// },268//269// CodeGenerator("InstanceOfGenerator", inputs: (.anything, .function() | .constructor())) { b, val, cls in270// b.doInstanceOf(val, cls)271// },272//273// CodeGenerator("InGenerator", input: .object()) { b, obj in274// let prop = b.randVar()275// b.doIn(prop, obj)276// },277//278 CodeGenerator("MethodCallGenerator", input: .object()) { b, obj in279 var methodName = b.type(of: obj).randomMethod()280 if methodName == nil {281 guard b.mode != .conservative else { return }282 methodName = b.genMethodName()283 }284 guard let arguments = b.randCallArguments(forMethod: methodName!, on: obj) else { return }285 b.callMethod(methodName!, on: obj, withArgs: arguments)286 },287//288// CodeGenerator("MethodCallWithSpreadGenerator", input: .object()) { b, obj in289// // We cannot currently track element types of Arrays and other Iterable objects and so cannot properly determine argument types when spreading.290// // For that reason, we don't run this CodeGenerator in conservative mode291// guard b.mode != .conservative else { return }292//293// var methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()294//295// let (arguments, spreads) = b.randCallArgumentsWithSpreading(n: Int.random(in: 3...5))296//297// b.callMethod(methodName, on: obj, withArgs: arguments, spreading: spreads)298// },299//300// CodeGenerator("ComputedMethodCallGenerator", input: .object()) { b, obj in301// var methodName = b.type(of: obj).randomMethod()302// if methodName == nil {303// guard b.mode != .conservative else { return }304// methodName = b.genMethodName()305// }306// let method = b.loadString(methodName!)307// guard let arguments = b.randCallArguments(forMethod: methodName!, on: obj) else { return }308// b.callComputedMethod(method, on: obj, withArgs: arguments)309// },310//311// CodeGenerator("ComputedMethodCallWithSpreadGenerator", input: .object()) { b, obj in312// // We cannot currently track element types of Arrays and other Iterable objects and so cannot properly determine argument types when spreading.313// // For that reason, we don't run this CodeGenerator in conservative mode314// guard b.mode != .conservative else { return }315//316// var methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()317// let method = b.loadString(methodName)318//319// let (arguments, spreads) = b.randCallArgumentsWithSpreading(n: Int.random(in: 3...5))320//321// b.callComputedMethod(method, on: obj, withArgs: arguments, spreading: spreads)322// },323//324// CodeGenerator("FunctionCallGenerator", input: .function()) { b, f in325// guard let arguments = b.randCallArguments(for: f) else { return }326// b.callFunction(f, withArgs: arguments)327// },328//329 CodeGenerator("ConstructorCallGenerator", input: .constructor()) { b, c in330 guard let arguments = b.randCallArguments(for: c) else { return }331 b.construct(c, withArgs: arguments)332 },333//334// CodeGenerator("FunctionCallWithSpreadGenerator", input: .function()) { b, f in335// // We cannot currently track element types of Arrays and other Iterable objects and so cannot properly determine argument types when spreading.336// // For that reason, we don't run this CodeGenerator in conservative mode337// guard b.mode != .conservative else { return }338//339// let (arguments, spreads) = b.randCallArgumentsWithSpreading(n: Int.random(in: 3...5))340//341// b.callFunction(f, withArgs: arguments, spreading: spreads)342// },343//344// CodeGenerator("ConstructorCallWithSpreadGenerator", input: .constructor()) { b, c in345// // We cannot currently track element types of Arrays and other Iterable objects and so cannot properly determine argument types when spreading.346// // For that reason, we don't run this CodeGenerator in conservative mode347// guard b.mode != .conservative else { return }348//349// let (arguments, spreads) = b.randCallArgumentsWithSpreading(n: Int.random(in: 3...5))350//351// b.construct(c, withArgs: arguments, spreading: spreads)352// },353//354// CodeGenerator("FunctionReturnGenerator", inContext: .function, input: .anything) { b, val in355// assert(b.context.contains(.function))356// b.doReturn(value: val)357// },358//359// CodeGenerator("YieldGenerator", inContext: .generatorFunction, input: .anything) { b, val in360// assert(b.context.contains(.generatorFunction))361// if probability(0.5) {362// b.yield(value: val)363// } else {364// b.yieldEach(value: val)365// }366// },367//368// CodeGenerator("AwaitGenerator", inContext: .asyncFunction, input: .anything) { b, val in369// assert(b.context.contains(.asyncFunction))370// b.await(value: val)371// },372//373// CodeGenerator("UnaryOperationGenerator", input: .anything) { b, val in374// b.unary(chooseUniform(from: allUnaryOperators), val)375// },376//377// CodeGenerator("BinaryOperationGenerator", inputs: (.anything, .anything)) { b, lhs, rhs in378// b.binary(lhs, rhs, with: chooseUniform(from: allBinaryOperators))379// },380//381// CodeGenerator("ReassignWithBinopGenerator", input: .anything) { b, val in382// let target = b.randVar()383// b.reassign(target, to: val, with: chooseUniform(from: allBinaryOperators))384// },385//386// CodeGenerator("DupGenerator") { b in387// b.dup(b.randVar())388// },389//390// CodeGenerator("ReassignmentGenerator", input: .anything) { b, val in391// let target = b.randVar()392// b.reassign(target, to: val)393// },394//395// CodeGenerator("DestructArrayGenerator", input: .iterable) { b, arr in396// // Fuzzilli generated arrays can have a length ranging from 0 to 10 elements,397// // We want to ensure that 1) when destructing arrays we are usually within this length range398// // and 2) The probability with which we select indices allows defining atleast 2-3 variables.399// var indices: [Int] = []400// for idx in 0..<Int.random(in: 0..<5) {401// withProbability(0.7) {402// indices.append(idx)403// }404// }405//406// b.destruct(arr, selecting: indices, hasRestElement: probability(0.2))407// },408//409// CodeGenerator("DestructArrayAndReassignGenerator", input: .iterable) {b, arr in410// var candidates: [Variable] = []411// var indices: [Int] = []412// for idx in 0..<Int.random(in: 0..<5) {413// withProbability(0.7) {414// indices.append(idx)415// candidates.append(b.randVar())416// }417// }418// b.destruct(arr, selecting: indices, into: candidates, hasRestElement: probability(0.2))419// },420//421// CodeGenerator("DestructObjectGenerator", input: .object()) { b, obj in422// var properties = Set<String>()423// for _ in 0..<Int.random(in: 2...6) {424// if let prop = b.type(of: obj).properties.randomElement(), !properties.contains(prop) {425// properties.insert(prop)426// } else {427// properties.insert(b.genPropertyNameForRead())428// }429// }430//431// let hasRestElement = probability(0.2)432//433// b.destruct(obj, selecting: properties.sorted(), hasRestElement: hasRestElement)434// },435//436// CodeGenerator("DestructObjectAndReassignGenerator", input: .object()) { b, obj in437// var properties = Set<String>()438// for _ in 0..<Int.random(in: 2...6) {439// if let prop = b.type(of: obj).properties.randomElement(), !properties.contains(prop) {440// properties.insert(prop)441// } else {442// properties.insert(b.genPropertyNameForRead())443// }444// }445//446// var candidates = properties.map{ _ in447// b.randVar()448// }449//450// let hasRestElement = probability(0.2)451// if hasRestElement {452// candidates.append(b.randVar())453// }454//455// b.destruct(obj, selecting: properties.sorted(), into: candidates, hasRestElement: hasRestElement)456// },457//458// CodeGenerator("ComparisonGenerator", inputs: (.anything, .anything)) { b, lhs, rhs in459// b.compare(lhs, rhs, with: chooseUniform(from: allComparators))460// },461//462// CodeGenerator("ConditionalOperationGenerator", inputs: (.anything, .anything)) { b, lhs, rhs in463// let condition = b.compare(lhs, rhs, with: chooseUniform(from: allComparators))464// b.conditional(condition, lhs, rhs)465// },466//467// CodeGenerator("ClassGenerator") { b in468// // Possibly pick a superclass469// var superclass: Variable? = nil470// if probability(0.5) {471// superclass = b.randVar(ofConservativeType: .constructor())472// }473//474// b.defineClass(withSuperclass: superclass) { cls in475// // TODO generate parameter types in a better way476// let constructorParameters = FunctionSignature(withParameterCount: Int.random(in: 1...3)).parameters477// cls.defineConstructor(withParameters: constructorParameters) { _ in478// // Must call the super constructor if there is a superclass479// if let superConstructor = superclass {480// let arguments = b.randCallArguments(for: superConstructor) ?? []481// b.callSuperConstructor(withArgs: arguments)482// }483//484// b.generateRecursive()485// }486//487// let numProperties = Int.random(in: 1...3)488// for _ in 0..<numProperties {489// cls.defineProperty(b.genPropertyNameForWrite())490// }491//492// let numMethods = Int.random(in: 1...3)493// for _ in 0..<numMethods {494// cls.defineMethod(b.genMethodName(), withSignature: FunctionSignature(withParameterCount: Int.random(in: 1...3), hasRestParam: probability(0.1))) { _ in495// b.generateRecursive()496// }497// }498// }499// },500//501// CodeGenerator("SuperMethodCallGenerator", inContext: .classDefinition) { b in502// let superType = b.currentSuperType()503// var methodName = superType.randomMethod()504// if methodName == nil {505// guard b.mode != .conservative else { return }506// methodName = b.genMethodName()507// }508// guard let arguments = b.randCallArguments(forMethod: methodName!, on: superType) else { return }509// b.callSuperMethod(methodName!, withArgs: arguments)510// },511//512// // Loads a property on the super object513// CodeGenerator("LoadSuperPropertyGenerator", inContext: .classDefinition) { b in514// let superType = b.currentSuperType()515// // Emit a property load516// let propertyName = superType.randomProperty() ?? b.genPropertyNameForRead()517// b.loadSuperProperty(propertyName)518// },519//520// // Stores a property on the super object521// CodeGenerator("StoreSuperPropertyGenerator", inContext: .classDefinition) { b in522// let superType = b.currentSuperType()523// // Emit a property store524// let propertyName: String525// // Either change an existing property or define a new one526// if probability(0.5) {527// propertyName = superType.randomProperty() ?? b.genPropertyNameForWrite()528// } else {529// propertyName = b.genPropertyNameForWrite()530// }531// var propertyType = b.type(ofProperty: propertyName)532// // TODO unify the .unknown => .anything conversion533// if propertyType == .unknown {534// propertyType = .anything535// }536// let value = b.randVar(ofType: propertyType) ?? b.generateVariable(ofType: propertyType)537// b.storeSuperProperty(value, as: propertyName)538// },539//540// // Stores a property with a binary operation on the super object541// CodeGenerator("StoreSuperPropertyWithBinopGenerator", inContext: .classDefinition) { b in542// let superType = b.currentSuperType()543// // Emit a property store544// let propertyName = superType.randomProperty() ?? b.genPropertyNameForWrite()545//546// var propertyType = b.type(ofProperty: propertyName)547// // TODO unify the .unknown => .anything conversion548// if propertyType == .unknown {549// propertyType = .anything550// }551// let value = b.randVar(ofType: propertyType) ?? b.generateVariable(ofType: propertyType)552// b.storeSuperProperty(value, as: propertyName, with: chooseUniform(from: allBinaryOperators))553// },554//555// CodeGenerator("IfElseGenerator", input: .boolean) { b, cond in556// b.beginIf(cond) {557// b.generateRecursive()558// }559// b.beginElse() {560// b.generateRecursive()561// }562// b.endIf()563// },564//565// CodeGenerator("SwitchCaseGenerator", input: .anything) { b, cond in566// var candidates: [Variable] = []567//568// // Generate a minimum of three cases (including a potential default case)569// for _ in 0..<Int.random(in: 3...8) {570// candidates.append(b.randVar())571// }572//573// // If this is set, the selected candidate becomes the default case574// var defaultCasePosition = -1575// if probability(0.8) {576// defaultCasePosition = Int.random(in: 0..<candidates.count)577// }578//579// b.doSwitch(on: cond) { cases in580// for (idx, val) in candidates.enumerated() {581// if idx == defaultCasePosition {582// cases.addDefault(previousCaseFallsThrough: probability(0.1)) {583// b.generateRecursive()584// }585// } else {586// cases.add(val, previousCaseFallsThrough: probability(0.1)) {587// b.generateRecursive()588// }589// }590// }591// }592// },593//594// CodeGenerator("SwitchCaseBreakGenerator", inContext: .switchCase) { b in595// b.switchBreak()596// },597//598// CodeGenerator("WhileLoopGenerator") { b in599// let loopVar = b.reuseOrLoadInt(0)600// let end = b.reuseOrLoadInt(Int64.random(in: 0...10))601// b.whileLoop(loopVar, .lessThan, end) {602// b.generateRecursive()603// b.unary(.PostInc, loopVar)604// }605// },606//607// CodeGenerator("DoWhileLoopGenerator") { b in608// let loopVar = b.reuseOrLoadInt(0)609// let end = b.reuseOrLoadInt(Int64.random(in: 0...10))610// b.doWhileLoop(loopVar, .lessThan, end) {611// b.generateRecursive()612// b.unary(.PostInc, loopVar)613// }614// },615//616// CodeGenerator("ForLoopGenerator") { b in617// let start = b.reuseOrLoadInt(0)618// let end = b.reuseOrLoadInt(Int64.random(in: 0...10))619// let step = b.reuseOrLoadInt(1)620// b.forLoop(start, .lessThan, end, .Add, step) { _ in621// b.generateRecursive()622// }623// },624//625// CodeGenerator("ForInLoopGenerator", input: .object()) { b, obj in626// b.forInLoop(obj) { _ in627// b.generateRecursive()628// }629// },630//631// CodeGenerator("ForOfLoopGenerator", input: .iterable) { b, obj in632// b.forOfLoop(obj) { _ in633// b.generateRecursive()634// }635// },636//637// CodeGenerator("ForOfWithDestructLoopGenerator", input: .iterable) { b, obj in638// // Don't run this generator in conservative mode, until we can track array element types639// guard b.mode != .conservative else { return }640// var indices: [Int] = []641// for idx in 0..<Int.random(in: 1..<5) {642// withProbability(0.8) {643// indices.append(idx)644// }645// }646//647// if indices.isEmpty {648// indices = [0]649// }650//651// b.forOfLoop(obj, selecting: indices, hasRestElement: probability(0.2)) { _ in652// b.generateRecursive()653// }654// },655//656// CodeGenerator("LoopBreakGenerator", inContext: .loop) { b in657// b.loopBreak()658// },659//660// CodeGenerator("ContinueGenerator", inContext: .loop) { b in661// assert(b.context.contains(.loop))662// b.doContinue()663// },664//665// CodeGenerator("TryCatchGenerator") { b in666// b.beginTry() {667// b.generateRecursive()668// }669// withEqualProbability({670// // try-catch-finally671// b.beginCatch() { _ in672// b.generateRecursive()673// }674// b.beginFinally() {675// b.generateRecursive()676// }677// }, {678// // try-catch679// b.beginCatch() { _ in680// b.generateRecursive()681// }682// }, {683// // try-finally684// b.beginFinally() {685// b.generateRecursive()686// }687// })688// b.endTryCatch()689// },690//691// CodeGenerator("ThrowGenerator") { b in692// let v = b.randVar()693// b.throwException(v)694// },695//696// //697// // Language-specific Generators698// //699//700// CodeGenerator("TypedArrayGenerator") { b in701// let size = b.loadInt(Int64.random(in: 0...0x10000))702// let constructor = b.reuseOrLoadBuiltin(703// chooseUniform(704// from: ["Uint8Array", "Int8Array", "Uint16Array", "Int16Array", "Uint32Array", "Int32Array", "Float32Array", "Float64Array", "Uint8ClampedArray"]705// )706// )707// b.construct(constructor, withArgs: [size])708// },709//710// CodeGenerator("FloatArrayGenerator") { b in711// let value = b.reuseOrLoadAnyFloat()712// b.createArray(with: Array(repeating: value, count: Int.random(in: 1...5)))713// },714//715// CodeGenerator("IntArrayGenerator") { b in716// let value = b.reuseOrLoadAnyInt()717// b.createArray(with: Array(repeating: value, count: Int.random(in: 1...5)))718// },719//720// CodeGenerator("ObjectArrayGenerator") { b in721// let value = b.createObject(with: [:])722// b.createArray(with: Array(repeating: value, count: Int.random(in: 1...5)))723// },724//725// CodeGenerator("WellKnownPropertyLoadGenerator", input: .object()) { b, obj in726// let Symbol = b.reuseOrLoadBuiltin("Symbol")727// let name = chooseUniform(from: ["isConcatSpreadable", "iterator", "match", "replace", "search", "species", "split", "toPrimitive", "toStringTag", "unscopables"])728// let pname = b.loadProperty(name, of: Symbol)729// b.loadComputedProperty(pname, of: obj)730// },731//732// CodeGenerator("WellKnownPropertyStoreGenerator", input: .object()) { b, obj in733// let Symbol = b.reuseOrLoadBuiltin("Symbol")734// let name = chooseUniform(from: ["isConcatSpreadable", "iterator", "match", "replace", "search", "species", "split", "toPrimitive", "toStringTag", "unscopables"])735// let pname = b.loadProperty(name, of: Symbol)736// let val = b.randVar()737// b.storeComputedProperty(val, as: pname, on: obj)738// },739//740// CodeGenerator("PrototypeAccessGenerator", input: .object()) { b, obj in741// b.loadProperty("__proto__", of: obj)742// },743//744// CodeGenerator("PrototypeOverwriteGenerator", inputs: (.object(), .object())) { b, obj, proto in745// b.storeProperty(proto, as: "__proto__", on: obj)746// },747//748// CodeGenerator("CallbackPropertyGenerator", inputs: (.object(), .function())) { b, obj, callback in749// // TODO add new callbacks like Symbol.toPrimitive?750// let propertyName = chooseUniform(from: ["valueOf", "toString"])751// b.storeProperty(callback, as: propertyName, on: obj)752// },753//754// CodeGenerator("PropertyAccessorGenerator", input: .object()) { b, obj in755// let propertyName = probability(0.5) ? b.loadString(b.genPropertyNameForWrite()) : b.loadInt(b.genIndex())756//757// var initialProperties = [String: Variable]()758// withEqualProbability({759// guard let getter = b.randVar(ofType: .function()) else { return }760// initialProperties["get"] = getter761// }, {762// guard let setter = b.randVar(ofType: .function()) else { return }763// initialProperties["set"] = setter764// }, {765// guard let getter = b.randVar(ofType: .function()) else { return }766// guard let setter = b.randVar(ofType: .function()) else { return }767// initialProperties["get"] = getter768// initialProperties["set"] = setter769// })770// let descriptor = b.createObject(with: initialProperties)771//772// let object = b.reuseOrLoadBuiltin("Object")773// b.callMethod("defineProperty", on: object, withArgs: [obj, propertyName, descriptor])774// },775//776// CodeGenerator("MethodCallWithDifferentThisGenerator", inputs: (.object(), .object())) { b, obj, this in777// var methodName = b.type(of: obj).randomMethod()778// if methodName == nil {779// guard b.mode != .conservative else { return }780// methodName = b.genMethodName()781// }782// guard let arguments = b.randCallArguments(forMethod: methodName!, on: obj) else { return }783// let Reflect = b.reuseOrLoadBuiltin("Reflect")784// let args = b.createArray(with: arguments)785// b.callMethod("apply", on: Reflect, withArgs: [b.loadProperty(methodName!, of: obj), this, args])786// },787//788// CodeGenerator("ProxyGenerator", input: .object()) { b, target in789// var candidates = Set(["getPrototypeOf", "setPrototypeOf", "isExtensible", "preventExtensions", "getOwnPropertyDescriptor", "defineProperty", "has", "get", "set", "deleteProperty", "ownKeys", "apply", "call", "construct"])790//791// var handlerProperties = [String: Variable]()792// for _ in 0..<Int.random(in: 0..<candidates.count) {793// let hook = chooseUniform(from: candidates)794// candidates.remove(hook)795// handlerProperties[hook] = b.randVar(ofType: .function())796// }797// let handler = b.createObject(with: handlerProperties)798//799// let Proxy = b.reuseOrLoadBuiltin("Proxy")800//801// b.construct(Proxy, withArgs: [target, handler])802// },803//804// CodeGenerator("PromiseGenerator") { b in805// // This is just so the variables have the correct type.806// let resolveFunc = b.definePlainFunction(withSignature: [.plain(.anything)] => .unknown) { _ in }807// let rejectFunc = b.dup(resolveFunc)808// let handlerSignature = [.plain(.function([.plain(.anything)] => .unknown)), .plain(.function([.plain(.anything)] => .unknown))] => .unknown809// let handler = b.definePlainFunction(withSignature: handlerSignature) { args in810// b.reassign(resolveFunc, to: args[0])811// b.reassign(rejectFunc, to: args[1])812// }813// let promiseConstructor = b.reuseOrLoadBuiltin("Promise")814// b.construct(promiseConstructor, withArgs: [handler])815// },816//817// // Tries to change the length property of some object818// CodeGenerator("LengthChangeGenerator", input: .object()) { b, obj in819// let newLength: Variable820// if probability(0.5) {821// // Shrink822// newLength = b.reuseOrLoadInt(Int64.random(in: 0..<3))823// } else {824// // (Probably) grow825// newLength = b.reuseOrLoadInt(b.genIndex())826// }827// b.storeProperty(newLength, as: "length", on: obj)828// },829//830// // Tries to change the element kind of an array831// CodeGenerator("ElementKindChangeGenerator", input: .object()) { b, obj in832// let value = b.randVar()833// b.storeElement(value, at: Int64.random(in: 0..<10), of: obj)834// },835//836// // Generates a JavaScript 'with' statement837// CodeGenerator("WithStatementGenerator", input: .object()) { b, obj in838// b.with(obj) {839// withProbability(0.5, do: { () -> Void in840// b.loadFromScope(id: b.genPropertyNameForRead())841// }, else: { () -> Void in842// let value = b.randVar()843// b.storeToScope(value, as: b.genPropertyNameForWrite())844// })845// b.generateRecursive()846// }847// },848//849// CodeGenerator("LoadFromScopeGenerator", inContext: .with) { b in850// assert(b.context.contains(.with))851// b.loadFromScope(id: b.genPropertyNameForRead())852// },853//854// CodeGenerator("StoreToScopeGenerator", inContext: .with) { b in855// assert(b.context.contains(.with))856// let value = b.randVar()857// b.storeToScope(value, as: b.genPropertyNameForWrite())858// },859//860// CodeGenerator("EvalGenerator") { b in861// let code = b.codeString() {862// b.generateRecursive()863// }864// let eval = b.reuseOrLoadBuiltin("eval")865// b.callFunction(eval, withArgs: [code])866// },867//868// CodeGenerator("BlockStatementGenerator") { b in869// b.blockStatement(){870// b.generateRecursive()871// }872// },873// CodeGenerator("MathOperationGenerator") { b in874// let Math = b.reuseOrLoadBuiltin("Math")875// // This can fail in tests, which lack the full JavaScriptEnvironment876// guard let method = b.type(of: Math).randomMethod() else { return }877// let args = b.generateCallArguments(forMethod: method, on: Math)878// b.callMethod(method, on: Math, withArgs: args)879// },880 881 //882 // BEGIN WASM FEATURE883 //884 885 CodeGenerator("GlobalDescriptorIntObjectGenerator") { b in886 var initialProperties = [String: Variable]()887 initialProperties = ["value": Bool.random() ? b.loadString("i32") : b.loadString("i64"), "mutable": Bool.random() ? b.loadString("true"): b.loadString("false")]888 889 let GlobalDescriptorIntObject = b.createObject(with: initialProperties)890 b.alter(GlobalDescriptorIntObject, "GlobalDescriptorIntObject")891 },892 893 CodeGenerator("GlobalDescriptorFloatObjectGenerator") { b in894 var initialProperties = [String: Variable]()895 initialProperties = ["value": Bool.random() ? b.loadString("f32") : b.loadString("f64"), "mutable": Bool.random() ? b.loadString("true"): b.loadString("false")]896 897 let GlobalDescriptorFloatObject = b.createObject(with: initialProperties)898 b.alter(GlobalDescriptorFloatObject, "GlobalDescriptorFloatObject")899 },900 901 CodeGenerator("TableDescriptorObjectGenerator") { b in902 var initialProperties = [String: Variable]()903 904 withEqualProbability({905 initialProperties = ["element": b.loadString("anyfunc"), "initial": b.loadString(String(CInt.random(in: 0...42)))]906 }, {907 initialProperties = ["element": b.loadString("anyfunc"), "initial": b.loadString(String(CInt.random(in: 0...42))), "maximum": b.loadString(String(CInt.random(in: 43...99)))]908 })909 910 let TableDescriptorObject = b.createObject(with: initialProperties)911 b.alter(TableDescriptorObject, "TableDescriptorObject")912 },913 914 CodeGenerator("MemoryDescriptorObjectGenerator") { b in915 var initialProperties = [String: Variable]()916 917 withEqualProbability({918 initialProperties = ["initial": b.loadString(String(CInt.random(in: 0...9)))]919 }, {920 initialProperties = ["initial": b.loadString(String(CInt.random(in: 0...9))), "maximum": b.loadString(String(Int.random(in: 9...999)))]921 })922 923 let MemoryDescriptorObject = b.createObject(with: initialProperties)924 b.alter(MemoryDescriptorObject, "MemoryDescriptorObject")925 },926 927 CodeGenerator("GlobalWasmFloatObjectGenerator", input: .GlobalDescriptorFloatObject) { b, obj in928 var arguments = [Variable]()929 arguments = [obj, b.loadFloat(b.genFloat())]930 let constructor = b.loadBuiltin("WebAssembly.Global") //type: GlobalWasmConstructor931 b.construct(constructor, withArgs: arguments)932 },933 934 CodeGenerator("GlobalWasmIntObjectGenerator", input: .GlobalDescriptorIntObject) { b, obj in935 var arguments = [Variable]()936 arguments = [obj, b.loadInt(b.genInt())]937 let constructor = b.loadBuiltin("WebAssembly.Global") //type: GlobalWasmConstructor938 b.construct(constructor, withArgs: arguments)939 },940 941 CodeGenerator("TableWasmObjectGenerator", input: .TableDescriptorObject) { b, obj in942 var arguments = [Variable]()943 arguments = [obj]944 let constructor = b.loadBuiltin("WebAssembly.Table")945 b.construct(constructor, withArgs: arguments)946 },947 948 CodeGenerator("MemoryWasmObjectGenerator", input: .MemoryDescriptorObject) { b, obj in949 var arguments = [Variable]()950 arguments = [obj]951 let constructor = b.loadBuiltin("WebAssembly.Memory")952 b.construct(constructor, withArgs: arguments)953 },954 CodeGenerator("ModuleWasmObjectGenerator", input: .jsTypedArray("Uint8Array")) { b, obj in955 var arguments = [Variable]()956 arguments = [obj]957 let constructor = b.loadBuiltin("WebAssembly.Module")958 b.construct(constructor, withArgs: arguments)959 },960 961 CodeGenerator("InstanceWasmObjectGenerator", inputs: (.ModuleWasmObject, .ImportObject)) { b, obj1, obj2 in962 var arguments = [Variable]()963 arguments = [obj1, obj2]964 let constructor = b.loadBuiltin("WebAssembly.Instance")965 b.construct(constructor, withArgs: arguments)966 },967 968 CodeGenerator("ImportObjectGenerator") { b in969 var initialProperties = [String: Variable]()970 withEqualProbability({971 initialProperties = [:]972 }, {973 let MemoryWasmObject = b.generalWasmObject(.MemoryWasmObject)974 initialProperties = ["mem": MemoryWasmObject]975 initialProperties = ["js": b.createObject(with: initialProperties)]976 }, {977 let TableWasmObject = b.generalWasmObject(.TableWasmObject)978 initialProperties = ["tbl": TableWasmObject]979 initialProperties = ["js": b.createObject(with: initialProperties)]980 })981 let o = b.createObject(with: initialProperties)982 b.alter(o, "ImportObject")983 },984 985 CodeGenerator("FuncRefObjectGenerator", input: .TableWasmObject) { b, obj in986 var arguments = [Variable]()987 arguments = [b.loadInt(Int64(Int.random(in: 0...42)))]988 b.callMethod("get", on: obj, withArgs: arguments)989 },990 991 CodeGenerator("BufferSourceGenerator") { b in992 let buffer = [0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,3,130,128,128,128,0,1,0,4,132,128,128,128,0,1,112,0,0,5,131,128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,145,128,128,128,0,2,6,109,101,109,111,114,121,2,0,4,109,97,105,110,0,0,10,138,128,128,128,0,1,132,128,128,128,0,0,65,42,11]993 var initialValues = [Variable]()994 for index in 0..<buffer.count {995 initialValues.append(b.loadInt(Int64(buffer[index])))996 }997 let AlterableArray = b.createArray(with: initialValues)998 let constructor = b.loadBuiltin("Uint8Array")999 b.construct(constructor, withArgs: [AlterableArray])1000 },1001 1002 CodeGenerator("GlobalWasmObjectCallGenerator", input: .GlobalWasmObject) { b, obj in1003 let methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()1004 let arguments = b.generateCallArguments(forMethod: methodName, on: obj)1005 b.callMethod(methodName, on: obj, withArgs: arguments)1006 },1007 1008 CodeGenerator("TableWasmObjectCallGenerator", input: .TableWasmObject) { b, obj in1009 let methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()1010 let arguments:[Variable]1011 1012 switch methodName {1013 case "get":1014 arguments = [b.loadInt(Int64(Int.random(in: 0...42)))]1015 case "grow":1016 arguments = [b.loadInt(Int64(Int.random(in: 0...42)))]1017 default:1018 arguments = b.generateCallArguments(forMethod: methodName, on: obj)1019 }1020 1021 b.callMethod(methodName, on: obj, withArgs: arguments)1022 },1023 1024 CodeGenerator("MemoryWasmObjectCallGenerator", input: .MemoryWasmObject) { b, obj in1025 let methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()1026 let arguments = b.generateCallArguments(forMethod: methodName, on: obj)1027 b.callMethod(methodName, on: obj, withArgs: arguments)1028 },1029 1030 CodeGenerator("InstanceWasmObjectCallGenerator", input: .InstanceWasmObject) { b, obj in1031 let methodName = b.type(of: obj).randomMethod() ?? b.genMethodName()1032 let arguments = b.generateCallArguments(forMethod: methodName, on: obj)1033 b.callMethod(methodName, on: obj, withArgs: arguments)1034 },1035 1036 CodeGenerator("ModuleConstructorWasmObjectCallGenerator") { b in1037 let Module = b.reuseOrLoadBuiltin("WebAssembly.Module")1038 guard let method = b.type(of: Module).randomMethod() else { return }1039 let args = b.generateCallArguments(forMethod: method, on: Module)1040 b.callMethod(method, on: Module, withArgs: args)1041 },1042 1043 CodeGenerator("WasmObjectCallGenerator") { b in1044 let Module = b.reuseOrLoadBuiltin("WebAssembly")1045 guard let method = b.type(of: Module).randomMethod() else { return }1046 let args = b.generateCallArguments(forMethod: method, on: Module)1047 b.callMethod(method, on: Module, withArgs: args)1048 },1049 1050 1051 //1052 // END WASM FEATURE1053 //1054]1055extension Array where Element == CodeGenerator {1056 public func get(_ name: String) -> CodeGenerator {1057 for generator in self {1058 if generator.name == name {1059 return generator1060 }1061 }1062 fatalError("Unknown code generator \(name)")1063 }1064}...
FeedbackManager.swift
Source:FeedbackManager.swift
...45 case heavy = 152146 }47 48 private var style: Style = .light49 private var generator: Any? = Impact.make(.light)50 51 private static func make(_ style: Style) -> Any? {52 guard _enabled else { return nil }53 if device.feedbackLevel == .improved {54 guard #available(iOS 10.0, *) else { return nil }55 let feedbackStyle: UIImpactFeedbackGenerator.FeedbackStyle56 switch style {57 case .light:58 feedbackStyle = .light59 case .medium:60 feedbackStyle = .medium61 case .heavy:62 feedbackStyle = .heavy63 }64 let generator = UIImpactFeedbackGenerator(style: feedbackStyle)65 generator.prepare()66 return generator67 } else {68 AudioServicesPlaySystemSound(SystemSoundID(style.rawValue))69 return nil70 }71 }72 73 private func updateFeedback(_ style: Style) {74 generator = Impact.make(style)75 self.style = style76 }77 78 public func feedback(_ style: Style) {79 updateFeedback(style)80 if #available(iOS 10.0, *) {81 guard let generator = generator as? UIImpactFeedbackGenerator else { return }82 generator.impactOccurred()83 generator.prepare()84 }85 }86 87 public func prepare(_ style: Style) {88 updateFeedback(style)89 if #available(iOS 10.0, *) {90 guard let generator = generator as? UIImpactFeedbackGenerator else { return }91 generator.prepare()92 }93 }94 }95 96 97 /// å°è£
`UISelectionFeedbackGenerator`98 public class Selection {99 private var generator: Any? = {100 guard #available(iOS 10.0, *) else { return nil }101 let generator: UISelectionFeedbackGenerator = UISelectionFeedbackGenerator()102 generator.prepare()103 return generator104 }()105 106 public func feedback() {107 guard _enabled else { return }108 if device.feedbackLevel == .improved {109 guard #available(iOS 10.0, *) else { return }110 guard let generator = generator as? UISelectionFeedbackGenerator else { return }111 generator.selectionChanged()112 generator.prepare()113 } else {114 AudioServicesPlaySystemSound(SystemSoundID(Impact.Style.light.rawValue))115 }116 }117 118 public func prepare() {119 guard _enabled else { return }120 if device.feedbackLevel == .improved {121 guard #available(iOS 10.0, *) else { return }122 guard let generator = generator as? UISelectionFeedbackGenerator else { return }123 generator.prepare()124 } else {125 AudioServicesPlaySystemSound(SystemSoundID(Impact.Style.light.rawValue))126 }127 }128 }129 130 131 /// å°è£
`UINotificationFeedbackGenerator`132 public class Notification {133 134 /// Notification åé¦ç±»å135 ///136 /// - success: æå137 /// - warning: è¦å138 /// - error: é误139 public enum `Type`: Int {140 case success = 1519141 case warning = 1520142 case error = 1521143 }144 145 private var generator: Any? = {146 guard #available(iOS 10.0, *) else { return nil }147 let generator: UINotificationFeedbackGenerator = UINotificationFeedbackGenerator()148 generator.prepare()149 return generator150 }()151 152 public func feedback(_ type: Type) {153 guard _enabled else { return }154 155 if device.feedbackLevel == .improved {156 guard #available(iOS 10.0, *) else { return }157 guard let generator = generator as? UINotificationFeedbackGenerator else { return }158 let feedbackType: UINotificationFeedbackGenerator.FeedbackType159 switch type {160 case .success:161 feedbackType = .success162 case .warning:163 feedbackType = .warning164 case .error:165 feedbackType = .error166 }167 generator.notificationOccurred(feedbackType)168 generator.prepare()169 } else {170 AudioServicesPlaySystemSound(SystemSoundID(type.rawValue))171 }172 }173 174 public func prepare() {175 guard _enabled else { return }176 if device.feedbackLevel == .improved {177 guard #available(iOS 10.0, *) else { return }178 guard let generator = generator as? UINotificationFeedbackGenerator else { return }179 generator.prepare()180 } else {181 AudioServicesPlaySystemSound(SystemSoundID(Type.success.rawValue))182 }183 }184 }185}186extension TapticEngine {187 static func toggle() {188 isEnabled.toggle()189 }190}191extension UIDevice {192 /// device support feedback level193 public enum Level {...
CodeGeneratorWeights.swift
Source:CodeGeneratorWeights.swift
...11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14import Fuzzilli15/// Assigned weights for the builtin code generators.16let codeGeneratorWeights = [17 // Base generators18// "IntegerGenerator": 0,19// "RegExpGenerator": 0,20// "BigIntGenerator": 0,21// "FloatGenerator": 0,22// "StringGenerator": 0,23// "BooleanGenerator": 0,24// "UndefinedGenerator": 0,25// "NullGenerator": 0,26// "ThisGenerator": 0,27// "ArgumentsGenerator": 0,28// "BuiltinGenerator": 10,29// "ObjectGenerator": 0,30// "ArrayGenerator": 0,31// "ObjectWithSpreadGenerator": 0,32// "ArrayWithSpreadGenerator": 0,33// "TemplateStringGenerator": 0,34// "PlainFunctionGenerator": 0,35// "ArrowFunctionGenerator": 0,36// "GeneratorFunctionGenerator": 0,37// "AsyncFunctionGenerator": 0,38// "AsyncArrowFunctionGenerator": 0,39// "AsyncGeneratorFunctionGenerator": 0,40// "FunctionReturnGenerator": 0,41// "YieldGenerator": 0,42// "AwaitGenerator": 0,43// "PropertyRetrievalGenerator": 0,44// "PropertyAssignmentGenerator": 0,45// "StorePropertyWithBinopGenerator": 0,46// "PropertyRemovalGenerator": 0,47// "ElementRetrievalGenerator": 0,48// "ElementAssignmentGenerator": 0,49// "StoreElementWithBinopGenerator": 0,50// "ElementRemovalGenerator": 0,51// "TypeTestGenerator": 0,52// "InstanceOfGenerator": 0,53// "InGenerator": 0,54// "ComputedPropertyRetrievalGenerator": 0,55// "ComputedPropertyAssignmentGenerator": 0,56// "StoreComputedPropertyWithBinopGenerator": 0,57// "ComputedPropertyRemovalGenerator": 0,58// "FunctionCallGenerator": 0,59// "FunctionCallWithSpreadGenerator": 0,60 "MethodCallGenerator": 1,61// "MethodCallWithSpreadGenerator": 0,62// "ComputedMethodCallGenerator": 0,63// "ComputedMethodCallWithSpreadGenerator": 0,64 "ConstructorCallGenerator": 1,65// "ConstructorCallWithSpreadGenerator": 0,66// "UnaryOperationGenerator": 0,67// "BinaryOperationGenerator": 0,68// "ReassignWithBinopGenerator": 0,69// "DupGenerator": 0,70// "ReassignmentGenerator": 0,71// "DestructArrayGenerator": 0,72// "DestructArrayAndReassignGenerator": 0,73// "DestructObjectGenerator": 0,74// "DestructObjectAndReassignGenerator": 0,75// "WithStatementGenerator": 0,76// "LoadFromScopeGenerator": 0,77// "StoreToScopeGenerator": 0,78// "ComparisonGenerator": 0,79// "ConditionalOperationGenerator": 0,80// "ClassGenerator": 0,81// "SuperMethodCallGenerator": 0,82// "LoadSuperPropertyGenerator": 0,83// "StoreSuperPropertyGenerator": 0,84// "StoreSuperPropertyWithBinopGenerator": 0,85// "IfElseGenerator": 0,86// "SwitchCaseGenerator": 0,87// "WhileLoopGenerator": 0,88// "DoWhileLoopGenerator": 0,89// "ForLoopGenerator": 0,90// "ForInLoopGenerator": 0,91// "ForOfLoopGenerator": 0,92// "ForOfWithDestructLoopGenerator": 0,93// "SwitchCaseBreakGenerator": 0,94// "LoopBreakGenerator": 0,95// "ContinueGenerator": 0,96// "TryCatchGenerator": 0,97// "ThrowGenerator": 0,98// "BlockStatementGenerator": 0,99 // Special generators100// "WellKnownPropertyLoadGenerator": 0,101// "WellKnownPropertyStoreGenerator": 0,102// "TypedArrayGenerator": 0,103// "FloatArrayGenerator": 0,104// "IntArrayGenerator": 0,105// "ObjectArrayGenerator": 0,106// "PrototypeAccessGenerator": 0,107// "PrototypeOverwriteGenerator": 0,108// "CallbackPropertyGenerator": 0,109// "PropertyAccessorGenerator": 0,110// "MethodCallWithDifferentThisGenerator": 0,111// "ProxyGenerator": 0,112// "LengthChangeGenerator": 0,113// "ElementKindChangeGenerator": 0,...
Name.php
Source:Name.php
2namespace Faker\Guesser;3use \Faker\Provider\Base;4class Name5{6 protected $generator;7 /**8 * @param \Faker\Generator $generator9 */10 public function __construct(\Faker\Generator $generator)11 {12 $this->generator = $generator;13 }14 /**15 * @param string $name16 * @param int|null $size Length of field, if known17 * @return callable18 */19 public function guessFormat($name, $size = null)20 {21 $name = Base::toLower($name);22 $generator = $this->generator;23 if (preg_match('/^is[_A-Z]/', $name)) {24 return function () use ($generator) {25 return $generator->boolean;26 };27 }28 if (preg_match('/(_a|A)t$/', $name)) {29 return function () use ($generator) {30 return $generator->dateTime;31 };32 }33 switch (str_replace('_', '', $name)) {34 case 'firstname':35 return function () use ($generator) {36 return $generator->firstName;37 };38 case 'lastname':39 return function () use ($generator) {40 return $generator->lastName;41 };42 case 'username':43 case 'login':44 return function () use ($generator) {45 return $generator->userName;46 };47 case 'email':48 case 'emailaddress':49 return function () use ($generator) {50 return $generator->email;51 };52 case 'phonenumber':53 case 'phone':54 case 'telephone':55 case 'telnumber':56 return function () use ($generator) {57 return $generator->phoneNumber;58 };59 case 'address':60 return function () use ($generator) {61 return $generator->address;62 };63 case 'city':64 case 'town':65 return function () use ($generator) {66 return $generator->city;67 };68 case 'streetaddress':69 return function () use ($generator) {70 return $generator->streetAddress;71 };72 case 'postcode':73 case 'zipcode':74 return function () use ($generator) {75 return $generator->postcode;76 };77 case 'state':78 return function () use ($generator) {79 return $generator->state;80 };81 case 'county':82 if ($this->generator->locale == 'en_US') {83 return function () use ($generator) {84 return sprintf('%s County', $generator->city);85 };86 }87 return function () use ($generator) {88 return $generator->state;89 };90 case 'country':91 switch ($size) {92 case 2:93 return function () use ($generator) {94 return $generator->countryCode;95 };96 case 3:97 return function () use ($generator) {98 return $generator->countryISOAlpha3;99 };100 case 5:101 case 6:102 return function () use ($generator) {103 return $generator->locale;104 };105 default:106 return function () use ($generator) {107 return $generator->country;108 };109 }110 break;111 case 'locale':112 return function () use ($generator) {113 return $generator->locale;114 };115 case 'currency':116 case 'currencycode':117 return function () use ($generator) {118 return $generator->currencyCode;119 };120 case 'url':121 case 'website':122 return function () use ($generator) {123 return $generator->url;124 };125 case 'company':126 case 'companyname':127 case 'employer':128 return function () use ($generator) {129 return $generator->company;130 };131 case 'title':132 if ($size !== null && $size <= 10) {133 return function () use ($generator) {134 return $generator->title;135 };136 }137 return function () use ($generator) {138 return $generator->sentence;139 };140 case 'body':141 case 'summary':142 case 'article':143 case 'description':144 return function () use ($generator) {145 return $generator->text;146 };147 }148 }149}...
GeneratorsTest.php
Source:GeneratorsTest.php
1<?php2namespace yiiunit\extensions\gii;3use yii\gii\CodeFile;4use yii\gii\generators\controller\Generator as ControllerGenerator;5use yii\gii\generators\crud\Generator as CRUDGenerator;6use yii\gii\generators\extension\Generator as ExtensionGenerator;7use yii\gii\generators\form\Generator as FormGenerator;8use yii\gii\generators\model\Generator as ModelGenerator;9use yii\gii\generators\module\Generator as ModuleGenerator;10/**11 * GeneratorsTest checks that Gii generators aren't throwing any errors during generation12 * @group gii13 */14class GeneratorsTest extends GiiTestCase15{16 public function testControllerGenerator()17 {18 $generator = new ControllerGenerator();19 $generator->template = 'default';20 $generator->controllerClass = 'app\runtime\TestController';21 $valid = $generator->validate();22 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));23 $this->assertNotEmpty($generator->generate());24 }25 public function testExtensionGenerator()26 {27 $generator = new ExtensionGenerator();28 $generator->template = 'default';29 $generator->vendorName = 'samdark';30 $generator->namespace = 'samdark\\';31 $generator->license = 'BSD';32 $generator->title = 'Sample extension';33 $generator->description = 'This is sample description.';34 $generator->authorName = 'Alexander Makarov';35 $generator->authorEmail = 'sam@rmcreative.ru';36 $valid = $generator->validate();37 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));38 $this->assertNotEmpty($generator->generate());39 }40 public function testModelGenerator()41 {42 $generator = new ModelGenerator();43 $generator->template = 'default';44 $generator->tableName = 'profile';45 $generator->modelClass = 'Profile';46 $valid = $generator->validate();47 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));48 $files = $generator->generate();49 $modelCode = $files[0]->content;50 $this->assertTrue(strpos($modelCode, "'id' => 'ID'") !== false, "ID label should be there:\n" . $modelCode);51 $this->assertTrue(strpos($modelCode, "'description' => 'Description',") !== false, "Description label should be there:\n" . $modelCode);52 }53 public function testModuleGenerator()54 {55 $generator = new ModuleGenerator();56 $generator->template = 'default';57 $generator->moduleID = 'test';58 $generator->moduleClass = 'app\modules\test\Module';59 $valid = $generator->validate();60 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));61 $this->assertNotEmpty($generator->generate());62 }63 public function testFormGenerator()64 {65 $generator = new FormGenerator();66 $generator->template = 'default';67 $generator->modelClass = 'yiiunit\extensions\gii\Profile';68 $generator->viewName = 'profile';69 $generator->viewPath = '@app/runtime';70 $valid = $generator->validate();71 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));72 $this->assertNotEmpty($generator->generate());73 }74 public function testCRUDGenerator()75 {76 $generator = new CRUDGenerator();77 $generator->template = 'default';78 $generator->modelClass = 'yiiunit\extensions\gii\Profile';79 $generator->controllerClass = 'app\TestController';80 $valid = $generator->validate();81 $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));82 $this->assertNotEmpty($generator->generate());83 }84}...
generator
Using AI Code Generation
1$generator = new \mageekguy\atoum\scripts\generator();2$generator->run();3$generator = new \mageekguy\atoum\scripts\generator();4$generator->run();5$generator = new \mageekguy\atoum\scripts\generator();6$generator->run();7$generator = new \mageekguy\atoum\scripts\generator();8$generator->run();9$generator = new \mageekguy\atoum\scripts\generator();10$generator->run();11$generator = new \mageekguy\atoum\scripts\generator();12$generator->run();13$generator = new \mageekguy\atoum\scripts\generator();14$generator->run();15$generator = new \mageekguy\atoum\scripts\generator();16$generator->run();17$generator = new \mageekguy\atoum\scripts\generator();18$generator->run();19$generator = new \mageekguy\atoum\scripts\generator();20$generator->run();21$generator = new \mageekguy\atoum\scripts\generator();22$generator->run();23$generator = new \mageekguy\atoum\scripts\generator();24$generator->run();
generator
Using AI Code Generation
1$generator = new \mageekguy\atoum\reports\asynchronous\generator();2$report = new \mageekguy\atoum\reports\asynchronous\html();3$report->addWriter(new \mageekguy\atoum\writers\file('path/to/your/report/directory'));4$generator->addReport($report);5$runner->setGenerator($generator);6$script->getRunner()->addTestsFromDirectory('path/to/your/tests/directory');7$script->run();8$generator = new \mageekguy\atoum\reports\asynchronous\generator();9$report = new \mageekguy\atoum\reports\asynchronous\html();10$report->addWriter(new \mageekguy\atoum\writers\file(__DIR__));11$generator->addReport($report);12$runner->setGenerator($generator);13$script->getRunner()->addTestsFromDirectory('path/to/your/tests/directory');14$script->run();15$generator = new \mageekguy\atoum\reports\asynchronous\generator();16$report = new \mageekguy\atoum\reports\asynchronous\html();17$report->addWriter(new \mageekg
generator
Using AI Code Generation
1namespace Tests\Units;2use mageekguy\atoum;3{4 public function testGenerator()5 {6 ->given($generator = new \Generator())7 ->object($generator)->isInstanceOf('\Generator')8 ;9 }10}11namespace Tests\Units;12use mageekguy\atoum;13{14 public function testGenerator()15 {16 ->given($generator = new \Generator())17 ->object($generator)->isInstanceOf('\Generator')18 ;19 }20}21namespace Tests\Units;22use mageekguy\atoum;23{24 public function testGenerator()25 {26 ->given($generator = new \Generator())27 ->object($generator)->isInstanceOf('\Generator')28 ;29 }30}31namespace Tests\Units;32use mageekguy\atoum;33{34 public function testGenerator()35 {36 ->given($generator = new \Generator())37 ->object($generator)->isInstanceOf('\Generator')38 ;39 }40}41namespace Tests\Units;42use mageekguy\atoum;43{44 public function testGenerator()45 {46 ->given($generator = new \Generator())47 ->object($generator)->isInstanceOf('\Generator')48 ;49 }50}51namespace Tests\Units;52use mageekguy\atoum;53{54 public function testGenerator()55 {56 ->given($generator = new \Generator())
generator
Using AI Code Generation
1$generator = new \mageekguy\atoum\scripts\generator();2$generator->setClassNamespace('tests\units');3$generator->setTestedClassName('MyClass');4$generator->setOutputDirectory(__DIR__ . '/tests/units');5$generator->run();6$generator = new \mageekguy\atoum\scripts\generator();7$generator->setClassNamespace('tests\units');8$generator->setTestedClassName('MyClass');9$generator->setOutputDirectory(__DIR__ . '/tests/units');10$generator->run();11$generator = new \mageekguy\atoum\scripts\generator();12$generator->setClassNamespace('tests\units');13$generator->setTestedClassName('MyClass');14$generator->setOutputDirectory(__DIR__ . '/tests/units');15$generator->run();16$generator = new \mageekguy\atoum\scripts\generator();17$generator->setClassNamespace('tests\units');18$generator->setTestedClassName('MyClass');19$generator->setOutputDirectory(__DIR__ . '/tests/units');20$generator->run();21$generator = new \mageekguy\atoum\scripts\generator();22$generator->setClassNamespace('tests\units');23$generator->setTestedClassName('MyClass');24$generator->setOutputDirectory(__DIR__ . '/tests/units');25$generator->run();26$generator = new \mageekguy\atoum\scripts\generator();27$generator->setClassNamespace('tests\units');28$generator->setTestedClassName('MyClass');29$generator->setOutputDirectory(__DIR__ . '/tests/units');30$generator->run();31$generator = new \mageekguy\atoum\scripts\generator();32$generator->setClassNamespace('tests\units');
generator
Using AI Code Generation
1use mageekguy\atoum\generator;2use ReflectionClass;3use ReflectionMethod;4use ReflectionParameter;5use ReflectionProperty;6use ReflectionClass;7use ReflectionMethod;8use ReflectionParameter;9use ReflectionProperty;10use ReflectionClass;11use ReflectionMethod;12use ReflectionParameter;13use ReflectionProperty;14use ReflectionClass;15use ReflectionMethod;16use ReflectionParameter;17use ReflectionProperty;18use ReflectionClass;19use ReflectionMethod;20use ReflectionParameter;21use ReflectionProperty;22use ReflectionClass;23use ReflectionMethod;24use ReflectionParameter;25use ReflectionProperty;26use ReflectionClass;27use ReflectionMethod;28use ReflectionParameter;29use ReflectionProperty;30use ReflectionClass;31use ReflectionMethod;32use ReflectionParameter;33use ReflectionProperty;34use ReflectionClass;35use ReflectionMethod;36use ReflectionParameter;37use ReflectionProperty;38use ReflectionClass;
generator
Using AI Code Generation
1use mageekguy\atoum\test;2use mageekguy\atoum\asserters\generator as generator;3{4 public function testGenerator()5 {6 ->generator(function() { yield 1; yield 2; yield 3; })7 ->yields->isEqualTo(1)8 ->yields->isEqualTo(2)9 ->yields->isEqualTo(3)10 ;11 }12}13use mageekguy\atoum\test;14use mageekguy\atoum\asserters\generator as generator;15{16 public function testGenerator()17 {18 ->generator(function() { yield 1; yield 2; yield 3; })19 ->yields->isEqualTo(1)20 ->yields->isEqualTo(2)21 ->yields->isEqualTo(3)22 ;23 }24}25use mageekguy\atoum\test;26use mageekguy\atoum\asserters\generator as generator;27{28 public function testGenerator()29 {30 ->generator(function() { yield 1; yield 2; yield 3; })31 ->yields->isEqualTo(1)32 ->yields->isEqualTo(2)33 ->yields->isEqualTo(3)34 ;35 }36}37use mageekguy\atoum\test;38use mageekguy\atoum\asserters\generator as generator;39{40 public function testGenerator()41 {42 ->generator(function() { yield 1; yield 2; yield 3; })43 ->yields->isEqualTo(1)44 ->yields->isEqualTo(2)45 ->yields->isEqualTo(3)46 ;47 }48}
generator
Using AI Code Generation
1$generator = new atoum\generator();2$generator->setClassNamespace('atoum\tests\units');3$generator->setClass('foo');4$generator->setClassParent('atoum\test');5$generator->addMethod('testBar');6$generator->addMethod('testBaz');7$generator->writeToDirectory(__DIR__ . '/units');8$generator = new atoum\generator();9$generator->setClassNamespace('atoum\tests\units');10$generator->setClass('bar');11$generator->setClassParent('atoum\test');12$generator->addMethod('testBar');13$generator->addMethod('testBaz');14$generator->writeToDirectory(__DIR__ . '/units');15$generator = new atoum\generator();16$generator->setClassNamespace('atoum\tests\units');17$generator->setClass('baz');18$generator->setClassParent('atoum\test');19$generator->addMethod('testBar');20$generator->addMethod('testBaz');21$generator->writeToDirectory(__DIR__ . '/units');22$generator = new atoum\generator();23$generator->setClassNamespace('atoum\tests\units');24$generator->setClass('qux');25$generator->setClassParent('atoum\test');26$generator->addMethod('testBar');27$generator->addMethod('testBaz');28$generator->writeToDirectory(__DIR__ . '/units');29$generator = new atoum\generator();30$generator->setClassNamespace('atoum\tests\units');31$generator->setClass('quux');32$generator->setClassParent('atoum\test');33$generator->addMethod('testBar');34$generator->addMethod('testBaz');35$generator->writeToDirectory(__DIR__ . '/units');36$generator = new atoum\generator();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.
Test now for FreeGet 100 minutes of automation test minutes FREE!!