How to use module method in ng-mocks

Best JavaScript code snippet using ng-mocks

binaryen.js-post.js

Source:binaryen.js-post.js Github

copy

Full Screen

1 // export friendly API methods2 function preserveStack(func) {3 try {4 var stack = Runtime.stackSave();5 return func();6 } finally {7 Runtime.stackRestore(stack);8 }9 };10 function strToStack(str) {11 if (!str) return 0;12 return allocate(intArrayFromString(str), 'i8', ALLOC_STACK);13 }14 function i32sToStack(i32s) {15 var ret = Runtime.stackAlloc(i32s.length << 2);16 for (var i = 0; i < i32s.length; i++) {17 HEAP32[ret + (i << 2) >> 2] = i32s[i];18 }19 return ret;20 }21 Module['none'] = Module['_BinaryenNone']();22 Module['i32'] = Module['_BinaryenInt32']();23 Module['i64'] = Module['_BinaryenInt64']();24 Module['f32'] = Module['_BinaryenFloat32']();25 Module['f64'] = Module['_BinaryenFloat64']();26 Module['undefined'] = Module['_BinaryenUndefined']();27 Module['ClzInt32'] = Module['_BinaryenClzInt32']();28 Module['CtzInt32'] = Module['_BinaryenCtzInt32']();29 Module['PopcntInt32'] = Module['_BinaryenPopcntInt32']();30 Module['NegFloat32'] = Module['_BinaryenNegFloat32']();31 Module['AbsFloat32'] = Module['_BinaryenAbsFloat32']();32 Module['CeilFloat32'] = Module['_BinaryenCeilFloat32']();33 Module['FloorFloat32'] = Module['_BinaryenFloorFloat32']();34 Module['TruncFloat32'] = Module['_BinaryenTruncFloat32']();35 Module['NearestFloat32'] = Module['_BinaryenNearestFloat32']();36 Module['SqrtFloat32'] = Module['_BinaryenSqrtFloat32']();37 Module['EqZInt32'] = Module['_BinaryenEqZInt32']();38 Module['ClzInt64'] = Module['_BinaryenClzInt64']();39 Module['CtzInt64'] = Module['_BinaryenCtzInt64']();40 Module['PopcntInt64'] = Module['_BinaryenPopcntInt64']();41 Module['NegFloat64'] = Module['_BinaryenNegFloat64']();42 Module['AbsFloat64'] = Module['_BinaryenAbsFloat64']();43 Module['CeilFloat64'] = Module['_BinaryenCeilFloat64']();44 Module['FloorFloat64'] = Module['_BinaryenFloorFloat64']();45 Module['TruncFloat64'] = Module['_BinaryenTruncFloat64']();46 Module['NearestFloat64'] = Module['_BinaryenNearestFloat64']();47 Module['SqrtFloat64'] = Module['_BinaryenSqrtFloat64']();48 Module['EqZInt64'] = Module['_BinaryenEqZInt64']();49 Module['ExtendSInt32'] = Module['_BinaryenExtendSInt32']();50 Module['ExtendUInt32'] = Module['_BinaryenExtendUInt32']();51 Module['WrapInt64'] = Module['_BinaryenWrapInt64']();52 Module['TruncSFloat32ToInt32'] = Module['_BinaryenTruncSFloat32ToInt32']();53 Module['TruncSFloat32ToInt64'] = Module['_BinaryenTruncSFloat32ToInt64']();54 Module['TruncUFloat32ToInt32'] = Module['_BinaryenTruncUFloat32ToInt32']();55 Module['TruncUFloat32ToInt64'] = Module['_BinaryenTruncUFloat32ToInt64']();56 Module['TruncSFloat64ToInt32'] = Module['_BinaryenTruncSFloat64ToInt32']();57 Module['TruncSFloat64ToInt64'] = Module['_BinaryenTruncSFloat64ToInt64']();58 Module['TruncUFloat64ToInt32'] = Module['_BinaryenTruncUFloat64ToInt32']();59 Module['TruncUFloat64ToInt64'] = Module['_BinaryenTruncUFloat64ToInt64']();60 Module['ReinterpretFloat32'] = Module['_BinaryenReinterpretFloat32']();61 Module['ReinterpretFloat64'] = Module['_BinaryenReinterpretFloat64']();62 Module['ConvertSInt32ToFloat32'] = Module['_BinaryenConvertSInt32ToFloat32']();63 Module['ConvertSInt32ToFloat64'] = Module['_BinaryenConvertSInt32ToFloat64']();64 Module['ConvertUInt32ToFloat32'] = Module['_BinaryenConvertUInt32ToFloat32']();65 Module['ConvertUInt32ToFloat64'] = Module['_BinaryenConvertUInt32ToFloat64']();66 Module['ConvertSInt64ToFloat32'] = Module['_BinaryenConvertSInt64ToFloat32']();67 Module['ConvertSInt64ToFloat64'] = Module['_BinaryenConvertSInt64ToFloat64']();68 Module['ConvertUInt64ToFloat32'] = Module['_BinaryenConvertUInt64ToFloat32']();69 Module['ConvertUInt64ToFloat64'] = Module['_BinaryenConvertUInt64ToFloat64']();70 Module['PromoteFloat32'] = Module['_BinaryenPromoteFloat32']();71 Module['DemoteFloat64'] = Module['_BinaryenDemoteFloat64']();72 Module['ReinterpretInt32'] = Module['_BinaryenReinterpretInt32']();73 Module['ReinterpretInt64'] = Module['_BinaryenReinterpretInt64']();74 Module['AddInt32'] = Module['_BinaryenAddInt32']();75 Module['SubInt32'] = Module['_BinaryenSubInt32']();76 Module['MulInt32'] = Module['_BinaryenMulInt32']();77 Module['DivSInt32'] = Module['_BinaryenDivSInt32']();78 Module['DivUInt32'] = Module['_BinaryenDivUInt32']();79 Module['RemSInt32'] = Module['_BinaryenRemSInt32']();80 Module['RemUInt32'] = Module['_BinaryenRemUInt32']();81 Module['AndInt32'] = Module['_BinaryenAndInt32']();82 Module['OrInt32'] = Module['_BinaryenOrInt32']();83 Module['XorInt32'] = Module['_BinaryenXorInt32']();84 Module['ShlInt32'] = Module['_BinaryenShlInt32']();85 Module['ShrUInt32'] = Module['_BinaryenShrUInt32']();86 Module['ShrSInt32'] = Module['_BinaryenShrSInt32']();87 Module['RotLInt32'] = Module['_BinaryenRotLInt32']();88 Module['RotRInt32'] = Module['_BinaryenRotRInt32']();89 Module['EqInt32'] = Module['_BinaryenEqInt32']();90 Module['NeInt32'] = Module['_BinaryenNeInt32']();91 Module['LtSInt32'] = Module['_BinaryenLtSInt32']();92 Module['LtUInt32'] = Module['_BinaryenLtUInt32']();93 Module['LeSInt32'] = Module['_BinaryenLeSInt32']();94 Module['LeUInt32'] = Module['_BinaryenLeUInt32']();95 Module['GtSInt32'] = Module['_BinaryenGtSInt32']();96 Module['GtUInt32'] = Module['_BinaryenGtUInt32']();97 Module['GeSInt32'] = Module['_BinaryenGeSInt32']();98 Module['GeUInt32'] = Module['_BinaryenGeUInt32']();99 Module['AddInt64'] = Module['_BinaryenAddInt64']();100 Module['SubInt64'] = Module['_BinaryenSubInt64']();101 Module['MulInt64'] = Module['_BinaryenMulInt64']();102 Module['DivSInt64'] = Module['_BinaryenDivSInt64']();103 Module['DivUInt64'] = Module['_BinaryenDivUInt64']();104 Module['RemSInt64'] = Module['_BinaryenRemSInt64']();105 Module['RemUInt64'] = Module['_BinaryenRemUInt64']();106 Module['AndInt64'] = Module['_BinaryenAndInt64']();107 Module['OrInt64'] = Module['_BinaryenOrInt64']();108 Module['XorInt64'] = Module['_BinaryenXorInt64']();109 Module['ShlInt64'] = Module['_BinaryenShlInt64']();110 Module['ShrUInt64'] = Module['_BinaryenShrUInt64']();111 Module['ShrSInt64'] = Module['_BinaryenShrSInt64']();112 Module['RotLInt64'] = Module['_BinaryenRotLInt64']();113 Module['RotRInt64'] = Module['_BinaryenRotRInt64']();114 Module['EqInt64'] = Module['_BinaryenEqInt64']();115 Module['NeInt64'] = Module['_BinaryenNeInt64']();116 Module['LtSInt64'] = Module['_BinaryenLtSInt64']();117 Module['LtUInt64'] = Module['_BinaryenLtUInt64']();118 Module['LeSInt64'] = Module['_BinaryenLeSInt64']();119 Module['LeUInt64'] = Module['_BinaryenLeUInt64']();120 Module['GtSInt64'] = Module['_BinaryenGtSInt64']();121 Module['GtUInt64'] = Module['_BinaryenGtUInt64']();122 Module['GeSInt64'] = Module['_BinaryenGeSInt64']();123 Module['GeUInt64'] = Module['_BinaryenGeUInt64']();124 Module['AddFloat32'] = Module['_BinaryenAddFloat32']();125 Module['SubFloat32'] = Module['_BinaryenSubFloat32']();126 Module['MulFloat32'] = Module['_BinaryenMulFloat32']();127 Module['DivFloat32'] = Module['_BinaryenDivFloat32']();128 Module['CopySignFloat32'] = Module['_BinaryenCopySignFloat32']();129 Module['MinFloat32'] = Module['_BinaryenMinFloat32']();130 Module['MaxFloat32'] = Module['_BinaryenMaxFloat32']();131 Module['EqFloat32'] = Module['_BinaryenEqFloat32']();132 Module['NeFloat32'] = Module['_BinaryenNeFloat32']();133 Module['LtFloat32'] = Module['_BinaryenLtFloat32']();134 Module['LeFloat32'] = Module['_BinaryenLeFloat32']();135 Module['GtFloat32'] = Module['_BinaryenGtFloat32']();136 Module['GeFloat32'] = Module['_BinaryenGeFloat32']();137 Module['AddFloat64'] = Module['_BinaryenAddFloat64']();138 Module['SubFloat64'] = Module['_BinaryenSubFloat64']();139 Module['MulFloat64'] = Module['_BinaryenMulFloat64']();140 Module['DivFloat64'] = Module['_BinaryenDivFloat64']();141 Module['CopySignFloat64'] = Module['_BinaryenCopySignFloat64']();142 Module['MinFloat64'] = Module['_BinaryenMinFloat64']();143 Module['MaxFloat64'] = Module['_BinaryenMaxFloat64']();144 Module['EqFloat64'] = Module['_BinaryenEqFloat64']();145 Module['NeFloat64'] = Module['_BinaryenNeFloat64']();146 Module['LtFloat64'] = Module['_BinaryenLtFloat64']();147 Module['LeFloat64'] = Module['_BinaryenLeFloat64']();148 Module['GtFloat64'] = Module['_BinaryenGtFloat64']();149 Module['GeFloat64'] = Module['_BinaryenGeFloat64']();150 Module['PageSize'] = Module['_BinaryenPageSize']();151 Module['CurrentMemory'] = Module['_BinaryenCurrentMemory']();152 Module['GrowMemory'] = Module['_BinaryenGrowMemory']();153 Module['HasFeature'] = Module['_BinaryenHasFeature']();154 // we provide a JS Module() object interface155 Module['Module'] = function(module) {156 if (!module) module = Module['_BinaryenModuleCreate']();157 this['ptr'] = module;158 this['dispose'] = function() {159 Module['_BinaryenModuleDispose'](module);160 };161 this['addFunctionType'] = function(name, result, paramTypes) {162 return preserveStack(function() {163 return Module['_BinaryenAddFunctionType'](module, strToStack(name), result,164 i32sToStack(paramTypes), paramTypes.length);165 });166 };167 this['getFunctionTypeBySignature'] = function(result, paramTypes) {168 return preserveStack(function() {169 return Module['_BinaryenGetFunctionTypeBySignature'](module, result,170 i32sToStack(paramTypes), paramTypes.length);171 });172 };173 this['block'] = function(name, children, type) {174 return preserveStack(function() {175 return Module['_BinaryenBlock'](module, name ? strToStack(name) : 0,176 i32sToStack(children), children.length,177 typeof type !== 'undefined' ? type : Module['undefined']);178 });179 };180 this['if'] = function(condition, ifTrue, ifFalse) {181 return Module['_BinaryenIf'](module, condition, ifTrue, ifFalse);182 };183 this['loop'] = function(label, body) {184 return preserveStack(function() {185 return Module['_BinaryenLoop'](module, strToStack(label), body);186 });187 };188 this['break'] = function(label, condition, value) {189 return preserveStack(function() {190 return Module['_BinaryenBreak'](module, strToStack(label), condition, value);191 });192 };193 this['switch'] = function(names, defaultName, condition, value) {194 return preserveStack(function() {195 var namei32s = [];196 names.forEach(function(name) {197 namei32s.push(strToStack(name));198 });199 return Module['_BinaryenSwitch'](module, i32sToStack(namei32s), namei32s.length,200 strToStack(defaultName), condition, value);201 });202 };203 this['call'] = function(name, operands, type) {204 return preserveStack(function() {205 return Module['_BinaryenCall'](module, strToStack(name), i32sToStack(operands), operands.length, type);206 });207 };208 this['callImport'] = function(name, operands, type) {209 return preserveStack(function() {210 return Module['_BinaryenCallImport'](module, strToStack(name), i32sToStack(operands), operands.length, type);211 });212 };213 this['callIndirect'] = function(target, operands, type) {214 return preserveStack(function() {215 return Module['_BinaryenCallIndirect'](module, target, i32sToStack(operands), operands.length, strToStack(type));216 });217 };218 this['getLocal'] = function(index, type) {219 return Module['_BinaryenGetLocal'](module, index, type);220 };221 this['setLocal'] = function(index, value) {222 return Module['_BinaryenSetLocal'](module, index, value);223 };224 this['teeLocal'] = function(index, value) {225 return Module['_BinaryenTeeLocal'](module, index, value);226 };227 this['getGlobal'] = function(name, type) {228 return Module['_BinaryenGetGlobal'](module, strToStack(name), type);229 }230 this['setGlobal'] = function(name, value) {231 return Module['_BinaryenSetGlobal'](module, strToStack(name), value);232 }233 this['currentMemory'] = function() {234 return Module['_BinaryenHost'](module, Module['CurrentMemory']);235 }236 this['growMemory'] = function(value) {237 return Module['_BinaryenHost'](module, Module['GrowMemory'], null, i32sToStack([value]), 1);238 }239 this['hasFeature'] = function(name) {240 return Module['_BinaryenHost'](module, Module['HasFeature'], strToStack(name));241 }242 // The Const creation API is a little different: we don't want users to243 // need to make their own Literals, as the C API handles them by value,244 // which means we would leak them. Instead, this is the only API that245 // accepts Literals, so fuse it with Literal creation246 var literal = _malloc(16); // a single literal in memory. the LLVM C ABI247 // makes us pass pointers to this.248 this['i32'] = {249 'load': function(offset, align, ptr) {250 return Module['_BinaryenLoad'](module, 4, true, offset, align, Module['i32'], ptr);251 },252 'load8_s': function(offset, align, ptr) {253 return Module['_BinaryenLoad'](module, 1, true, offset, align, Module['i32'], ptr);254 },255 'load8_u': function(offset, align, ptr) {256 return Module['_BinaryenLoad'](module, 1, false, offset, align, Module['i32'], ptr);257 },258 'load16_s': function(offset, align, ptr) {259 return Module['_BinaryenLoad'](module, 2, true, offset, align, Module['i32'], ptr);260 },261 'load16_u': function(offset, align, ptr) {262 return Module['_BinaryenLoad'](module, 2, false, offset, align, Module['i32'], ptr);263 },264 'store': function(offset, align, ptr, value) {265 return Module['_BinaryenStore'](module, 4, offset, align, ptr, value, Module['i32']);266 },267 'store8': function(offset, align, ptr, value) {268 return Module['_BinaryenStore'](module, 1, offset, align, ptr, value, Module['i32']);269 },270 'store16': function(offset, align, ptr, value) {271 return Module['_BinaryenStore'](module, 2, offset, align, ptr, value, Module['i32']);272 },273 'const': function(x) {274 Module['_BinaryenLiteralInt32'](literal, x);275 return Module['_BinaryenConst'](module, literal);276 },277 'clz': function(value) {278 return Module['_BinaryenUnary'](module, Module['ClzInt32'], value);279 },280 'ctz': function(value) {281 return Module['_BinaryenUnary'](module, Module['CtzInt32'], value);282 },283 'popcnt': function(value) {284 return Module['_BinaryenUnary'](module, Module['PopcntInt32'], value);285 },286 'eqz': function(value) {287 return Module['_BinaryenUnary'](module, Module['EqZInt32'], value);288 },289 'trunc_s': {290 'f32': function(value) {291 return Module['_BinaryenUnary'](module, Module['TruncSFloat32ToInt32'], value);292 },293 'f64': function(value) {294 return Module['_BinaryenUnary'](module, Module['TruncSFloat64ToInt32'], value);295 },296 },297 'trunc_u': {298 'f32': function(value) {299 return Module['_BinaryenUnary'](module, Module['TruncUFloat32ToInt32'], value);300 },301 'f64': function(value) {302 return Module['_BinaryenUnary'](module, Module['TruncUFloat64ToInt32'], value);303 },304 },305 'reinterpret': function(value) {306 return Module['_BinaryenUnary'](module, Module['ReinterpretFloat32'], value);307 },308 'wrap': function(value) {309 return Module['_BinaryenUnary'](module, Module['WrapInt64'], value);310 },311 'add': function(left, right) {312 return Module['_BinaryenBinary'](module, Module['AddInt32'], left, right);313 },314 'sub': function(left, right) {315 return Module['_BinaryenBinary'](module, Module['SubInt32'], left, right);316 },317 'mul': function(left, right) {318 return Module['_BinaryenBinary'](module, Module['MulInt32'], left, right);319 },320 'div_s': function(left, right) {321 return Module['_BinaryenBinary'](module, Module['DivSInt32'], left, right);322 },323 'div_u': function(left, right) {324 return Module['_BinaryenBinary'](module, Module['DivUInt32'], left, right);325 },326 'rem_s': function(left, right) {327 return Module['_BinaryenBinary'](module, Module['RemSInt32'], left, right);328 },329 'rem_u': function(left, right) {330 return Module['_BinaryenBinary'](module, Module['RemUInt32'], left, right);331 },332 'and': function(left, right) {333 return Module['_BinaryenBinary'](module, Module['AndInt32'], left, right);334 },335 'or': function(left, right) {336 return Module['_BinaryenBinary'](module, Module['OrInt32'], left, right);337 },338 'xor': function(left, right) {339 return Module['_BinaryenBinary'](module, Module['XorInt32'], left, right);340 },341 'shl': function(left, right) {342 return Module['_BinaryenBinary'](module, Module['ShlInt32'], left, right);343 },344 'shr_u': function(left, right) {345 return Module['_BinaryenBinary'](module, Module['ShrUInt32'], left, right);346 },347 'shr_s': function(left, right) {348 return Module['_BinaryenBinary'](module, Module['ShrSInt32'], left, right);349 },350 'rotl': function(left, right) {351 return Module['_BinaryenBinary'](module, Module['RotLInt32'], left, right);352 },353 'rotr': function(left, right) {354 return Module['_BinaryenBinary'](module, Module['RotRInt32'], left, right);355 },356 'eq': function(left, right) {357 return Module['_BinaryenBinary'](module, Module['EqInt32'], left, right);358 },359 'ne': function(left, right) {360 return Module['_BinaryenBinary'](module, Module['NeInt32'], left, right);361 },362 'lt_s': function(left, right) {363 return Module['_BinaryenBinary'](module, Module['LtSInt32'], left, right);364 },365 'lt_u': function(left, right) {366 return Module['_BinaryenBinary'](module, Module['LtUInt32'], left, right);367 },368 'le_s': function(left, right) {369 return Module['_BinaryenBinary'](module, Module['LeSInt32'], left, right);370 },371 'le_u': function(left, right) {372 return Module['_BinaryenBinary'](module, Module['LeUInt32'], left, right);373 },374 'gt_s': function(left, right) {375 return Module['_BinaryenBinary'](module, Module['GtSInt32'], left, right);376 },377 'gt_u': function(left, right) {378 return Module['_BinaryenBinary'](module, Module['GtUInt32'], left, right);379 },380 'ge_s': function(left, right) {381 return Module['_BinaryenBinary'](module, Module['GeSInt32'], left, right);382 },383 'ge_u': function(left, right) {384 return Module['_BinaryenBinary'](module, Module['GeUInt32'], left, right);385 },386 };387 this['i64'] = {388 'load': function(offset, align, ptr) {389 return Module['_BinaryenLoad'](module, 8, true, offset, align, Module['i64'], ptr);390 },391 'load8_s': function(offset, align, ptr) {392 return Module['_BinaryenLoad'](module, 1, true, offset, align, Module['i64'], ptr);393 },394 'load8_u': function(offset, align, ptr) {395 return Module['_BinaryenLoad'](module, 1, false, offset, align, Module['i64'], ptr);396 },397 'load16_s': function(offset, align, ptr) {398 return Module['_BinaryenLoad'](module, 2, true, offset, align, Module['i64'], ptr);399 },400 'load16_u': function(offset, align, ptr) {401 return Module['_BinaryenLoad'](module, 2, false, offset, align, Module['i64'], ptr);402 },403 'load32_s': function(offset, align, ptr) {404 return Module['_BinaryenLoad'](module, 4, true, offset, align, Module['i64'], ptr);405 },406 'load32_u': function(offset, align, ptr) {407 return Module['_BinaryenLoad'](module, 4, false, offset, align, Module['i64'], ptr);408 },409 'store': function(offset, align, ptr, value) {410 return Module['_BinaryenStore'](module, 8, offset, align, ptr, value, Module['i64']);411 },412 'store8': function(offset, align, ptr, value) {413 return Module['_BinaryenStore'](module, 1, offset, align, ptr, value, Module['i64']);414 },415 'store16': function(offset, align, ptr, value) {416 return Module['_BinaryenStore'](module, 2, offset, align, ptr, value, Module['i64']);417 },418 'store32': function(offset, align, ptr, value) {419 return Module['_BinaryenStore'](module, 4, offset, align, ptr, value, Module['i64']);420 },421 'const': function(x, y) {422 Module['_BinaryenLiteralInt64'](literal, x, y);423 return Module['_BinaryenConst'](module, literal);424 },425 'clz': function(value) {426 return Module['_BinaryenUnary'](module, Module['ClzInt64'], value);427 },428 'ctz': function(value) {429 return Module['_BinaryenUnary'](module, Module['CtzInt64'], value);430 },431 'popcnt': function(value) {432 return Module['_BinaryenUnary'](module, Module['PopcntInt64'], value);433 },434 'eqz': function(value) {435 return Module['_BinaryenUnary'](module, Module['EqZInt64'], value);436 },437 'trunc_s': {438 'f32': function(value) {439 return Module['_BinaryenUnary'](module, Module['TruncSFloat32ToInt64'], value);440 },441 'f64': function(value) {442 return Module['_BinaryenUnary'](module, Module['TruncSFloat64ToInt64'], value);443 },444 },445 'trunc_u': {446 'f32': function(value) {447 return Module['_BinaryenUnary'](module, Module['TruncUFloat32ToInt64'], value);448 },449 'f64': function(value) {450 return Module['_BinaryenUnary'](module, Module['TruncUFloat64ToInt64'], value);451 },452 },453 'reinterpret': function(value) {454 return Module['_BinaryenUnary'](module, Module['ReinterpretFloat64'], value);455 },456 'extend_s': function(value) {457 return Module['_BinaryenUnary'](module, Module['ExtendSInt32'], value);458 },459 'extend_u': function(value) {460 return Module['_BinaryenUnary'](module, Module['ExtendUInt32'], value);461 },462 'add': function(left, right) {463 return Module['_BinaryenBinary'](module, Module['AddInt64'], left, right);464 },465 'sub': function(left, right) {466 return Module['_BinaryenBinary'](module, Module['SubInt64'], left, right);467 },468 'mul': function(left, right) {469 return Module['_BinaryenBinary'](module, Module['MulInt64'], left, right);470 },471 'div_s': function(left, right) {472 return Module['_BinaryenBinary'](module, Module['DivSInt64'], left, right);473 },474 'div_u': function(left, right) {475 return Module['_BinaryenBinary'](module, Module['DivUInt64'], left, right);476 },477 'rem_s': function(left, right) {478 return Module['_BinaryenBinary'](module, Module['RemSInt64'], left, right);479 },480 'rem_u': function(left, right) {481 return Module['_BinaryenBinary'](module, Module['RemUInt64'], left, right);482 },483 'and': function(left, right) {484 return Module['_BinaryenBinary'](module, Module['AndInt64'], left, right);485 },486 'or': function(left, right) {487 return Module['_BinaryenBinary'](module, Module['OrInt64'], left, right);488 },489 'xor': function(left, right) {490 return Module['_BinaryenBinary'](module, Module['XorInt64'], left, right);491 },492 'shl': function(left, right) {493 return Module['_BinaryenBinary'](module, Module['ShlInt64'], left, right);494 },495 'shr_u': function(left, right) {496 return Module['_BinaryenBinary'](module, Module['ShrUInt64'], left, right);497 },498 'shr_s': function(left, right) {499 return Module['_BinaryenBinary'](module, Module['ShrSInt64'], left, right);500 },501 'rotl': function(left, right) {502 return Module['_BinaryenBinary'](module, Module['RotLInt64'], left, right);503 },504 'rotr': function(left, right) {505 return Module['_BinaryenBinary'](module, Module['RotRInt64'], left, right);506 },507 'eq': function(left, right) {508 return Module['_BinaryenBinary'](module, Module['EqInt64'], left, right);509 },510 'ne': function(left, right) {511 return Module['_BinaryenBinary'](module, Module['NeInt64'], left, right);512 },513 'lt_s': function(left, right) {514 return Module['_BinaryenBinary'](module, Module['LtSInt64'], left, right);515 },516 'lt_u': function(left, right) {517 return Module['_BinaryenBinary'](module, Module['LtUInt64'], left, right);518 },519 'le_s': function(left, right) {520 return Module['_BinaryenBinary'](module, Module['LeSInt64'], left, right);521 },522 'le_u': function(left, right) {523 return Module['_BinaryenBinary'](module, Module['LeUInt64'], left, right);524 },525 'gt_s': function(left, right) {526 return Module['_BinaryenBinary'](module, Module['GtSInt64'], left, right);527 },528 'gt_u': function(left, right) {529 return Module['_BinaryenBinary'](module, Module['GtUInt64'], left, right);530 },531 'ge_s': function(left, right) {532 return Module['_BinaryenBinary'](module, Module['GeSInt64'], left, right);533 },534 'ge_u': function(left, right) {535 return Module['_BinaryenBinary'](module, Module['GeUInt64'], left, right);536 },537 };538 this['f32'] = {539 'load': function(offset, align, ptr) {540 return Module['_BinaryenLoad'](module, 4, true, offset, align, Module['f32'], ptr);541 },542 'store': function(offset, align, ptr, value) {543 return Module['_BinaryenStore'](module, 4, offset, align, ptr, value, Module['f32']);544 },545 'const': function(x) {546 Module['_BinaryenLiteralFloat32'](literal, x);547 return Module['_BinaryenConst'](module, literal);548 },549 'const_bits': function(x) {550 Module['_BinaryenLiteralFloat32Bits'](literal, x);551 return Module['_BinaryenConst'](module, literal);552 },553 'neg': function(value) {554 return Module['_BinaryenUnary'](module, Module['NegFloat32'], value);555 },556 'abs': function(value) {557 return Module['_BinaryenUnary'](module, Module['AbsFloat32'], value);558 },559 'ceil': function(value) {560 return Module['_BinaryenUnary'](module, Module['CeilFloat32'], value);561 },562 'floor': function(value) {563 return Module['_BinaryenUnary'](module, Module['FloorFloat32'], value);564 },565 'trunc': function(value) {566 return Module['_BinaryenUnary'](module, Module['TruncFloat32'], value);567 },568 'nearest': function(value) {569 return Module['_BinaryenUnary'](module, Module['NearestFloat32'], value);570 },571 'sqrt': function(value) {572 return Module['_BinaryenUnary'](module, Module['SqrtFloat32'], value);573 },574 'reinterpret': function(value) {575 return Module['_BinaryenUnary'](module, Module['ReinterpretInt32'], value);576 },577 'convert_s': {578 'i32': function(value) {579 return Module['_BinaryenUnary'](module, Module['ConvertSInt32ToFloat32'], value);580 },581 'i64': function(value) {582 return Module['_BinaryenUnary'](module, Module['ConvertSInt64ToFloat32'], value);583 },584 },585 'convert_u': {586 'i32': function(value) {587 return Module['_BinaryenUnary'](module, Module['ConvertUInt32ToFloat32'], value);588 },589 'i64': function(value) {590 return Module['_BinaryenUnary'](module, Module['ConvertUInt64ToFloat32'], value);591 },592 },593 'demote': function(value) {594 return Module['_BinaryenUnary'](module, Module['DemoteFloat64'], value);595 },596 'add': function(left, right) {597 return Module['_BinaryenBinary'](module, Module['AddFloat32'], left, right);598 },599 'sub': function(left, right) {600 return Module['_BinaryenBinary'](module, Module['SubFloat32'], left, right);601 },602 'mul': function(left, right) {603 return Module['_BinaryenBinary'](module, Module['MulFloat32'], left, right);604 },605 'div': function(left, right) {606 return Module['_BinaryenBinary'](module, Module['DivFloat32'], left, right);607 },608 'copysign': function(left, right) {609 return Module['_BinaryenBinary'](module, Module['CopySignFloat32'], left, right);610 },611 'min': function(left, right) {612 return Module['_BinaryenBinary'](module, Module['MinFloat32'], left, right);613 },614 'max': function(left, right) {615 return Module['_BinaryenBinary'](module, Module['MaxFloat32'], left, right);616 },617 'eq': function(left, right) {618 return Module['_BinaryenBinary'](module, Module['EqFloat32'], left, right);619 },620 'ne': function(left, right) {621 return Module['_BinaryenBinary'](module, Module['NeFloat32'], left, right);622 },623 'lt': function(left, right) {624 return Module['_BinaryenBinary'](module, Module['LtFloat32'], left, right);625 },626 'le': function(left, right) {627 return Module['_BinaryenBinary'](module, Module['LeFloat32'], left, right);628 },629 'gt': function(left, right) {630 return Module['_BinaryenBinary'](module, Module['GtFloat32'], left, right);631 },632 'ge': function(left, right) {633 return Module['_BinaryenBinary'](module, Module['GeFloat32'], left, right);634 },635 };636 this['f64'] = {637 'load': function(offset, align, ptr) {638 return Module['_BinaryenLoad'](module, 8, true, offset, align, Module['f64'], ptr);639 },640 'store': function(offset, align, ptr, value) {641 return Module['_BinaryenStore'](module, 8, offset, align, ptr, value, Module['f64']);642 },643 'const': function(x) {644 Module['_BinaryenLiteralFloat64'](literal, x);645 return Module['_BinaryenConst'](module, literal);646 },647 'const_bits': function(x, y) {648 Module['_BinaryenLiteralFloat64Bits'](literal, x, y);649 return Module['_BinaryenConst'](module, literal);650 },651 'neg': function(value) {652 return Module['_BinaryenUnary'](module, Module['NegFloat64'], value);653 },654 'abs': function(value) {655 return Module['_BinaryenUnary'](module, Module['AbsFloat64'], value);656 },657 'ceil': function(value) {658 return Module['_BinaryenUnary'](module, Module['CeilFloat64'], value);659 },660 'floor': function(value) {661 return Module['_BinaryenUnary'](module, Module['FloorFloat64'], value);662 },663 'trunc': function(value) {664 return Module['_BinaryenUnary'](module, Module['TruncFloat64'], value);665 },666 'nearest': function(value) {667 return Module['_BinaryenUnary'](module, Module['NearestFloat64'], value);668 },669 'sqrt': function(value) {670 return Module['_BinaryenUnary'](module, Module['SqrtFloat64'], value);671 },672 'reinterpret': function(value) {673 return Module['_BinaryenUnary'](module, Module['ReinterpretInt64'], value);674 },675 'convert_s': {676 'i32': function(value) {677 return Module['_BinaryenUnary'](module, Module['ConvertSInt32ToFloat64'], value);678 },679 'i64': function(value) {680 return Module['_BinaryenUnary'](module, Module['ConvertSInt64ToFloat64'], value);681 },682 },683 'convert_u': {684 'i32': function(value) {685 return Module['_BinaryenUnary'](module, Module['ConvertUInt32ToFloat64'], value);686 },687 'i64': function(value) {688 return Module['_BinaryenUnary'](module, Module['ConvertUInt64ToFloat64'], value);689 },690 },691 'promote': function(value) {692 return Module['_BinaryenUnary'](module, Module['PromoteFloat32'], value);693 },694 'add': function(left, right) {695 return Module['_BinaryenBinary'](module, Module['AddFloat64'], left, right);696 },697 'sub': function(left, right) {698 return Module['_BinaryenBinary'](module, Module['SubFloat64'], left, right);699 },700 'mul': function(left, right) {701 return Module['_BinaryenBinary'](module, Module['MulFloat64'], left, right);702 },703 'div': function(left, right) {704 return Module['_BinaryenBinary'](module, Module['DivFloat64'], left, right);705 },706 'copysign': function(left, right) {707 return Module['_BinaryenBinary'](module, Module['CopySignFloat64'], left, right);708 },709 'min': function(left, right) {710 return Module['_BinaryenBinary'](module, Module['MinFloat64'], left, right);711 },712 'max': function(left, right) {713 return Module['_BinaryenBinary'](module, Module['MaxFloat64'], left, right);714 },715 'eq': function(left, right) {716 return Module['_BinaryenBinary'](module, Module['EqFloat64'], left, right);717 },718 'ne': function(left, right) {719 return Module['_BinaryenBinary'](module, Module['NeFloat64'], left, right);720 },721 'lt': function(left, right) {722 return Module['_BinaryenBinary'](module, Module['LtFloat64'], left, right);723 },724 'le': function(left, right) {725 return Module['_BinaryenBinary'](module, Module['LeFloat64'], left, right);726 },727 'gt': function(left, right) {728 return Module['_BinaryenBinary'](module, Module['GtFloat64'], left, right);729 },730 'ge': function(left, right) {731 return Module['_BinaryenBinary'](module, Module['GeFloat64'], left, right);732 },733 };734 this['select'] = function(condition, ifTrue, ifFalse) {735 return Module['_BinaryenSelect'](module, condition, ifTrue, ifFalse);736 };737 this['drop'] = function(value) {738 return Module['_BinaryenDrop'](module, value);739 };740 this['return'] = function(value) {741 return Module['_BinaryenReturn'](module, value);742 };743 this['host'] = function() {744 throw 'TODO';745 };746 this['nop'] = function() {747 return Module['_BinaryenNop'](module);748 };749 this['unreachable'] = function() {750 return Module['_BinaryenUnreachable'](module);751 };752 this['addFunction'] = function(name, functionType, varTypes, body) {753 return preserveStack(function() {754 return Module['_BinaryenAddFunction'](module, strToStack(name), functionType, i32sToStack(varTypes), varTypes.length, body);755 });756 };757 this['addGlobal'] = function(name, type, mutable, init) {758 return preserveStack(function() {759 return Module['_BinaryenAddGlobal'](module, strToStack(name), type, mutable, init);760 });761 }762 this['addImport'] = function(internalName, externalModuleName, externalBaseName, type) {763 return preserveStack(function() {764 return Module['_BinaryenAddImport'](module, strToStack(internalName), strToStack(externalModuleName), strToStack(externalBaseName), type);765 });766 };767 this['removeImport'] = function(internalName) {768 return preserveStack(function() {769 return Module['_BinaryenRemoveImport'](module, strToStack(internalName));770 });771 };772 this['addExport'] = function(internalName, externalName) {773 return preserveStack(function() {774 return Module['_BinaryenAddExport'](module, strToStack(internalName), strToStack(externalName));775 });776 };777 this['removeExport'] = function(externalName) {778 return preserveStack(function() {779 return Module['_BinaryenRemoveExport'](module, strToStack(externalName));780 });781 };782 this['setFunctionTable'] = function(funcs) {783 return preserveStack(function() {784 return Module['_BinaryenSetFunctionTable'](module, i32sToStack(funcs), funcs.length);785 });786 };787 this['setMemory'] = function(initial, maximum, exportName, segments) {788 // segments are assumed to be { offset: expression ref, data: array of 8-bit data }789 return preserveStack(function() {790 return Module['_BinaryenSetMemory'](791 module, initial, maximum, strToStack(exportName),792 i32sToStack(793 segments.map(function(segment) {794 return allocate(segment.data, 'i8', ALLOC_STACK);795 })796 ),797 i32sToStack(798 segments.map(function(segment) {799 return segment.offset;800 })801 ),802 i32sToStack(803 segments.map(function(segment) {804 return segment.data.length;805 })806 ),807 segments.length808 );809 });810 };811 this['setStart'] = function(start) {812 return Module['_BinaryenSetStart'](module, start);813 };814 this['emitText'] = function() {815 var old = Module['print'];816 var ret = '';817 Module['print'] = function(x) { ret += x + '\n' };818 Module['_BinaryenModulePrint'](module);819 Module['print'] = old;820 return ret;821 };822 this['validate'] = function() {823 return Module['_BinaryenModuleValidate'](module);824 };825 this['optimize'] = function() {826 return Module['_BinaryenModuleOptimize'](module);827 };828 this['autoDrop'] = function() {829 return Module['_BinaryenModuleAutoDrop'](module);830 };831 // TODO: fix this hard-wired limit832 var MAX = 1024*1024;833 var writeBuffer = null;834 this['emitBinary'] = function() {835 if (!writeBuffer) writeBuffer = _malloc(MAX);836 var bytes = Module['_BinaryenModuleWrite'](module, writeBuffer, MAX);837 assert(bytes < MAX, 'FIXME: hardcoded limit on module size'); // we should not use the whole buffer838 return new Uint8Array(HEAPU8.subarray(writeBuffer, writeBuffer + bytes));839 };840 this['interpret'] = function() {841 return Module['_BinaryenModuleInterpret'](module);842 };843 };844 Module['Relooper'] = function() {845 var relooper = this.ptr = Module['_RelooperCreate']();846 this['addBlock'] = function(code) {847 return Module['_RelooperAddBlock'](relooper, code);848 };849 this['addBranch'] = function(from, to, condition, code) {850 return Module['_RelooperAddBranch'](from, to, condition, code);851 };852 this['addBlockWithSwitch'] = function(code, condition) {853 return Module['_RelooperAddBlockWithSwitch'](relooper, code, condition);854 };855 this['addBranchForSwitch'] = function(from, to, indexes, code) {856 return preserveStack(function() {857 return Module['_RelooperAddBranchForSwitch'](from, to, i32sToStack(indexes), indexes.length, code);858 });859 };860 this['renderAndDispose'] = function(entry, labelHelper, module) {861 return Module['_RelooperRenderAndDispose'](relooper, entry, labelHelper, module['ptr']);862 };863 };864 // emit text of an expression or a module865 Module['emitText'] = function(expr) {866 if (typeof expr === 'object') {867 return expr.emitText();868 }869 var old = Module['print'];870 var ret = '';871 Module['print'] = function(x) { ret += x + '\n' };872 Module['_BinaryenExpressionPrint'](expr);873 Module['print'] = old;874 return ret;875 };876 Module['readBinary'] = function(data) {877 var buffer = allocate(data, 'i8', ALLOC_NORMAL);878 var ptr = Module['_BinaryenModuleRead'](buffer, data.length);879 _free(buffer);880 return new Module['Module'](ptr);881 };882 Module['parseText'] = function(text) {883 var buffer = _malloc(text.length + 1);884 writeAsciiToMemory(text, buffer);885 var ptr = Module['_BinaryenModuleParse'](buffer);886 _free(buffer);887 return new Module['Module'](ptr);888 };889 Module['setAPITracing'] = function(on) {890 return Module['_BinaryenSetAPITracing'](on);891 };892 return Module;893};894if (typeof exports != 'undefined') {895 (function(){896 var a = Binaryen();897 if (typeof module === 'object') {898 module.exports = a;899 } else {900 for (var k in a) {901 exports[k] = a[k];902 }903 }904 })();905}906(typeof window !== 'undefined' ? window :907 typeof global !== 'undefined' && (908 typeof process === 'undefined' ||909 // Note: We must export "Binaryen" even inside a CommonJS/AMD/UMD module910 // space because check.py generates a.js which requires Binaryen global var911 ( process.argv &&912 Array.isArray(process.argv) &&913 process.argv[1] &&914 (process.argv[1].substr(-5) === '/a.js' ||915 process.argv[1].substr(-5) === '\\a.js')916 )917 ) ? global :918 this...

Full Screen

Full Screen

test_module.py

Source:test_module.py Github

copy

Full Screen

...6from prolog.interpreter import term7from prolog.interpreter.signature import Signature8from prolog.interpreter.continuation import Engine9from prolog.interpreter.error import UncaughtError10def test_set_currently_parsed_module():11 e = get_engine("""12 f(a).13 """)14 m = e.modulewrapper15 assert m.current_module == m.user_module16 m.add_module("m1", [])17 assert "m1" in m.modules18 mod1 = m.modules["m1"]19 assert mod1.exports == []20 assert mod1.functions == {}21 atom = term.Callable.build("f")22 e.add_rule(atom)23 assert atom.signature() in mod1.functions24def test_module_exports():25 e = get_engine("""26 :- module(m, [g/2]).27 g(a, b).28 f(c, d, e).29 """)30 exports = e.modulewrapper.modules["m"].exports31 assert len(exports) == 1 and exports[0].eq(Signature("g", 2))32def test_use_module_with_file():33 e = get_engine("""34 :- use_module(m).35 """, True,36 m = """37 :- module(m, [f/0]).38 f.39 """)40 assert len(e.modulewrapper.modules) == 241 assert_true("f.", e)42def test_use_module_locate_file():43 src1 = "src.pl"44 src2 = "src2"45 create_file(src1, ":- module(src, []).")46 create_file(src2, ":- module(src2, []).")47 try:48 assert_true("use_module('%s')." % src1)49 assert_true("use_module('%s')." % "src")50 # XXX some problems with unification, should be existence_error(_, _) 51 # instead of X52 prolog_raises("X", "use_module('%s')" % "src2.pl")53 assert_true("use_module('%s')." % "src2")54 finally:55 delete_file(src1)56 delete_file(src2)57def test_module_uses():58 e = get_engine("""59 :- use_module(b).60 """,61 a = """62 :- module(a, [h/1]).63 h(z).64 """,65 b = """66 :- module(b, [f/1]).67 :- use_module(a).68 f(X) :- h(X).69 g(a).70 """)71 assert len(e.modulewrapper.modules) == 372def test_lookup():73 e = get_engine("""74 :- use_module(m).75 f(a) :- g(a, b).76 """,77 m = """78 :- module(m, [g/2]).79 g(a, b).80 h(w).81 """)82 f_sig = Signature.getsignature("f", 1)83 g_sig = Signature.getsignature("g", 2)84 h_sig = Signature.getsignature("h", 1)85 user = e.modulewrapper.modules["user"]86 m = e.modulewrapper.modules["m"]87 assert user.lookup(g_sig) == m.functions[g_sig]88 assert user.lookup(h_sig).rulechain is None89 assert m.lookup(g_sig) == m.functions[g_sig]90 assert m.lookup(f_sig).rulechain is None91 assert m.lookup(h_sig) == m.functions[h_sig]92def test_modules_use_module():93 e = get_engine("""94 :- use_module(m).95 f(X) :- g(X).96 f(b).97 h(a).98 """,99 m = """100 :- module(m, [g/1]).101 g(a).102 h(b).103 """)104 assert_true("f(a).", e)105 assert_true("f(b).", e)106 assert_true("h(a).", e)107 assert_false("h(b).", e)108def test_use_module_not_instantiated():109 prolog_raises("instantiation_error", "use_module(X)")110 prolog_raises("instantiation_error", "use_module(X, [])")111def test_modules_integration():112 e = get_engine("""113 :- use_module(m).114 f(X) :- g(X).115 h(b).116 both(X, Y) :- f(X), h(Y).117 """,118 m = """119 :- module(m, [g/1]).120 g(X) :- h(X).121 h(a).122 """)123 assert_true("findall(X, h(X), L), L = [b].", e)124 assert_true("both(X, Y), X == a, Y == b.", e)125def test_fail_and_retry_in_different_modules():126 e = get_engine("""127 :- use_module(m1).128 :- use_module(m2).129 """, 130 m1 = """131 :- module(m1, [f/1]).132 f(a).133 """, 134 m2 = """135 :- module(m2, [g/1]).136 g(a).137 """)138 assert_true(";((f(a), fail), g(a)).", e)139def test_builtin_module_or():140 e = get_engine("""141 :- use_module(m).142 t :- h, x.143 x.144 """,145 m = """146 :- module(m, [h/0]).147 h :- f; g.148 f.149 g.150 """)151 assert_true("t.", e)152 assert_true("not(x); h.", e)153 assert_true("h; x.", e)154 assert_true("(\+ h; \+ x); h.", e)155def test_builtin_module_and():156 e = get_engine("""157 :- use_module(m).158 t :- h, x.159 x.160 """,161 m = """162 :- module(m, [h/0]).163 h :- f, g.164 f.165 g.166 """)167 assert_true("t.", e)168 assert_true("x, h.", e)169 assert_false("h, \+ x.", e)170 assert_false("\+ x, h.", e)171 assert_false("\+ x, \+ h.", e)172 assert_true("\+ (x, \+ h).", e)173def test_catch_error():174 e = get_engine("""175 :- use_module(m).176 h :- catch(f, X, g).177 g.178 """,179 m = """180 :- module(m, [f/0]).181 f :- throw(foo).182 """)183 assert_true("h.", e)184def test_abolish():185 e = get_engine("""186 :- use_module(m).187 f(a).188 """,189 m = """190 :- module(m, [g/1]).191 g(a).192 """)193 assert_true("f(a).", e)194 assert len(e.modulewrapper.modules["user"].functions) == 2195 assert_true("abolish(f/1).", e)196 prolog_raises("existence_error(A, B)", "f(a)", e)197 assert_true("g(a).", e)198 assert_true("abolish(g/1).", e)199 prolog_raises("existence_error(A, B)", "g(a)", e)200 assert len(e.modulewrapper.modules["user"].functions) == 2201 assert len(e.modulewrapper.modules["m"].functions) == 1202def test_if():203 e = get_engine("""204 :- use_module(m).205 f(X) :- (X = b206 -> g(X)207 ; h(X)).208 g(c).209 """,210 m = """211 :- module(m, [h/1]).212 h(a).213 """)214 assert_true("f(a).", e)215 assert_false("f(b).", e)216def test_once():217 e = get_engine("""218 :- use_module(m).219 x :- f, h.220 h.221 """,222 m = """223 :- module(m, [f/0]).224 f :- once(g).225 g.226 """)227 assert_true("x.", e)228def test_module_switch_1():229 e = get_engine("""230 :- use_module(m).231 :- module(m).232 """,233 m = """234 :- module(m, [g/0]).235 g.236 f.237 """)238 assert e.modulewrapper.current_module.name == "m"239 assert_true("g.", e)240 assert_true("f.", e)241def test_module_switch_2():242 e = get_engine("""243 :- use_module(m).244 f.245 :- module(m).246 """,247 m = """248 :- module(m, []).249 g.250 """)251 assert e.modulewrapper.current_module.name == "m"252 prolog_raises("existence_error(X, Y)", "f", e)253 assert_true("g.", e)254 assert_true("module(user).", e)255 assert e.modulewrapper.current_module.name == "user"256 prolog_raises("existence_error(X, Y)", "g", e)257 assert_true("f.", e)258def test_switch_to_nonexistent_module():259 e = get_engine("""260 :- module(m).261 """)262 prolog_raises("existence_error(X, Y)", "x", e)263 assert_true("assert(x).", e)264 assert_true("x.", e)265 assert_true("module(user).", e)266 prolog_raises("existence_error(X, Y)", "x", e)267def test_module_assert_retract():268 e = Engine()269 assert_true("module(m).", e)270 assert_true("assert(x).", e)271 assert_true("asserta(y).", e)272 assert_true("x, y.", e)273 assert_true("module(user).", e)274 assert_false("retract(x).", e)275 assert_false("retract(y).", e)276 assert_true("assert(x).", e)277 assert_true("x.", e)278 assert_true("module(m).", e)279 assert_true("retract(x).", e)280 prolog_raises("existence_error(X, Y)", "x", e)281 assert_true("module(user).", e)282 assert_true("x.", e)283def test_module_prefixing():284 e = get_engine("""285 a.286 """,287 m = """288 :- module(m, []).289 f(a).290 f(b).291 """)292 assert_true("m:f(a), m:f(b).", e)293 assert_true("m:f(a), a.", e)294 prolog_raises("existence_error(X, Y)", "m:a", e)295 assert_true("module(m).", e)296 prolog_raises("existence_error(X, Y)", "a", e)297 assert_true("user:a.", e)298def test_prefix_non_existent_module():299 prolog_raises("existence_error(X, Y)", "a:b")300def test_prefix_module_in_other_directory():301 d = "__dir__"302 create_dir(d)303 m = "mod"304 create_file("%s/%s" % (d, m), """305 :- module(%s, [f/1]).306 f(a).307 """ % m)308 e = Engine()309 try:310 assert_true("use_module('%s/%s')." % (d, m), e)311 assert_true("current_module(%s)." % m, e)312 assert_true("%s:f(X), X == a." % m, e)313 finally:314 delete_dir(d)315def test_recursive_use_module():316 # if this test fails, one will recognize it by317 # waiting very long ...318 mod = "m"319 create_file(mod, """320 :- module(m, []).321 :- use_module(m).322 """)323 try:324 e = get_engine("""325 :- use_module(m).326 """)327 finally:328 delete_file(mod)329def test_alternating_recursive_import():330 mod = "m2"331 create_file(mod, """332 :- module(m2, [g/1]).333 :- use_module(m1).334 g(b).335 """)336 337 e = get_engine("""338 :- use_module(m1).339 """,340 m1 = """341 :- module(m1, [f/1]).342 f(a).343 :- use_module(m2).344 """)345 try:346 assert_true("f(X), X = a.", e)347 prolog_raises("existence_error(X, Y)", "g(X)", e)348 finally:349 delete_file(mod)350def test_recursive_ring_import():351 mod2 = "m2"352 mod3 = "m3"353 create_file(mod2, """354 :- module(m2, [g/1]).355 :- use_module(m3).356 g(a).357 """)358 create_file(mod3, """359 :- module(m3, [h/1]).360 :- use_module(m1).361 h(a).362 """)363 e = get_engine("""364 :- use_module(m1).365 z(a).366 """,367 m1 = """368 :- module(m1, [f/1]).369 f(a).370 :- use_module(m2).371 """)372 m = e.modulewrapper373 try:374 assert len(m.modules) == 4375 assert len(m.modules["user"].functions) == 2376 assert len(m.modules["m1"].functions) == 2377 assert len(m.modules["m2"].functions) == 2378 assert len(m.modules["m3"].functions) == 2379 assert_true("z(a).", e)380 assert_true("f(a).", e)381 assert_true("m1:f(a).", e)382 assert_true("m1:g(a).", e)383 assert_true("m2:g(a).", e)384 assert_true("m2:h(a).", e)385 assert_true("m3:h(a).", e)386 assert_true("m3:f(a).", e)387 finally:388 delete_file(mod2)389 delete_file(mod3)390def test_use_same_module_twice():391 # if this test fails, one will recognize it by392 # waiting very long ...393 e = get_engine(394 """395 :- use_module(m1).396 :- use_module(m2).397 h(X) :- g(X), f(X).398 """, True,399 m1 = """400 :- module(m1, [f/1]).401 f(a).402 """,403 m2 = """404 :- module(m2, [g/1]).405 :- use_module(m1).406 g(X) :- f(X).407 """)408 assert_true("h(X), X == a.", e)409def test_impl_use_module():410 from prolog.builtin.modules import impl_use_module411 from prolog.interpreter.heap import Heap412 filecontent = """413 :- module(blub, []).414 """415 e = Engine()416 h = Heap()417 m = e.modulewrapper418 create_file("blub.pl", filecontent)419 try:420 impl_use_module(e, m.user_module, h,421 term.Callable.build("blub.pl"))422 assert "blub" in e.modulewrapper.modules.keys()423 finally:424 delete_file("blub.pl")425 create_file("blub", filecontent)426 m.modules = {}427 m.seen_modules = {}428 try:429 impl_use_module(e, m.user_module, h, term.Callable.build("blub"))430 assert "blub" in m.modules.keys()431 finally:432 delete_file("blub")433def test_add_library_dir():434 e = Engine()435 m = e.modulewrapper436 assert m.libs == []437 prolog_raises("existence_error(X, Y)", "add_library_dir('does_not_exist')", e)438 lib1 = "__lib1__"439 lib2 = "__lib2__"440 create_dir(lib1)441 create_dir(lib2)442 try:443 assert_true("add_library_dir('%s')." % lib1, e)444 assert_true("add_library_dir('%s')." % lib2, e)445 assert len(m.libs) == 2446 finally:447 delete_dir(lib1)448 delete_dir(lib2)449def test_library_directory():450 e = Engine()451 m = e.modulewrapper452 assert m.libs == []453 libs = collect_all(e, "library_directory(X).")454 assert len(libs) == 0455 tempdir1 = "__tempdir1__"456 tempdir2 = "__tempdir2__"457 create_dir(tempdir1)458 create_dir(tempdir2)459 try:460 assert_true("add_library_dir('%s')." % tempdir1, e)461 assert_true("add_library_dir('%s')." % tempdir2, e)462 libs = collect_all(e, "library_directory(X).")463 assert len(libs) == 2464 assert len(m.libs) == 2465 finally:466 delete_dir(tempdir1)467 delete_dir(tempdir2)468def test_use_library_errors():469 prolog_raises("instantiation_error", "use_module(library(X))")470 prolog_raises("existence_error(_, _)", "use_module(library(does_not_exist_))")471 prolog_raises("existence_error(source_sink, _)", "use_module(sdfdsfsf(sadasd))")472def test_library_dir_single_query():473 e = Engine()474 tempdir = "__temp__"475 create_dir(tempdir)476 try:477 assert_true("add_library_dir('%s')." % tempdir, e)478 assert_true("library_directory('%s')." % tempdir, e)479 finally:480 delete_dir(tempdir)481def test_library_usage():482 tempdir = "__tempdir__"483 mod = "m"484 mod2 = "m2"485 create_dir(tempdir)486 create_file(tempdir + "/" + mod, """487 :- module(m, [f/1]).488 f(a).489 g.490 """)491 create_file(tempdir + "/" + (mod2 + ".pl"), """492 :- module(m2, [f/1]).493 f(a).494 g.495 """)496 try:497 e = get_engine(":- add_library_dir('%s')." % tempdir)498 assert len(e.modulewrapper.libs) == 1499 assert_true("use_module(library('%s'))." % mod, e)500 assert_true("f(a).", e)501 prolog_raises("existence_error(X, Y)", "g", e)502 e = get_engine(":- add_library_dir('%s')." % tempdir)503 assert len(e.modulewrapper.libs) == 1504 assert_true("use_module(library('%s'))." % mod2, e)505 assert_true("f(a).", e)506 prolog_raises("existence_error(X, Y)", "g", e)507 finally:508 delete_dir(tempdir)509def test_library_load_priority():510 tempdir = "__tempdir__"511 mod = "m"512 create_dir(tempdir)513 create_file(tempdir + "/" + mod, """514 :- module(m, [f/1]).515 f(a).516 g.517 """)518 create_file(mod, """519 :- module(m, [f/1, g]).520 f(b).521 g.522 """)523 try:524 e = get_engine(":- add_library_dir('%s')." % tempdir)525 assert len(e.modulewrapper.libs) == 1526 assert_true("use_module(library('%s'))." % mod, e)527 assert_true("f(a).", e)528 prolog_raises("existence_error(X, Y)", "g", e)529 finally:530 delete_dir(tempdir)531 delete_file(mod)532def test_add_library_twice():533 e = Engine()534 lib1 = "__lib1__"535 lib2 = "__lib2__"536 create_dir(lib1)537 create_dir(lib2)538 try:539 assert_true("add_library_dir('%s')." % lib1, e)540 assert len(e.modulewrapper.libs) == 1541 assert_true("add_library_dir('%s')." % lib1, e)542 assert len(e.modulewrapper.libs) == 1543 assert_true("add_library_dir('%s')." % lib2, e)544 assert len(e.modulewrapper.libs) == 2545 finally:546 delete_dir(lib1)547 delete_dir(lib2)548def test_import_list_simple():549 e = get_engine("""550 :- use_module(m, [f/1, g/0]).551 h(X) :- f(X), g.552 """,553 m = """554 :- module(m, [f/1, g/0]).555 f(a).556 g.557 q.558 """)559 assert_true("h(a).", e)560 prolog_raises("existence_error(X, Y)", "q", e)561def test_empty_import_list():562 e = get_engine("""563 :- use_module(m, []).564 """,565 m = """566 :- module(m, [f/1, g/0]).567 f(a).568 g.569 q.570 """)571 assert len(e.modulewrapper.modules["user"].functions) == 0572 prolog_raises("existence_error(X, Y)", "f(a)", e)573 prolog_raises("existence_error(X, Y)", "g", e)574 prolog_raises("existence_error(X, Y)", "q", e)575def test_nonexisting_predicates_in_import_list():576 e = get_engine("""577 :- use_module(m, [z/0, g/1]).578 """,579 m = """580 :- module(m, [f/1, g/0]).581 f(a).582 g.583 q.584 """)585 prolog_raises("existence_error(X, Y)", "z", e)586 prolog_raises("existence_error(X, Y)", "g(A)", e)587def test_existing_system_module():588 e = Engine(load_system=True)589 assert e.modulewrapper.modules.has_key("system")590# needs list module591def test_access_system_predicate():592 e = Engine(load_system=True)593 assert_true("append([1], [2], [1, 2]).", e)594# needs list and dcg module595def test_term_expansion():596 e = get_engine("""597 a --> [b].598 f(X) :-599 X = x;600 X = y.601 """,602 load_system=True)603 assert_true("a([b], []).", e)604 assert_false("a([], []).", e)605 assert_false("f(a).", e)606 assert_false("f(b).", e)607 assert_true("f(x).", e)608 assert_true("f(y).", e)609 assert_true("assert((g --> [h])).", e)610 prolog_raises("existence_error(A, B)", "g([h], [])", e)611 assert_true("g --> [h].", e)612 assert_false("g --> [].", e)613 assert_true("term_expand((z --> [q]), R).", e)614 prolog_raises("existence_error(A, B)", "z([q], [])", e)615def test_overwrite_term_expand():616 e = get_engine("""617 term_expand(A, A).618 a --> [b].619 """,620 load_system=True)621 assert_true("(X --> Y), X == a, Y == [b].", e)622 assert_true("system:term_expand((a --> [b]), R), assert(R).", e)623 assert_true("a([b], []).", e)624 assert_true("term_expand((a --> b), R), assert(R).", e)625 assert_true("(A --> b), A == a.", e)626def test_module_with_dcg():627 e = get_engine("""628 :- use_module(m).629 """,630 m = """631 :- module(m, [f/1]).632 f(X) :- a(X, []).633 a --> [b], c, [d].634 c --> [1].635 c --> [x, y, z].636 """,637 load_system=True)638 assert_true("f([b, 1, d]).", e)639 assert_true("f([b, x, y, z, d]).", e)640 assert_false("f([b, y, z, d]).", e)641 assert_false("f([]).", e)642def test_assert_dcg():643 e = Engine(load_system=True)644 assert_true("assert((a --> b)).", e)645 assert_true("a --> b.", e)646def test_term_expand_fail():647 # Since self-defined term_expand fails648 # the system term_expand should be called.649 e = get_engine("""650 term_expand(A, A) :- fail.651 a --> [b].652 """,653 load_system=True)654 assert_true("a([b], []).", e)655def test_assert_other_module():656 e = Engine()657 assert_true("assert(m:f(a)).", e)658 assert len(e.modulewrapper.modules) == 2659 assert_true("m:f(a).", e)660 prolog_raises("existence_error(_, _)", "f(a)", e)661 assert_true("module(m).", e)662 assert_true("f(a).", e)663 assert_true("module(user).", e)664 prolog_raises("existence_error(_, _)", "f(a)", e)665def test_asserta_other_module():666 e = Engine()667 assert_true("asserta(m:f(a)).", e)668 assert len(e.modulewrapper.modules) == 2669 assert_true("m:f(a).", e)670 prolog_raises("existence_error(_, _)", "f(a)", e)671 assert_true("module(m).", e)672 assert_true("f(a).", e)673 assert_true("module(user).", e)674 prolog_raises("existence_error(_, _)", "f(a)", e)675def test_retract_other_module():676 e = get_engine("",677 m = """678 :- module(m, []).679 f(a).680 f(b).681 """)682 assert_true("m:f(a), m:f(b).", e)683 assert_true("retract(m:f(a)).", e)684 assert_false("retract(m:f(a)).", e)685 assert_false("m:f(a).", e)686 assert_true("m:f(b).", e)687 assert_true("retract(m:f(b)).", e)688 prolog_raises("existence_error(_, _)", "f(b)", e)689def test_abolish_other_module():690 e = get_engine("",691 m = """692 :- module(m, []).693 f(a).694 f(b).695 g(c).696 """)697 assert_true("m:f(a), m:f(b), m:g(c).", e)698 assert_true("abolish(m:f/1).", e)699 prolog_raises("existence_error(_, _)", "m:f(X)", e)700 assert_true("m:g(c).", e)701 assert_true("abolish(m:g/1).", e)702 prolog_raises("existence_error(_, _)", "m:g(c)", e)703 assert_true("abolish(m:g/1).", e)704def test_assert_rule_into_other_module():705 e = get_engine("""706 :- use_module(m).707 """,708 m = """709 :- module(m, []).710 """)711 assert_true("m:assert(a).", e)712 assert_true("m:a.", e)713 prolog_raises("existence_error(_, _)", "a", e)714 assert_true("m:assert(user:b).", e)715 assert_true("b.", e)716 prolog_raises("existence_error(_, _)", "m:b", e)717def test_assert_rule_into_other_module_2():718 e = get_engine("""719 :- use_module(m).720 """,721 m = """722 :- module(m, [f/1]).723 f(Rule) :-724 assert(Rule).725 """)726 assert_true("f(g(a)).", e)727 prolog_raises("existence_error(_, _)", "g(a)", e)728 assert_true("m:g(a).", e)729def test_retract_rule_from_other_module():730 e = get_engine("""731 :- use_module(m).732 """,733 m = """734 :- module(m, []).735 a.736 """)737 assert_false("retract(a).", e)738 assert_true("m:retract(a).", e)739 assert_false("m:retract(a).", e)740def test_abolish_from_other_module():741 e = get_engine("""742 :- use_module(m).743 """,744 m = """745 :- module(m, []).746 a.747 """)748 assert_true("m:abolish(a/0).", e)749 prolog_raises("existence_error(_, _)", "m:a", e)750def test_call_other_module():751 e = get_engine("",752 m = """753 :- module(m, []).754 f(a).755 """)756 assert_true("call(m:f(X)), X = a.", e)757 prolog_raises("existence_error(_, _)", "f(X)", e)758def test_once_other_module():759 e = get_engine("",760 m = """761 :- module(m, []).762 f(a).763 """)764 assert_true("once(m:f(X)), X = a.", e)765 prolog_raises("existence_error(_, _)", "f(X)", e)766def test_file_parsing():767 e = get_engine("""768 :- use_module(m).769 :- use_module(m).770 """,771 create_files=True,772 m = """773 :- module(m, []).774 :- assert(user:f(a)).775 """)776 assert_true("findall(X, f(X), [a]).", e)777def test_this_module():778 e = get_engine(":- module(a).")779 assert_true("this_module(user).")780 assert_true("this_module(a).", e)781 assert_true("this_module(X), X == user.")782def test_this_module_2():783 e = get_engine("""784 :- use_module(m).785 g(X) :- f(X).786 """,787 m = """788 :- module(m, [f/1]).789 f(X) :-790 this_module(X).791 """,792 n = """793 :- module(n).794 :- use_module(m).795 g(X) :- f(X).796 """)797 assert_true("g(X), X == user.", e)798def test_meta_function():799 e = get_engine("""800 :- meta_predicate f(:), g('?'), h(0).801 f(X) :- X = foobar.802 a(FooBar).803 """)804 user = e.modulewrapper.modules["user"]805 assert len(user.functions) == 4806 for key in user.functions.keys():807 assert key.name in ["f","g","h","a"]808 assert key.numargs == 1809 if key.name in ["f", "g", "h"]:810 assert user.functions[key].meta_args != []811 else:812 assert not user.functions[key].meta_args == []813def test_meta_predicate():814 e = get_engine("""815 :- use_module(mod).816 """,817 mod = """818 :- module(mod, [test/1, test2/2]).819 :- meta_predicate test(:), test2(:, -).820 test(X) :- X = _:_.821 test2(M:A, M:A).822 """)823 824 assert_true("test(blar).", e)825 assert_false("test2(f, f).", e)826 assert_true("test2(f, user:f).", e)827 assert_true("test2(f(A, B, C), user:f(A, B, C)).", e)828def test_meta_predicate_2():829 e = get_engine("",830 m = """831 :- module(m, [f/4]).832 :- meta_predicate f(:, :, '?', '?').833 f(M1:G1, M2:G2, M1, M2).834 """)835 # setup836 assert_true("module(x).", e)837 assert_true("use_module(m).", e)838 # real tests839 assert_true("f(a, b, x, x).", e)840 assert_false("f(1:a, 2:b, x, x).", e)841 assert_true("f(1:a, 2:b, 1, 2).", e)842 assert_true("m:f(a, b, m, m).", e)843 assert_false("m:f(1:a, 2:b, m, m).", e)844 assert_true("m:f(1:a, 2:b, 1, 2).", e)845def test_meta_predicate_prefixing():846 e = get_engine("""847 :- use_module(mod).848 """,849 mod = """850 :- module(mod, [f/2]).851 :- meta_predicate f(:, '?').852 f(X, M) :-853 X = M:_,854 M =.. [A|_],855 A \== ':'.856 """)857 assert_true("f(a, user).", e)858 assert_true("f(user:a, user).", e)859 assert_true("mod:f(a, mod).", e)860 assert_true("mod:f(user:a, user).", e)861 assert_true("mod:f(mod:user:a, mod).", e)862def test_meta_predicate_module_chaining():863 m1 = "m1.pl"864 m2 = "m2.pl"865 m3 = "m3.pl"866 try:867 create_file(m1, """868 :- module(m1, [f/2]).869 :- meta_predicate f(:, '?').870 f(M:_, M).871 """)872 create_file(m2, """873 :- module(m2, [g/2]).874 :- use_module(m1).875 g(X, Y) :- f(X, Y).876 """)877 create_file(m3, """878 :- module(m3, [h/2]).879 :- meta_predicate h(:, ?).880 :- use_module(m2).881 h(X, Y) :- g(X, Y).882 """)883 884 e = get_engine("""885 :- use_module(m2).886 :- use_module(m3).887 """)888 assert_true("g(a, X), X == m2.", e)889 assert_true("g(user:a, X), X == user.", e)890 assert_true("h(a, X), X == user.", e)891 assert_true("m3:h(a, X), X == m3.", e)892 assert_true("m3:h(user:a, X), X == user.", e)893 finally:894 delete_file(m1)895 delete_file(m2)896 delete_file(m3)897def test_meta_predicate_colon_predicate():898 e = get_engine("""899 :- use_module(m).900 """,901 m = """902 :- module(m, [:/3]).903 :- meta_predicate :(:, :, '?'), :(:, :).904 :(A, B, C) :-905 A = X:_,906 B = Y:_,907 C = (X, Y).908 """)909 assert_true(":(a, blub:b, (user, blub)).", e)910 assert_true(":(1, a:2, (user, a)).", e)911 assert_true(":(a:1.234, 2, (a, user)).", e)912 assert_true(":(a:9999999999999999999999999999999999999999999999999, b:2, (a, b)).", e)913def test_meta_predicate_errors():914 py.test.skip("todo")915 prolog_raises("instantiation_error", "meta_predicate f(X)")916 prolog_raises("instantiation_error", "meta_predicate X")917 prolog_raises("domain_error(_, _)", "meta_predicate f(blub)")918 m = "mod"919 create_file(m, """920 :- module(%s, []).921 :- meta_predicate X.922 """ % m)923 e = Engine()924 try:925 try: # XXX strange behaviour, can't catch926 prolog_raises("instantiation_error", "use_module(%s)" % m)927 except UncaughtError:928 pass929 assert e.modulewrapper.current_module.name == "user"930 finally:931 delete_file(m)932def test_current_module():933 e = get_engine("""934 length([], 0).935 length([_|T], R) :-936 length(T, R1),937 R is R1 + 1.938 """,939 m1 = ":- module(m1, []).",940 m2 = ":- module(m2, []).",941 m3 = ":- module(m3, []).")942 assert_true("current_module(user).", e)943 assert_true("current_module(m1).", e)944 assert_true("current_module(m2).", e)945 assert_true("current_module(m3).", e)946 assert_true("findall(X, current_module(X), L), length(L, 4).", e)947 e = Engine()948 assert_true("findall(X, current_module(X), L), L == [user].", e)949 assert_false("current_module(1).")950 assert_false("current_module(some_strange_thing).")951def test_engine_current_module_after_invalid_import():952 m = "m.pl"953 create_file(m, """954 :- module(m, [f(a)]).955 f(a).956 """)957 e = Engine()958 try:959 try: # XXX strange, prolog_raises does not catch the error960 prolog_raises("type_error(_, _)", "use_module(m)", e)961 except UncaughtError:962 pass963 assert e.modulewrapper.current_module.name == "user"964 finally:965 delete_file(m)966 967def test_importlist_with_not_existing_rule():968 e = Engine()969 m = "mod"970 create_file(m, """971 :- module('%s', [f/1]).972 """ % m)973 try:974 prolog_raises("import_error(mod, 'f/1')", "use_module(%s)" % m, e)975 assert e.modulewrapper.current_module.name == "user"976 finally:977 delete_file(m)978def test_numeric_module():979 prolog_raises("domain_error(_, _)", "assert(:(1, 2))")980 prolog_raises("domain_error(_, _)", "assert(:(1.2, 2.2))")981def test_load_broken_module_twice():982 e = Engine()983 m = "mod"984 create_file(m, """985 :- module(%s, [f/1]).986 """ % m)987 try:988 prolog_raises("import_error(mod, 'f/1')", "use_module('%s')" % m, e)989 assert_true("use_module('%s')." % m, e)990 assert m in e.modulewrapper.modules991 finally:992 delete_file(m)993def test_retract_module_name_is_not_atom():994 assert_false("retract(f(x):f(y)).")995def test_importlist_intersection():996 e = get_engine("""997 :- use_module(m, []).998 """, 999 m = """1000 :- module(m, [f/1]).1001 f(a).1002 g(a).1003 """)1004 prolog_raises("existence_error(procedure, '/'('f', 1))", "f(a)", e)1005 prolog_raises("existence_error(procedure, '/'('g', 1))", "g(a)", e)1006 e = get_engine("""1007 :- use_module(m, [g/1]).1008 """, 1009 m = """1010 :- module(m, [f/1]).1011 f(a).1012 g(a).1013 """)1014 prolog_raises("existence_error(procedure, '/'('f', 1))", "f(a)", e)1015 prolog_raises("existence_error(procedure, '/'('g', 1))", "g(a)", e)1016 e = get_engine("""1017 :- use_module(m, [f/1, g/1]).1018 """, 1019 m = """1020 :- module(m, [f/1]).1021 f(a).1022 g(a).1023 """)1024 assert_true("f(a).", e)1025 prolog_raises("existence_error(procedure, '/'('g', 1))", "g(a)", e)1026def test_modules_without_module_declaration():1027 m1 = "mod1"1028 m2 = "mod2"1029 create_file(m1, """1030 :- use_module(%s).1031 f(a).1032 """ % m2)1033 create_file(m2, """1034 :- use_module(%s).1035 g(a).1036 """ % m1)1037 e = Engine()1038 try:1039 assert_true("use_module(%s)." % m1, e)1040 assert_true("f(a).", e)1041 assert_true("g(a).", e)1042 assert len(e.modulewrapper.modules) == 11043 assert "user" in e.modulewrapper.modules1044 finally:1045 delete_file(m1)...

Full Screen

Full Screen

module_organize.py

Source:module_organize.py Github

copy

Full Screen

...218 "", "", "", whole_libs, call_libs )219 f = open(mk_file_path, "w")220 f.write(file_content)221 f.close()222 def gen_compiled_module(self, module_name):223 print("generate compiled module : %s" % module_name)224 module_info = self.modules_info[module_name]225 # copy the include files226 if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):227 for include_cfg in module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]:228 excopy.copy_files_with_config(include_cfg, self.src_root, self.dst_root)229 # handle the process for android230 self.handle_for_android(module_info)231 # handle the process for win32232 self.handle_for_win32(module_info)233 # handle the process for ios and mac234 self.handle_for_ios_mac(module_info)235 # handle the lua-bindings236 if module_info.has_key(ModuleOrganizer.KEY_MODULE_LUA_BINDINGS):237 self.handle_for_lua_bindings(module_name)238 def gen_prebuilt_module(self, module_name):239 print("generate prebuilt module : %s" % module_name)240 module_info = self.modules_info[module_name]241 if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXCLUDE):242 exclude = module_info[ModuleOrganizer.KEY_MODULE_EXCLUDE]243 else:244 exclude = []245 if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):246 include = module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]247 else:248 include = []249 copy_cfg = {250 "from" : module_info[ModuleOrganizer.KEY_MODULE_FROM_DIR],251 "to": module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]252 }253 if len(include) > 0:254 copy_cfg["include"] = include255 elif len(exclude) > 0:256 copy_cfg["exclude"] = exclude257 excopy.copy_files_with_config(copy_cfg, self.src_root, self.dst_root)258 def export_modules_info(self):259 export_file_path = os.path.join(self.dst_root, ModuleOrganizer.EXPORT_MODULE_INFO_FILE_NAME)260 export_info = {}261 for module_name in self.modules_info.keys():262 module_info = self.modules_info[module_name]263 dst_info = {}264 for key in ModuleOrganizer.EXPORT_KEYS:265 if module_info.has_key(key):266 dst_info[key] = module_info[key]267 export_info[module_name] = dst_info268 outfile = open(export_file_path, "w")269 json.dump(export_info, outfile, sort_keys = True, indent = 4)270 outfile.close()271 def gen_modules(self):272 if os.path.exists(self.dst_root):273 shutil.rmtree(self.dst_root)274 for module in self.modules_info.keys():275 module_info = self.modules_info[module]276 if module_info[ModuleOrganizer.KEY_MODULE_IS_COMPILED]:277 self.gen_compiled_module(module)278 else:279 self.gen_prebuilt_module(module)280 # copy the module config file to dst root281 self.export_modules_info()282 # restore the version of engine283 src_file = os.path.join(self.src_root, ModuleOrganizer.VERSION_SRC_FILE)284 ver = ""285 f = open(src_file)286 import re287 for line in f.readlines():288 match = re.match(r".*return[ \t]*\"(.*)\";", line)289 if match:290 ver = match.group(1)291 break292 f.close()293 if len(ver) <= 0:...

Full Screen

Full Screen

writeFiles.py

Source:writeFiles.py Github

copy

Full Screen

1# !/usr/bin/python2import sys3directorySeparationCharacter="/"4maxDirectoryDepth=995##6# Extract a module name from a given file name.7#8# Calculates the name of the directory to which the given file name belongs.9# restricted to a directory nesting depth of maxDirectoryDepth.10#11# E.g.: 12# extractModuleNameFromFileName("a/b/c/d.h", i) = "a/b/c" for all i in [3,infinity]13# extractModuleNameFromFileName("a/b/c/d.h", 2) = "a/b"14# extractModuleNameFromFileName("a/b/c/d.h", 1) = "a"15#16# extractModuleNameFromFileName("a.h", i) = "/" for all i17#18# Assumptions: 19# +Directory separation is provided by the "/" character.20# 21# +The root level of the directory structure is "/"22# +The final part of a given file name (as separated in directories)23# is considered to be a file when it contains a "."24#25# E.g.:26# /a/b.[?]* is considered to be a file b.[?]* within a directory a within /27#28# @maxDirectoryDepth - allows to configure the extraction of module names29# Has no effect when smaller then 1.30#31# @returns The name of the module to which the file belongs.32##33def extractModuleName(fileName):34 global directorySeparationCharacter35 global maxDirectoryDepth36 37 substringIndicatingNameAsFile="."38 39 # by default every file is contained40 # in the root module41 moduleName=directorySeparationCharacter42 43 # if the file belongs to a directory44 if ( "/" in fileName):45 fileNameParts = fileName.split(directorySeparationCharacter)46 47 # by default a file in a directory48 # belongs to the root directory module49 moduleName=fileNameParts[0] 50 # if the file is located at least51 # one directory deep52 if (len(fileNameParts) > 1 ):53 lastDirectoryIndex=min(len(fileNameParts)-1,maxDirectoryDepth-1)54 55 if lastDirectoryIndex > 0:56 index=157 while ( index < lastDirectoryIndex ):58 moduleName += directorySeparationCharacter + fileNameParts[index]59 index += 160 61 lastFileNamePart = fileNameParts[lastDirectoryIndex]62 moduleNameIsFileName = (substringIndicatingNameAsFile in lastFileNamePart)63 #if not(moduleNameIsFileName):64 # moduleName += directorySeparationCharacter + lastFileNamePart65 66 return moduleName67##68# Adds the parents of the given module name to the modules list, in case these69# are not contained yet. E.g.,:70# addParentModules("/a/b/c",[]) will result in the addition of (in order):71# +"/"72# +"/a"73# +"/a/b"74#75# @moduleName - string representing a module name. Should not be a file name.76# I.e., every part of the module name should be a valid module.77# moduleName should start with a directorySeparationCharacter78##79def addParentModules(moduleName, modules, moduleBelongsToModule):80 if moduleName == "":81 return82 83 # first add the root module84 if not(directorySeparationCharacter in modules):85 parentModuleName = directorySeparationCharacter86 modules.append(parentModuleName)87 print moduleName88 childModules = moduleName.rstrip(directorySeparationCharacter).split(directorySeparationCharacter)89 # it always holds that childModules[0] = 90 print childModules91 # e.g. /X92 if len(childModules) == 2:93 # ensure that the module will have the root as94 # its parent95 childModuleId = modules.index(moduleName)+196 # retrieve the module id of the root97 parentModuleId = modules.index(directorySeparationCharacter)+198 if not(childModuleId in moduleBelongsToModule):99 moduleBelongsToModule[childModuleId] = parentModuleId100 # e.g. /X/Y/Z101 elif len(childModules) > 2:102 childModules = childModules[1:len(childModules)] # ['X','Y']103 104 childModulePath=directorySeparationCharacter105 for childModule in childModules:106 parentModulePath = childModulePath # initially /107 108 if ( childModulePath != directorySeparationCharacter ):109 childModulePath += directorySeparationCharacter110 childModulePath += childModule # e.g., /X, /X/Y111 if not(childModulePath in modules):112 modules.append(childModulePath)113 childModuleId = modules.index(childModulePath)+1114 if not(childModuleId in moduleBelongsToModule):115 parentModuleId = modules.index(parentModulePath)+1116 moduleBelongsToModule[childModuleId] = parentModuleId117def addFile(line, files, modules, fileBelongsToModule, moduleBelongsToModule):118 sourceFile = line.split("\"")[1]119 if ( not(sourceFile in files) ):120 files.append(sourceFile)121 fileId = files.index(sourceFile)+1122 moduleName = extractModuleName(sourceFile)123 124 if not(moduleName.startswith(directorySeparationCharacter)):125 moduleName = directorySeparationCharacter + moduleName126 if not(moduleName in modules):127 modules.append(moduleName)128 moduleId = modules.index(moduleName)+1129 fileBelongsToModule[fileId] = moduleId130 addParentModules(moduleName, modules, moduleBelongsToModule)131## main132if __name__ == "__main__":133 if len(sys.argv) < 2:134 print "Usage:",sys.argv[0],"cdif-input-file"135 sys.exit(64)136 137 input_file=sys.argv[1]138 input_file=open(input_file, 'r')139 140 # first build up the relations141 files = [] # sourceFileName (fileId = index(sourceFileName)+1)142 modules=[] # moduleName (moduleId = index(moduleName)+1)143 fileBelongsToModule={} # fileId x moduleId144 moduleBelongsToModule={} # childModuleId x parentModuleId145 146 for line in input_file:147 line = line.strip()148 149 # if the line is the start of an entity150 if line.startswith("(SourceFile FM"):151 for line in input_file:152 line = line.strip()153 if line.startswith("(uniqueName "):154 addFile(line, files, modules, fileBelongsToModule, moduleBelongsToModule)155 elif line.startswith(")"):156 break157 158 input_file.close()159 # then write everything to file160 modules_file=open("modulesWithIDs.txt", 'w') 161 for moduleName in modules:162 moduleId = `modules.index(moduleName)+1`163 moduleInfo = moduleId + "\t\"" + moduleName + "\"\n";164 modules_file.write(moduleInfo)165 modules_file.close()166 moduleBelongsToModule_file=open("moduleBelongsToModule.txt", 'w')167 moduleIndices = moduleBelongsToModule.keys()168 moduleIndices.sort()169 for childModuleId in moduleIndices:170 parentModuleId = moduleBelongsToModule[childModuleId]171 moduleBelongsToModuleInfo = `childModuleId` + "\t" + `parentModuleId` + "\n"172 moduleBelongsToModule_file.write(moduleBelongsToModuleInfo)173 moduleBelongsToModule_file.close()174 files_file=open("filesWithIDs.txt", 'w')175 for fileName in files:176 fileId = `files.index(fileName)+1`177 fileInfo = fileId + "\t\"" + fileName + "\"\n";178 files_file.write(fileInfo)179 files_file.close()180 181 fileBelongsToModule_file=open("fileBelongsToModule.txt", 'w')182 fileIndices = fileBelongsToModule.keys()183 fileIndices.sort()184 for fileId in fileIndices:185 parentModuleId = fileBelongsToModule[fileId]186 fileBelongsToModuleInfo = `fileId` + "\t" + `parentModuleId` + "\n"187 fileBelongsToModule_file.write(fileBelongsToModuleInfo)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11});12import { NgModule } from '@angular/core';13import { AppComponent } from './app.component';14@NgModule({15})16export class AppModule {}17import { Component } from '@angular/core';18@Component({19})20export class AppComponent {}21import { MockBuilder, MockRender } from 'ng-mocks';22import { AppModule } from './app.module';23import { AppComponent } from './app.component';24describe('AppComponent', () => {25 beforeEach(() => MockBuilder(AppComponent, AppModule));26 it('should create the app', () => {27 const fixture = MockRender(AppComponent);28 const app = fixture.point.componentInstance;29 expect(app).toBeTruthy();30 });31});32h1 {33 color: red;34}35h1 {36 color: red;37}38h1 {39 color: red;40}41import { Component } from '@angular/core';42@Component({43})44export class AppComponent {}45import { MockBuilder, MockRender } from 'ng-mocks';46import { AppModule } from './app.module';47import { AppComponent } from './app.component';48describe('AppComponent', () => {49 beforeEach(() => MockBuilder(AppComponent, AppModule));50 it('should create the app', () => {51 const fixture = MockRender(AppComponent);52 const app = fixture.point.componentInstance;53 expect(app).toBeTruthy();54 });

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { TestBed } from '@angular/core/testing';3import { MockBuilder, MockRender } from 'ng-mocks';4import { TestBed } from '@angular/core/testing';5import { MockBuilder, MockRender } from 'ng-mocks';6import { TestBed } from '@angular/core/testing';7import { MockBuilder, MockRender } from 'ng-mocks';8import { TestBed } from '@angular/core/testing';9import { MockBuilder, MockRender } from 'ng-mocks';10import { TestBed } from '@angular/core/testing';11import { MockBuilder, MockRender } from 'ng-mocks';12import { TestBed } from '@angular/core/testing';13import { MockBuilder, MockRender } from 'ng-mocks';14import { TestBed } from '@angular/core/testing';15import { MockBuilder, MockRender } from 'ng-mocks';16import { TestBed } from '@angular/core/testing';17import { MockBuilder, MockRender } from 'ng-mocks';18import { TestBed } from '@angular/core/testing';19import { MockBuilder, MockRender } from 'ng-mocks';20import { TestBed } from '@angular/core/testing';21import { MockBuilder, MockRender } from 'ng-mocks';22import { TestBed } from '@angular/core/testing';23import { MockBuilder, MockRender } from 'ng-mocks';24import { TestBed } from '@angular/core/testing';25import { MockBuilder, MockRender } from 'ng-mocks';26import { TestBed } from '@angular/core/testing';27import { MockBuilder, MockRender } from 'ng-mocks';28import { TestBed } from '@angular/core/testing';29import { MockBuilder, MockRender } from

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { TestBed } from '@angular/core/testing';3import { MockModule } from 'ng-mocks';4describe('App', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 beforeEach(() => MockRender(AppComponent));7 it('should work', () => {8 expect(true).toEqual(true);9 });10});11import { MockBuilder, MockRender } from 'ng-mocks';12import { TestBed } from '@angular/core/testing';13import { MockModule } from 'ng-mocks';14describe('AppComponent', () => {15 beforeEach(() => MockBuilder(AppComponent, AppModule));16 beforeEach(() => MockRender(AppComponent));17 it('should work', () => {18 expect(true).toEqual(true);19 });20});21import { MockBuilder, MockRender } from 'ng-mocks';22import { TestBed } from '@angular/core/testing';23import { MockModule } from 'ng-mocks';24describe('AppModule', () => {25 beforeEach(() => MockBuilder(AppComponent, AppModule));26 beforeEach(() => MockRender(AppComponent));27 it('should work', () => {28 expect(true).toEqual(true);29 });30});31import { MockBuilder, MockRender } from 'ng-mocks';32import { TestBed } from '@angular/core/testing';33import { MockModule } from 'ng-mocks';34describe('AppService', () => {35 beforeEach(() => MockBuilder(AppComponent, AppModule));36 beforeEach(() => MockRender(AppComponent));37 it('should work', () => {38 expect(true).toEqual(true);39 });40});41import { Component } from '@angular/core';42import { AppService } from './app.service';43@Component({44})45export class AppComponent {46 title = 'app';47 constructor(private appService: AppService) {}

Full Screen

Using AI Code Generation

copy

Full Screen

1const ngMocks = require('ng-mocks');2const ngMocks = require('ng-mocks');3describe('AppComponent', () => {4 beforeEach(() => ngMocks.module('app'));5 it('should create the app', () => {6 const fixture = ngMocks.create(AppComponent);7 const app = fixture.componentInstance;8 expect(app).toBeTruthy();9 });10});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { mockModule } from 'ng-mocks';2import { MyModule } from './my-module';3describe('test', () => {4 beforeEach(() => mockModule(MyModule));5});6import { NgModule } from '@angular/core';7import { MyComponent } from './my-component';8@NgModule({9})10export class MyModule {}

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful